diff --git a/CMakeLists.txt b/CMakeLists.txt index e16f0c2845..88ccc058c5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -219,3 +219,10 @@ install(FILES completions/dolphin.zsh RENAME _dolphin DESTINATION ${KDE_INSTALL_ feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) +include(KDEClangFormat) +# add clang-format target +file(GLOB_RECURSE ALL_CLANG_FORMAT_SOURCE_FILES *.cpp *.h *.c) +kde_clang_format(${ALL_CLANG_FORMAT_SOURCE_FILES}) + +include(KDEGitCommitHooks) +kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT) diff --git a/src/dbusinterface.cpp b/src/dbusinterface.cpp index 8d5bf7645b..5e3285c1e3 100644 --- a/src/dbusinterface.cpp +++ b/src/dbusinterface.cpp @@ -5,8 +5,8 @@ */ #include "dbusinterface.h" -#include "global.h" #include "dolphin_generalsettings.h" +#include "global.h" #include #include @@ -14,42 +14,43 @@ #include #include -DBusInterface::DBusInterface() : - QObject() +DBusInterface::DBusInterface() + : QObject() { - QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/freedesktop/FileManager1"), this, - QDBusConnection::ExportScriptableContents | QDBusConnection::ExportAdaptors); + QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/freedesktop/FileManager1"), + this, + QDBusConnection::ExportScriptableContents | QDBusConnection::ExportAdaptors); QDBusConnectionInterface *sessionInterface = QDBusConnection::sessionBus().interface(); if (sessionInterface) { sessionInterface->registerService(QStringLiteral("org.freedesktop.FileManager1"), QDBusConnectionInterface::QueueService); } } -void DBusInterface::ShowFolders(const QStringList& uriList, const QString& startUpId) +void DBusInterface::ShowFolders(const QStringList &uriList, const QString &startUpId) { const QList urls = Dolphin::validateUris(uriList); if (urls.isEmpty()) { return; } const auto serviceName = isDaemon() ? QString() : QStringLiteral("org.kde.dolphin-%1").arg(QCoreApplication::applicationPid()); - if(!Dolphin::attachToExistingInstance(urls, false, GeneralSettings::splitView(), serviceName, startUpId)) { + if (!Dolphin::attachToExistingInstance(urls, false, GeneralSettings::splitView(), serviceName, startUpId)) { Dolphin::openNewWindow(urls); } } -void DBusInterface::ShowItems(const QStringList& uriList, const QString& startUpId) +void DBusInterface::ShowItems(const QStringList &uriList, const QString &startUpId) { const QList urls = Dolphin::validateUris(uriList); if (urls.isEmpty()) { return; } const auto serviceName = isDaemon() ? QString() : QStringLiteral("org.kde.dolphin-%1").arg(QCoreApplication::applicationPid()); - if(!Dolphin::attachToExistingInstance(urls, true, GeneralSettings::splitView(), serviceName, startUpId)) { + if (!Dolphin::attachToExistingInstance(urls, true, GeneralSettings::splitView(), serviceName, startUpId)) { Dolphin::openNewWindow(urls, nullptr, Dolphin::OpenNewWindowFlag::Select); }; } -void DBusInterface::ShowItemProperties(const QStringList& uriList, const QString& startUpId) +void DBusInterface::ShowItemProperties(const QStringList &uriList, const QString &startUpId) { const QList urls = Dolphin::validateUris(uriList); if (!urls.isEmpty()) { diff --git a/src/dbusinterface.h b/src/dbusinterface.h index 66659e9762..fc465cba0f 100644 --- a/src/dbusinterface.h +++ b/src/dbusinterface.h @@ -16,9 +16,9 @@ class DBusInterface : QObject public: DBusInterface(); - Q_SCRIPTABLE void ShowFolders(const QStringList& uriList, const QString& startUpId); - Q_SCRIPTABLE void ShowItems(const QStringList& uriList, const QString& startUpId); - Q_SCRIPTABLE void ShowItemProperties(const QStringList& uriList, const QString& startUpId); + Q_SCRIPTABLE void ShowFolders(const QStringList &uriList, const QString &startUpId); + Q_SCRIPTABLE void ShowItems(const QStringList &uriList, const QString &startUpId); + Q_SCRIPTABLE void ShowItemProperties(const QStringList &uriList, const QString &startUpId); Q_SCRIPTABLE void SortOrderForUrl(const QString &url, QString &role, QString &order); diff --git a/src/dolphinbookmarkhandler.cpp b/src/dolphinbookmarkhandler.cpp index 6335aec4fe..9b4b1bbbd1 100644 --- a/src/dolphinbookmarkhandler.cpp +++ b/src/dolphinbookmarkhandler.cpp @@ -14,15 +14,11 @@ #include #include -DolphinBookmarkHandler::DolphinBookmarkHandler(DolphinMainWindow *mainWindow, - KActionCollection* collection, - QMenu* menu, - QObject* parent) : - QObject(parent), - m_mainWindow(mainWindow) +DolphinBookmarkHandler::DolphinBookmarkHandler(DolphinMainWindow *mainWindow, KActionCollection *collection, QMenu *menu, QObject *parent) + : QObject(parent) + , m_mainWindow(mainWindow) { - QString bookmarksFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, - QStringLiteral("kfile/bookmarks.xml")); + QString bookmarksFile = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("kfile/bookmarks.xml")); if (bookmarksFile.isEmpty()) { QString genericDataLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); if (genericDataLocation.isEmpty()) { @@ -79,43 +75,45 @@ QList DolphinBookmarkHandler::currentBookmarkLis bool DolphinBookmarkHandler::enableOption(KBookmarkOwner::BookmarkOption option) const { switch (option) { - case BookmarkOption::ShowAddBookmark: return true; - case BookmarkOption::ShowEditBookmark: return true; + case BookmarkOption::ShowAddBookmark: + return true; + case BookmarkOption::ShowEditBookmark: + return true; } return false; } -void DolphinBookmarkHandler::openBookmark(const KBookmark& bookmark, Qt::MouseButtons, Qt::KeyboardModifiers) +void DolphinBookmarkHandler::openBookmark(const KBookmark &bookmark, Qt::MouseButtons, Qt::KeyboardModifiers) { m_mainWindow->changeUrl(bookmark.url()); } -void DolphinBookmarkHandler::openFolderinTabs(const KBookmarkGroup& bookmarkGroup) +void DolphinBookmarkHandler::openFolderinTabs(const KBookmarkGroup &bookmarkGroup) { m_mainWindow->openDirectories(bookmarkGroup.groupUrlList(), false); } -void DolphinBookmarkHandler::openInNewTab(const KBookmark& bookmark) +void DolphinBookmarkHandler::openInNewTab(const KBookmark &bookmark) { m_mainWindow->openNewTab(bookmark.url()); } -void DolphinBookmarkHandler::openInNewWindow(const KBookmark& bookmark) +void DolphinBookmarkHandler::openInNewWindow(const KBookmark &bookmark) { Dolphin::openNewWindow({bookmark.url()}, m_mainWindow); } -QString DolphinBookmarkHandler::title(DolphinViewContainer* viewContainer) +QString DolphinBookmarkHandler::title(DolphinViewContainer *viewContainer) { return viewContainer->caption(); } -QUrl DolphinBookmarkHandler::url(DolphinViewContainer* viewContainer) +QUrl DolphinBookmarkHandler::url(DolphinViewContainer *viewContainer) { return viewContainer->url(); } -QString DolphinBookmarkHandler::icon(DolphinViewContainer* viewContainer) +QString DolphinBookmarkHandler::icon(DolphinViewContainer *viewContainer) { return KIO::iconNameForUrl(viewContainer->url()); } diff --git a/src/dolphinbookmarkhandler.h b/src/dolphinbookmarkhandler.h index a750905007..a40c026754 100644 --- a/src/dolphinbookmarkhandler.h +++ b/src/dolphinbookmarkhandler.h @@ -35,11 +35,12 @@ private: void openFolderinTabs(const KBookmarkGroup &bookmarkGroup) override; void openInNewTab(const KBookmark &bookmark) override; void openInNewWindow(const KBookmark &bookmark) override; - static QString title(DolphinViewContainer* viewContainer); - static QUrl url(DolphinViewContainer* viewContainer); - static QString icon(DolphinViewContainer* viewContainer); + static QString title(DolphinViewContainer *viewContainer); + static QUrl url(DolphinViewContainer *viewContainer); + static QString icon(DolphinViewContainer *viewContainer); + private: - DolphinMainWindow* m_mainWindow; + DolphinMainWindow *m_mainWindow; KBookmarkManager *m_bookmarkManager; QScopedPointer m_bookmarkMenu; }; diff --git a/src/dolphincontextmenu.cpp b/src/dolphincontextmenu.cpp index fbc0d75d2a..94fed18721 100644 --- a/src/dolphincontextmenu.cpp +++ b/src/dolphincontextmenu.cpp @@ -6,8 +6,8 @@ #include "dolphincontextmenu.h" -#include "dolphin_generalsettings.h" #include "dolphin_contextmenusettings.h" +#include "dolphin_generalsettings.h" #include "dolphinmainwindow.h" #include "dolphinnewfilemenu.h" #include "dolphinplacesmodelsingleton.h" @@ -35,22 +35,22 @@ #include #include -DolphinContextMenu::DolphinContextMenu(DolphinMainWindow* parent, - const KFileItem& fileInfo, +DolphinContextMenu::DolphinContextMenu(DolphinMainWindow *parent, + const KFileItem &fileInfo, const KFileItemList &selectedItems, - const QUrl& baseUrl, - KFileItemActions *fileItemActions) : - QMenu(parent), - m_mainWindow(parent), - m_fileInfo(fileInfo), - m_baseUrl(baseUrl), - m_baseFileItem(nullptr), - m_selectedItems(selectedItems), - m_selectedItemsProperties(nullptr), - m_context(NoContext), - m_copyToMenu(parent), - m_removeAction(nullptr), - m_fileItemActions(fileItemActions) + const QUrl &baseUrl, + KFileItemActions *fileItemActions) + : QMenu(parent) + , m_mainWindow(parent) + , m_fileInfo(fileInfo) + , m_baseUrl(baseUrl) + , m_baseFileItem(nullptr) + , m_selectedItems(selectedItems) + , m_selectedItemsProperties(nullptr) + , m_context(NoContext) + , m_copyToMenu(parent) + , m_removeAction(nullptr) + , m_fileItemActions(fileItemActions) { QApplication::instance()->installEventFilter(this); @@ -67,8 +67,7 @@ DolphinContextMenu::~DolphinContextMenu() void DolphinContextMenu::addAllActions() { - static_cast(m_mainWindow->actionCollection()-> - action(QStringLiteral("hamburger_menu")))->addToMenu(this); + static_cast(m_mainWindow->actionCollection()->action(QStringLiteral("hamburger_menu")))->addToMenu(this); // get the context information const auto scheme = m_baseUrl.scheme(); @@ -99,12 +98,12 @@ void DolphinContextMenu::addAllActions() } } -bool DolphinContextMenu::eventFilter(QObject* object, QEvent* event) +bool DolphinContextMenu::eventFilter(QObject *object, QEvent *event) { Q_UNUSED(object) - if(event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { - QKeyEvent* keyEvent = static_cast(event); + if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { + QKeyEvent *keyEvent = static_cast(event); if (m_removeAction && keyEvent->key() == Qt::Key_Shift) { if (event->type() == QEvent::KeyPress) { @@ -122,12 +121,12 @@ void DolphinContextMenu::addTrashContextMenu() { Q_ASSERT(m_context & TrashContext); - QAction *emptyTrashAction = addAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"), [this](){ + QAction *emptyTrashAction = addAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"), [this]() { Trash::empty(m_mainWindow); }); emptyTrashAction->setEnabled(!Trash::isEmpty()); - QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); + QAction *propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); addAction(propertiesAction); } @@ -136,7 +135,7 @@ void DolphinContextMenu::addTrashItemContextMenu() Q_ASSERT(m_context & TrashContext); Q_ASSERT(m_context & ItemContext); - addAction(QIcon::fromTheme("restoration"), i18nc("@action:inmenu", "Restore"), [this](){ + addAction(QIcon::fromTheme("restoration"), i18nc("@action:inmenu", "Restore"), [this]() { QList selectedUrls; selectedUrls.reserve(m_selectedItems.count()); for (const KFileItem &item : qAsConst(m_selectedItems)) { @@ -148,17 +147,17 @@ void DolphinContextMenu::addTrashItemContextMenu() job->uiDelegate()->setAutoErrorHandlingEnabled(true); }); - QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)); + QAction *deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)); addAction(deleteAction); - QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); + QAction *propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); addAction(propertiesAction); } void DolphinContextMenu::addDirectoryItemContextMenu() { // insert 'Open in new window' and 'Open in new tab' entries - const KFileItemListProperties& selectedItemsProps = selectedItemsProperties(); + const KFileItemListProperties &selectedItemsProps = selectedItemsProperties(); if (ContextMenuSettings::showOpenInNewTab()) { addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab"))); } @@ -170,7 +169,7 @@ void DolphinContextMenu::addDirectoryItemContextMenu() addOpenWithActions(); // set up 'Create New' menu - DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow); + DolphinNewFileMenu *newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow); newFileMenu->checkUpToDate(); #if KIO_VERSION >= QT_VERSION_CHECK(5, 97, 0) newFileMenu->setWorkingDirectory(m_fileInfo.url()); @@ -181,7 +180,7 @@ void DolphinContextMenu::addDirectoryItemContextMenu() connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater); connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater); - QMenu* menu = newFileMenu->menu(); + QMenu *menu = newFileMenu->menu(); menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New")); menu->setIcon(QIcon::fromTheme(QStringLiteral("list-add"))); addMenu(menu); @@ -193,7 +192,7 @@ void DolphinContextMenu::addItemContextMenu() { Q_ASSERT(!m_fileInfo.isNull()); - const KFileItemListProperties& selectedItemsProps = selectedItemsProperties(); + const KFileItemListProperties &selectedItemsProps = selectedItemsProperties(); m_fileItemActions->setItemListProperties(selectedItemsProps); @@ -204,26 +203,17 @@ void DolphinContextMenu::addItemContextMenu() } else if (m_context & TimelineContext || m_context & SearchContext) { addOpenWithActions(); - addAction(QIcon::fromTheme(QStringLiteral("document-open-folder")), - i18nc("@action:inmenu", - "Open Path"), - [this](){ + addAction(QIcon::fromTheme(QStringLiteral("document-open-folder")), i18nc("@action:inmenu", "Open Path"), [this]() { m_mainWindow->changeUrl(KIO::upUrl(m_fileInfo.url())); m_mainWindow->activeViewContainer()->view()->markUrlsAsSelected({m_fileInfo.url()}); m_mainWindow->activeViewContainer()->view()->markUrlAsCurrent(m_fileInfo.url()); }); - addAction(QIcon::fromTheme(QStringLiteral("window-new")), - i18nc("@action:inmenu", - "Open Path in New Window"), - [this](){ + addAction(QIcon::fromTheme(QStringLiteral("window-new")), i18nc("@action:inmenu", "Open Path in New Window"), [this]() { Dolphin::openNewWindow({m_fileInfo.url()}, m_mainWindow, Dolphin::OpenNewWindowFlag::Select); }); - addAction(QIcon::fromTheme(QStringLiteral("tab-new")), - i18nc("@action:inmenu", - "Open Path in New Tab"), - [this](){ + addAction(QIcon::fromTheme(QStringLiteral("tab-new")), i18nc("@action:inmenu", "Open Path in New Tab"), [this]() { m_mainWindow->openNewTab(KIO::upUrl(m_fileInfo.url())); }); @@ -240,7 +230,7 @@ void DolphinContextMenu::addItemContextMenu() // multiple files bool selectionHasOnlyDirs = true; for (const auto &item : qAsConst(m_selectedItems)) { - const QUrl& url = DolphinView::openItemAsFolderUrl(item); + const QUrl &url = DolphinView::openItemAsFolderUrl(item); if (url.isEmpty()) { selectionHasOnlyDirs = false; break; @@ -269,7 +259,7 @@ void DolphinContextMenu::addItemContextMenu() // insert 'Properties...' entry addSeparator(); - QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); + QAction *propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); addAction(propertiesAction); } @@ -279,7 +269,7 @@ void DolphinContextMenu::addViewportContextMenu() m_fileItemActions->setItemListProperties(baseUrlProperties); // Set up and insert 'Create New' menu - KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu(); + KNewFileMenu *newFileMenu = m_mainWindow->newFileMenu(); newFileMenu->checkUpToDate(); #if KIO_VERSION >= QT_VERSION_CHECK(5, 97, 0) newFileMenu->setWorkingDirectory(m_baseUrl); @@ -292,14 +282,13 @@ void DolphinContextMenu::addViewportContextMenu() // use cases for this, such as opening an empty dir in Kate or VSCode or something addOpenWithActions(); - QAction* pasteAction = createPasteAction(); + QAction *pasteAction = createPasteAction(); if (pasteAction) { addAction(pasteAction); } // Insert 'Add to Places' entry if it's not already in the places panel - if (ContextMenuSettings::showAddToPlaces() && - !placeExists(m_mainWindow->activeViewContainer()->url())) { + if (ContextMenuSettings::showAddToPlaces() && !placeExists(m_mainWindow->activeViewContainer()->url())) { addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places"))); } addSeparator(); @@ -319,23 +308,23 @@ void DolphinContextMenu::addViewportContextMenu() addSeparator(); - QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); + QAction *propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties")); addAction(propertiesAction); } -void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& properties) +void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties &properties) { - const KActionCollection* collection = m_mainWindow->actionCollection(); + const KActionCollection *collection = m_mainWindow->actionCollection(); // Insert 'Cut', 'Copy', 'Copy Location' and 'Paste' addAction(collection->action(KStandardAction::name(KStandardAction::Cut))); addAction(collection->action(KStandardAction::name(KStandardAction::Copy))); if (ContextMenuSettings::showCopyLocation()) { - QAction* copyPathAction = collection->action(QString("copy_location")); + QAction *copyPathAction = collection->action(QString("copy_location")); copyPathAction->setEnabled(m_selectedItems.size() == 1); addAction(copyPathAction); } - QAction* pasteAction = createPasteAction(); + QAction *pasteAction = createPasteAction(); if (pasteAction) { addAction(pasteAction); } @@ -349,20 +338,15 @@ void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& addAction(collection->action(KStandardAction::name(KStandardAction::RenameFile))); // Insert 'Add to Places' entry if appropriate - if (ContextMenuSettings::showAddToPlaces() && - m_selectedItems.count() == 1 && - m_fileInfo.isDir() && - !placeExists(m_fileInfo.url())) { + if (ContextMenuSettings::showAddToPlaces() && m_selectedItems.count() == 1 && m_fileInfo.isDir() && !placeExists(m_fileInfo.url())) { addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places"))); } addSeparator(); // Insert 'Move to Trash' and/or 'Delete' - const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) || - !properties.isLocal()); - const bool showMoveToTrashAction = (properties.isLocal() && - properties.supportsMoving()); + const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) || !properties.isLocal()); + const bool showMoveToTrashAction = (properties.isLocal() && properties.supportsMoving()); if (showDeleteAction && showMoveToTrashAction) { delete m_removeAction; @@ -380,18 +364,18 @@ void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& } } -bool DolphinContextMenu::placeExists(const QUrl& url) const +bool DolphinContextMenu::placeExists(const QUrl &url) const { - const KFilePlacesModel* placesModel = DolphinPlacesModelSingleton::instance().placesModel(); + const KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel(); - const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, url, 1, Qt::MatchExactly); + const auto &matchedPlaces = placesModel->match(placesModel->index(0, 0), KFilePlacesModel::UrlRole, url, 1, Qt::MatchExactly); return !matchedPlaces.isEmpty(); } -QAction* DolphinContextMenu::createPasteAction() +QAction *DolphinContextMenu::createPasteAction() { - QAction* action = nullptr; + QAction *action = nullptr; KFileItem destItem; if (!m_fileInfo.isNull() && m_selectedItems.count() <= 1) { destItem = m_fileInfo; @@ -417,7 +401,7 @@ QAction* DolphinContextMenu::createPasteAction() return action; } -KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const +KFileItemListProperties &DolphinContextMenu::selectedItemsProperties() const { if (!m_selectedItemsProperties) { m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems); @@ -428,7 +412,7 @@ KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const KFileItem DolphinContextMenu::baseFileItem() { if (!m_baseFileItem) { - const DolphinView* view = m_mainWindow->activeViewContainer()->view(); + const DolphinView *view = m_mainWindow->activeViewContainer()->view(); KFileItem baseItem = view->rootItem(); if (baseItem.isNull() || baseItem.url() != m_baseUrl) { m_baseFileItem = new KFileItem(m_baseUrl); @@ -455,11 +439,10 @@ void DolphinContextMenu::addAdditionalActions(const KFileItemListProperties &pro } m_fileItemActions->addActionsTo(this, KFileItemActions::MenuActionSource::All, additionalActions); - const DolphinView* view = m_mainWindow->activeViewContainer()->view(); - const QList versionControlActions = view->versionControlActions(m_selectedItems); + const DolphinView *view = m_mainWindow->activeViewContainer()->view(); + const QList versionControlActions = view->versionControlActions(m_selectedItems); if (!versionControlActions.isEmpty()) { addActions(versionControlActions); addSeparator(); } } - diff --git a/src/dolphincontextmenu.h b/src/dolphincontextmenu.h index 56ba673143..04b0697d0a 100644 --- a/src/dolphincontextmenu.h +++ b/src/dolphincontextmenu.h @@ -47,16 +47,16 @@ public: * @baseUrl Base URL of the viewport where the context menu * should be opened. */ - DolphinContextMenu(DolphinMainWindow* parent, - const KFileItem& fileInfo, + DolphinContextMenu(DolphinMainWindow *parent, + const KFileItem &fileInfo, const KFileItemList &selectedItems, - const QUrl& baseUrl, + const QUrl &baseUrl, KFileItemActions *fileItemActions); ~DolphinContextMenu() override; protected: - bool eventFilter(QObject* object, QEvent* event) override; + bool eventFilter(QObject *object, QEvent *event) override; private: /** @@ -71,13 +71,13 @@ private: void addItemContextMenu(); void addViewportContextMenu(); - void insertDefaultItemActions(const KFileItemListProperties&); + void insertDefaultItemActions(const KFileItemListProperties &); - bool placeExists(const QUrl& url) const; + bool placeExists(const QUrl &url) const; - QAction* createPasteAction(); + QAction *createPasteAction(); - KFileItemListProperties& selectedItemsProperties() const; + KFileItemListProperties &selectedItemsProperties() const; /** * Returns the file item for m_baseUrl. @@ -95,18 +95,16 @@ private: void addAdditionalActions(const KFileItemListProperties &props); private: - struct Entry - { + struct Entry { int type; QString name; - QString filePath; // empty for separator + QString filePath; // empty for separator QString templatePath; // same as filePath for template QString icon; QString comment; }; - enum ContextType - { + enum ContextType { NoContext = 0, ItemContext = 1, TrashContext = 2, @@ -114,23 +112,22 @@ private: SearchContext = 8, }; - DolphinMainWindow* m_mainWindow; + DolphinMainWindow *m_mainWindow; KFileItem m_fileInfo; QUrl m_baseUrl; - KFileItem* m_baseFileItem; /// File item for m_baseUrl + KFileItem *m_baseFileItem; /// File item for m_baseUrl KFileItemList m_selectedItems; - mutable KFileItemListProperties* m_selectedItemsProperties; + mutable KFileItemListProperties *m_selectedItemsProperties; int m_context; KFileCopyToMenu m_copyToMenu; - DolphinRemoveAction* m_removeAction; // Action that represents either 'Move To Trash' or 'Delete' + DolphinRemoveAction *m_removeAction; // Action that represents either 'Move To Trash' or 'Delete' void addDirectoryItemContextMenu(); KFileItemActions *m_fileItemActions; - }; #endif diff --git a/src/dolphindockwidget.cpp b/src/dolphindockwidget.cpp index 16f5755837..d4c05eb5c0 100644 --- a/src/dolphindockwidget.cpp +++ b/src/dolphindockwidget.cpp @@ -8,22 +8,28 @@ #include -namespace { - // Disable the 'Floatable' feature, i.e., the possibility to drag the - // dock widget out of the main window. This works around problems like - // https://bugs.kde.org/show_bug.cgi?id=288629 - // https://bugs.kde.org/show_bug.cgi?id=322299 - const QDockWidget::DockWidgetFeatures DefaultDockWidgetFeatures = QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable; +namespace +{ +// Disable the 'Floatable' feature, i.e., the possibility to drag the +// dock widget out of the main window. This works around problems like +// https://bugs.kde.org/show_bug.cgi?id=288629 +// https://bugs.kde.org/show_bug.cgi?id=322299 +const QDockWidget::DockWidgetFeatures DefaultDockWidgetFeatures = QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable; } - // Empty titlebar for the dock widgets when "Lock Layout" has been activated. +// Empty titlebar for the dock widgets when "Lock Layout" has been activated. class DolphinDockTitleBar : public QWidget { Q_OBJECT public: - explicit DolphinDockTitleBar(QWidget* parent = nullptr) : QWidget(parent) {} - ~DolphinDockTitleBar() override {} + explicit DolphinDockTitleBar(QWidget *parent = nullptr) + : QWidget(parent) + { + } + ~DolphinDockTitleBar() override + { + } QSize minimumSizeHint() const override { @@ -37,10 +43,10 @@ public: } }; -DolphinDockWidget::DolphinDockWidget(const QString& title, QWidget* parent, Qt::WindowFlags flags) : - QDockWidget(title, parent, flags), - m_locked(false), - m_dockTitleBar(nullptr) +DolphinDockWidget::DolphinDockWidget(const QString &title, QWidget *parent, Qt::WindowFlags flags) + : QDockWidget(title, parent, flags) + , m_locked(false) + , m_dockTitleBar(nullptr) { setFeatures(DefaultDockWidgetFeatures); } diff --git a/src/dolphindockwidget.h b/src/dolphindockwidget.h index eaf66e45ac..114a11b55f 100644 --- a/src/dolphindockwidget.h +++ b/src/dolphindockwidget.h @@ -17,7 +17,7 @@ class DolphinDockWidget : public QDockWidget Q_OBJECT public: - explicit DolphinDockWidget(const QString& title = QString(), QWidget* parent = nullptr, Qt::WindowFlags flags = {}); + explicit DolphinDockWidget(const QString &title = QString(), QWidget *parent = nullptr, Qt::WindowFlags flags = {}); ~DolphinDockWidget() override; /** @@ -29,7 +29,7 @@ public: private: bool m_locked; - QWidget* m_dockTitleBar; + QWidget *m_dockTitleBar; }; #endif diff --git a/src/dolphinmainwindow.cpp b/src/dolphinmainwindow.cpp index d69514b7a3..5d31a55dc4 100644 --- a/src/dolphinmainwindow.cpp +++ b/src/dolphinmainwindow.cpp @@ -8,18 +8,19 @@ #include "dolphinmainwindow.h" -#include "dolphinmainwindowadaptor.h" -#include "global.h" +#include "dolphin_generalsettings.h" #include "dolphinbookmarkhandler.h" -#include "dolphindockwidget.h" #include "dolphincontextmenu.h" +#include "dolphindockwidget.h" +#include "dolphinmainwindowadaptor.h" #include "dolphinnavigatorswidgetaction.h" #include "dolphinnewfilemenu.h" -#include "dolphinrecenttabsmenu.h" #include "dolphinplacesmodelsingleton.h" +#include "dolphinrecenttabsmenu.h" +#include "dolphintabpage.h" #include "dolphinurlnavigatorscontroller.h" #include "dolphinviewcontainer.h" -#include "dolphintabpage.h" +#include "global.h" #include "middleclickactioneventfilter.h" #include "panels/folders/folderspanel.h" #include "panels/places/placespanel.h" @@ -27,12 +28,11 @@ #include "selectionmode/actiontexthelper.h" #include "settings/dolphinsettingsdialog.h" #include "statusbar/dolphinstatusbar.h" -#include "views/dolphinviewactionhandler.h" +#include "views/dolphinnewfilemenuobserver.h" #include "views/dolphinremoteencoding.h" +#include "views/dolphinviewactionhandler.h" #include "views/draganddrophelper.h" #include "views/viewproperties.h" -#include "views/dolphinnewfilemenuobserver.h" -#include "dolphin_generalsettings.h" #include #include @@ -70,8 +70,8 @@ #include #include -#include #include +#include #include #include @@ -88,60 +88,56 @@ #include #include -namespace { - // Used for GeneralSettings::version() to determine whether - // an updated version of Dolphin is running, so as to migrate - // removed/renamed ...etc config entries; increment it in such - // cases - const int CurrentDolphinVersion = 202; - // The maximum number of entries in the back/forward popup menu - const int MaxNumberOfNavigationentries = 12; - // The maximum number of "Activate Tab" shortcuts - const int MaxActivateTabShortcuts = 9; +namespace +{ +// Used for GeneralSettings::version() to determine whether +// an updated version of Dolphin is running, so as to migrate +// removed/renamed ...etc config entries; increment it in such +// cases +const int CurrentDolphinVersion = 202; +// The maximum number of entries in the back/forward popup menu +const int MaxNumberOfNavigationentries = 12; +// The maximum number of "Activate Tab" shortcuts +const int MaxActivateTabShortcuts = 9; } -DolphinMainWindow::DolphinMainWindow() : - KXmlGuiWindow(nullptr), - m_newFileMenu(nullptr), - m_tabWidget(nullptr), - m_activeViewContainer(nullptr), - m_actionHandler(nullptr), - m_remoteEncoding(nullptr), - m_settingsDialog(), - m_bookmarkHandler(nullptr), - m_lastHandleUrlOpenJob(nullptr), - m_terminalPanel(nullptr), - m_placesPanel(nullptr), - m_tearDownFromPlacesRequested(false), - m_backAction(nullptr), - m_forwardAction(nullptr) +DolphinMainWindow::DolphinMainWindow() + : KXmlGuiWindow(nullptr) + , m_newFileMenu(nullptr) + , m_tabWidget(nullptr) + , m_activeViewContainer(nullptr) + , m_actionHandler(nullptr) + , m_remoteEncoding(nullptr) + , m_settingsDialog() + , m_bookmarkHandler(nullptr) + , m_lastHandleUrlOpenJob(nullptr) + , m_terminalPanel(nullptr) + , m_placesPanel(nullptr) + , m_tearDownFromPlacesRequested(false) + , m_backAction(nullptr) + , m_forwardAction(nullptr) { Q_INIT_RESOURCE(dolphin); new MainWindowAdaptor(this); #ifndef Q_OS_WIN - setWindowFlags(Qt::WindowContextHelpButtonHint); + setWindowFlags(Qt::WindowContextHelpButtonHint); #endif setComponentName(QStringLiteral("dolphin"), QGuiApplication::applicationDisplayName()); setObjectName(QStringLiteral("Dolphin#")); setStateConfigGroup("State"); - connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage, - this, &DolphinMainWindow::showErrorMessage); + connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage, this, &DolphinMainWindow::showErrorMessage); - KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self(); + KIO::FileUndoManager *undoManager = KIO::FileUndoManager::self(); undoManager->setUiInterface(new UndoUiInterface()); - connect(undoManager, &KIO::FileUndoManager::undoAvailable, - this, &DolphinMainWindow::slotUndoAvailable); - connect(undoManager, &KIO::FileUndoManager::undoTextChanged, - this, &DolphinMainWindow::slotUndoTextChanged); - connect(undoManager, &KIO::FileUndoManager::jobRecordingStarted, - this, &DolphinMainWindow::clearStatusBar); - connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, - this, &DolphinMainWindow::showCommand); + connect(undoManager, &KIO::FileUndoManager::undoAvailable, this, &DolphinMainWindow::slotUndoAvailable); + connect(undoManager, &KIO::FileUndoManager::undoTextChanged, this, &DolphinMainWindow::slotUndoTextChanged); + connect(undoManager, &KIO::FileUndoManager::jobRecordingStarted, this, &DolphinMainWindow::clearStatusBar); + connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinMainWindow::showCommand); const bool firstRun = (GeneralSettings::version() < 200); if (firstRun) { @@ -154,12 +150,9 @@ DolphinMainWindow::DolphinMainWindow() : actionCollection()->addAction(QStringLiteral("url_navigators"), navigatorsWidgetAction); m_tabWidget = new DolphinTabWidget(navigatorsWidgetAction, this); m_tabWidget->setObjectName("tabWidget"); - connect(m_tabWidget, &DolphinTabWidget::activeViewChanged, - this, &DolphinMainWindow::activeViewChanged); - connect(m_tabWidget, &DolphinTabWidget::tabCountChanged, - this, &DolphinMainWindow::tabCountChanged); - connect(m_tabWidget, &DolphinTabWidget::currentUrlChanged, - this, &DolphinMainWindow::updateWindowTitle); + connect(m_tabWidget, &DolphinTabWidget::activeViewChanged, this, &DolphinMainWindow::activeViewChanged); + connect(m_tabWidget, &DolphinTabWidget::tabCountChanged, this, &DolphinMainWindow::tabCountChanged); + connect(m_tabWidget, &DolphinTabWidget::currentUrlChanged, this, &DolphinMainWindow::updateWindowTitle); setCentralWidget(m_tabWidget); m_actionTextHelper = new SelectionMode::ActionTextHelper(this); @@ -171,19 +164,17 @@ DolphinMainWindow::DolphinMainWindow() : connect(m_actionHandler, &DolphinViewActionHandler::selectionModeChangeTriggered, this, &DolphinMainWindow::slotSetSelectionMode); m_remoteEncoding = new DolphinRemoteEncoding(this, m_actionHandler); - connect(this, &DolphinMainWindow::urlChanged, - m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl); + connect(this, &DolphinMainWindow::urlChanged, m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl); setupDockWidgets(); setupGUI(Save | Create | ToolBar); stateChanged(QStringLiteral("new_file")); - QClipboard* clipboard = QApplication::clipboard(); - connect(clipboard, &QClipboard::dataChanged, - this, &DolphinMainWindow::updatePasteAction); + QClipboard *clipboard = QApplication::clipboard(); + connect(clipboard, &QClipboard::dataChanged, this, &DolphinMainWindow::updatePasteAction); - QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); + QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); toggleFilterBarAction->setChecked(GeneralSettings::filterBar()); if (firstRun) { @@ -191,15 +182,13 @@ DolphinMainWindow::DolphinMainWindow() : } const bool showMenu = !menuBar()->isHidden(); - QAction* showMenuBarAction = actionCollection()->action(KStandardAction::name(KStandardAction::ShowMenubar)); - showMenuBarAction->setChecked(showMenu); // workaround for bug #171080 + QAction *showMenuBarAction = actionCollection()->action(KStandardAction::name(KStandardAction::ShowMenubar)); + showMenuBarAction->setChecked(showMenu); // workaround for bug #171080 - auto hamburgerMenu = static_cast(actionCollection()->action( - KStandardAction::name(KStandardAction::HamburgerMenu))); + auto hamburgerMenu = static_cast(actionCollection()->action(KStandardAction::name(KStandardAction::HamburgerMenu))); hamburgerMenu->setMenuBar(menuBar()); hamburgerMenu->setShowMenuBarAction(showMenuBarAction); - connect(hamburgerMenu, &KHamburgerMenu::aboutToShowMenu, - this, &DolphinMainWindow::updateHamburgerMenu); + connect(hamburgerMenu, &KHamburgerMenu::aboutToShowMenu, this, &DolphinMainWindow::updateHamburgerMenu); hamburgerMenu->hideActionsOf(toolBar()); if (GeneralSettings::version() < 201 && !toolBar()->actions().contains(hamburgerMenu)) { addHamburgerMenuToToolbar(); @@ -223,8 +212,7 @@ DolphinMainWindow::DolphinMainWindow() : showErrorMessage(errorMessage); }); - connect(GeneralSettings::self(), &GeneralSettings::splitViewChanged, - this, &DolphinMainWindow::slotSplitViewChanged); + connect(GeneralSettings::self(), &GeneralSettings::splitViewChanged, this, &DolphinMainWindow::slotSplitViewChanged); } DolphinMainWindow::~DolphinMainWindow() @@ -233,9 +221,9 @@ DolphinMainWindow::~DolphinMainWindow() disconnect(QGuiApplication::clipboard(), &QClipboard::dataChanged, this, &DolphinMainWindow::updatePasteAction); } -QVector DolphinMainWindow::viewContainers() const +QVector DolphinMainWindow::viewContainers() const { - QVector viewContainers; + QVector viewContainers; for (int i = 0; i < m_tabWidget->count(); ++i) { DolphinTabPage *tabPage = m_tabWidget->tabPageAt(i); @@ -248,17 +236,17 @@ QVector DolphinMainWindow::viewContainers() const return viewContainers; } -void DolphinMainWindow::openDirectories(const QList& dirs, bool splitView) +void DolphinMainWindow::openDirectories(const QList &dirs, bool splitView) { m_tabWidget->openDirectories(dirs, splitView); } -void DolphinMainWindow::openDirectories(const QStringList& dirs, bool splitView) +void DolphinMainWindow::openDirectories(const QStringList &dirs, bool splitView) { openDirectories(QUrl::fromStringList(dirs), splitView); } -void DolphinMainWindow::openFiles(const QList& files, bool splitView) +void DolphinMainWindow::openFiles(const QList &files, bool splitView) { m_tabWidget->openFiles(files, splitView); } @@ -277,7 +265,7 @@ bool DolphinMainWindow::isInformationPanelEnabled() const #endif } -void DolphinMainWindow::openFiles(const QStringList& files, bool splitView) +void DolphinMainWindow::openFiles(const QStringList &files, bool splitView) { openFiles(QUrl::fromStringList(files), splitView); } @@ -302,7 +290,7 @@ bool DolphinMainWindow::isActiveWindow() void DolphinMainWindow::showCommand(CommandType command) { - DolphinStatusBar* statusBar = m_activeViewContainer->statusBar(); + DolphinStatusBar *statusBar = m_activeViewContainer->statusBar(); switch (command) { case KIO::FileUndoManager::Copy: statusBar->setText(i18nc("@info:status", "Successfully copied.")); @@ -352,7 +340,7 @@ void DolphinMainWindow::changeUrl(const QUrl &url) Q_EMIT urlChanged(url); } -void DolphinMainWindow::slotTerminalDirectoryChanged(const QUrl& url) +void DolphinMainWindow::slotTerminalDirectoryChanged(const QUrl &url) { if (m_tearDownFromPlacesRequested && url == QUrl::fromLocalFile(QDir::homePath())) { m_placesPanel->proceedWithTearDown(); @@ -366,18 +354,17 @@ void DolphinMainWindow::slotTerminalDirectoryChanged(const QUrl& url) void DolphinMainWindow::slotEditableStateChanged(bool editable) { - KToggleAction* editableLocationAction = - static_cast(actionCollection()->action(QStringLiteral("editable_location"))); + KToggleAction *editableLocationAction = static_cast(actionCollection()->action(QStringLiteral("editable_location"))); editableLocationAction->setChecked(editable); } -void DolphinMainWindow::slotSelectionChanged(const KFileItemList& selection) +void DolphinMainWindow::slotSelectionChanged(const KFileItemList &selection) { updateFileAndEditActions(); const int selectedUrlsCount = m_tabWidget->currentTabPage()->selectedItemsCount(); - QAction* compareFilesAction = actionCollection()->action(QStringLiteral("compare_files")); + QAction *compareFilesAction = actionCollection()->action(QStringLiteral("compare_files")); if (selectedUrlsCount == 2) { compareFilesAction->setEnabled(isKompareInstalled()); } else { @@ -392,25 +379,24 @@ void DolphinMainWindow::updateHistory() const KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigatorInternalWithHistory(); const int index = urlNavigator->historyIndex(); - QAction* backAction = actionCollection()->action(KStandardAction::name(KStandardAction::Back)); + QAction *backAction = actionCollection()->action(KStandardAction::name(KStandardAction::Back)); if (backAction) { backAction->setToolTip(i18nc("@info", "Go back")); backAction->setWhatsThis(i18nc("@info:whatsthis go back", "Return to the previously viewed folder.")); backAction->setEnabled(index < urlNavigator->historySize() - 1); } - QAction* forwardAction = actionCollection()->action(KStandardAction::name(KStandardAction::Forward)); + QAction *forwardAction = actionCollection()->action(KStandardAction::name(KStandardAction::Forward)); if (forwardAction) { forwardAction->setToolTip(i18nc("@info", "Go forward")); - forwardAction->setWhatsThis(xi18nc("@info:whatsthis go forward", - "This undoes a Go|Back action.")); + forwardAction->setWhatsThis(xi18nc("@info:whatsthis go forward", "This undoes a Go|Back action.")); forwardAction->setEnabled(index > 0); } } void DolphinMainWindow::updateFilterBarAction(bool show) { - QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); + QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); toggleFilterBarAction->setChecked(show); } @@ -453,7 +439,7 @@ void DolphinMainWindow::addToPlaces() } } -void DolphinMainWindow::openNewTab(const QUrl& url) +void DolphinMainWindow::openNewTab(const QUrl &url) { m_tabWidget->openNewTab(url, QUrl()); } @@ -476,11 +462,11 @@ void DolphinMainWindow::slotSplitViewChanged() void DolphinMainWindow::openInNewTab() { - const KFileItemList& list = m_activeViewContainer->view()->selectedItems(); + const KFileItemList &list = m_activeViewContainer->view()->selectedItems(); bool tabCreated = false; - for (const KFileItem& item : list) { - const QUrl& url = DolphinView::openItemAsFolderUrl(item); + for (const KFileItem &item : list) { + const QUrl &url = DolphinView::openItemAsFolderUrl(item); if (!url.isEmpty()) { openNewTab(url); tabCreated = true; @@ -502,7 +488,7 @@ void DolphinMainWindow::openInNewWindow() if (list.isEmpty()) { newWindowUrl = m_activeViewContainer->url(); } else if (list.count() == 1) { - const KFileItem& item = list.first(); + const KFileItem &item = list.first(); newWindowUrl = DolphinView::openItemAsFolderUrl(item); } @@ -522,12 +508,11 @@ void DolphinMainWindow::showTarget() if (QFileInfo::exists(linkDestination)) { KIO::highlightInFileManager({QUrl::fromLocalFile(linkDestination).adjusted(QUrl::StripTrailingSlash)}); } else { - m_activeViewContainer->showMessage(xi18nc("@info", "Could not access %1.", linkDestination), - DolphinViewContainer::Warning); + m_activeViewContainer->showMessage(xi18nc("@info", "Could not access %1.", linkDestination), DolphinViewContainer::Warning); } } -void DolphinMainWindow::showEvent(QShowEvent* event) +void DolphinMainWindow::showEvent(QShowEvent *event) { KXmlGuiWindow::showEvent(event); @@ -536,7 +521,7 @@ void DolphinMainWindow::showEvent(QShowEvent* event) } } -void DolphinMainWindow::closeEvent(QCloseEvent* event) +void DolphinMainWindow::closeEvent(QCloseEvent *event) { // Find out if Dolphin is closed directly by the user or // by the session manager because the session is closed @@ -545,10 +530,7 @@ void DolphinMainWindow::closeEvent(QCloseEvent* event) closedByUser = false; } - if (m_tabWidget->count() > 1 - && GeneralSettings::confirmClosingMultipleTabs() - && !GeneralSettings::rememberOpenedTabs() - && closedByUser) { + if (m_tabWidget->count() > 1 && GeneralSettings::confirmClosingMultipleTabs() && !GeneralSettings::rememberOpenedTabs() && closedByUser) { // Ask the user if he really wants to quit and close all tabs. // Open a confirmation dialog with 3 buttons: // QDialogButtonBox::Yes -> Quit @@ -557,8 +539,10 @@ void DolphinMainWindow::closeEvent(QCloseEvent* event) QDialog *dialog = new QDialog(this, Qt::Dialog); dialog->setWindowTitle(i18nc("@title:window", "Confirmation")); dialog->setModal(true); - QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel); - KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), KGuiItem(i18nc("@action:button 'Quit Dolphin' button", "&Quit %1", QGuiApplication::applicationDisplayName()), QIcon::fromTheme(QStringLiteral("application-exit")))); + QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel); + KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), + KGuiItem(i18nc("@action:button 'Quit Dolphin' button", "&Quit %1", QGuiApplication::applicationDisplayName()), + QIcon::fromTheme(QStringLiteral("application-exit")))); KGuiItem::assign(buttons->button(QDialogButtonBox::No), KGuiItem(i18n("C&lose Current Tab"), QIcon::fromTheme(QStringLiteral("tab-close")))); KGuiItem::assign(buttons->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel()); buttons->button(QDialogButtonBox::Yes)->setDefault(true); @@ -566,29 +550,29 @@ void DolphinMainWindow::closeEvent(QCloseEvent* event) bool doNotAskAgainCheckboxResult = false; const auto result = KMessageBox::createKMessageBox(dialog, - buttons, - QMessageBox::Warning, - i18n("You have multiple tabs open in this window, are you sure you want to quit?"), - QStringList(), - i18n("Do not ask again"), - &doNotAskAgainCheckboxResult, - KMessageBox::Notify); + buttons, + QMessageBox::Warning, + i18n("You have multiple tabs open in this window, are you sure you want to quit?"), + QStringList(), + i18n("Do not ask again"), + &doNotAskAgainCheckboxResult, + KMessageBox::Notify); if (doNotAskAgainCheckboxResult) { GeneralSettings::setConfirmClosingMultipleTabs(false); } switch (result) { - case QDialogButtonBox::Yes: - // Quit - break; - case QDialogButtonBox::No: - // Close only the current tab - m_tabWidget->closeTab(); - Q_FALLTHROUGH(); - default: - event->ignore(); - return; + case QDialogButtonBox::Yes: + // Quit + break; + case QDialogButtonBox::No: + // Close only the current tab + m_tabWidget->closeTab(); + Q_FALLTHROUGH(); + default: + event->ignore(); + return; } } @@ -608,43 +592,41 @@ void DolphinMainWindow::closeEvent(QCloseEvent* event) QDialogButtonBox *buttons = new QDialogButtonBox(standardButtons); KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), KStandardGuiItem::quit()); if (!m_terminalPanel->isVisible()) { - KGuiItem::assign( - buttons->button(QDialogButtonBox::No), - KGuiItem(i18n("Show &Terminal Panel"), QIcon::fromTheme(QStringLiteral("dialog-scripts")))); + KGuiItem::assign(buttons->button(QDialogButtonBox::No), KGuiItem(i18n("Show &Terminal Panel"), QIcon::fromTheme(QStringLiteral("dialog-scripts")))); } KGuiItem::assign(buttons->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel()); bool doNotAskAgainCheckboxResult = false; const auto result = KMessageBox::createKMessageBox( - dialog, - buttons, - QMessageBox::Warning, - i18n("The program '%1' is still running in the Terminal panel. Are you sure you want to quit?", m_terminalPanel->runningProgramName()), - QStringList(), - i18n("Do not ask again"), - &doNotAskAgainCheckboxResult, - KMessageBox::Dangerous); + dialog, + buttons, + QMessageBox::Warning, + i18n("The program '%1' is still running in the Terminal panel. Are you sure you want to quit?", m_terminalPanel->runningProgramName()), + QStringList(), + i18n("Do not ask again"), + &doNotAskAgainCheckboxResult, + KMessageBox::Dangerous); if (doNotAskAgainCheckboxResult) { GeneralSettings::setConfirmClosingTerminalRunningProgram(false); } switch (result) { - case QDialogButtonBox::Yes: - // Quit - break; - case QDialogButtonBox::No: - actionCollection()->action("show_terminal_panel")->trigger(); - // Do not quit, ignore quit event - Q_FALLTHROUGH(); - default: - event->ignore(); - return; + case QDialogButtonBox::Yes: + // Quit + break; + case QDialogButtonBox::No: + actionCollection()->action("show_terminal_panel")->trigger(); + // Do not quit, ignore quit event + Q_FALLTHROUGH(); + default: + event->ignore(); + return; } } - if (GeneralSettings::rememberOpenedTabs()) { + if (GeneralSettings::rememberOpenedTabs()) { KConfigGui::setSessionConfig(QStringLiteral("dolphin"), QStringLiteral("dolphin")); KConfig *config = KConfigGui::sessionConfig(); saveGlobalProperties(config); @@ -658,12 +640,12 @@ void DolphinMainWindow::closeEvent(QCloseEvent* event) KXmlGuiWindow::closeEvent(event); } -void DolphinMainWindow::saveProperties(KConfigGroup& group) +void DolphinMainWindow::saveProperties(KConfigGroup &group) { m_tabWidget->saveProperties(group); } -void DolphinMainWindow::readProperties(const KConfigGroup& group) +void DolphinMainWindow::readProperties(const KConfigGroup &group) { m_tabWidget->readProperties(group); } @@ -693,22 +675,22 @@ void DolphinMainWindow::quit() close(); } -void DolphinMainWindow::showErrorMessage(const QString& message) +void DolphinMainWindow::showErrorMessage(const QString &message) { m_activeViewContainer->showMessage(message, DolphinViewContainer::Error); } void DolphinMainWindow::slotUndoAvailable(bool available) { - QAction* undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); + QAction *undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); if (undoAction) { undoAction->setEnabled(available); } } -void DolphinMainWindow::slotUndoTextChanged(const QString& text) +void DolphinMainWindow::slotUndoTextChanged(const QString &text) { - QAction* undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); + QAction *undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); if (undoAction) { undoAction->setText(text); } @@ -753,13 +735,13 @@ void DolphinMainWindow::find() void DolphinMainWindow::updateSearchAction() { - QAction* toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search")); + QAction *toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search")); toggleSearchAction->setChecked(m_activeViewContainer->isSearchModeEnabled()); } void DolphinMainWindow::updatePasteAction() { - QAction* pasteAction = actionCollection()->action(KStandardAction::name(KStandardAction::Paste)); + QAction *pasteAction = actionCollection()->action(KStandardAction::name(KStandardAction::Paste)); QPair pasteInfo = m_activeViewContainer->view()->pasteInfo(); pasteAction->setEnabled(pasteInfo.first); pasteAction->setText(pasteInfo.second); @@ -826,7 +808,7 @@ void DolphinMainWindow::slotAboutToShowBackPopupMenu() } } -void DolphinMainWindow::slotGoBack(QAction* action) +void DolphinMainWindow::slotGoBack(QAction *action) { int gotoIndex = action->data().value(); const KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigatorInternalWithHistory(); @@ -835,7 +817,7 @@ void DolphinMainWindow::slotGoBack(QAction* action) } } -void DolphinMainWindow::slotBackForwardActionMiddleClicked(QAction* action) +void DolphinMainWindow::slotBackForwardActionMiddleClicked(QAction *action) { if (action) { const KUrlNavigator *urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory(); @@ -854,7 +836,7 @@ void DolphinMainWindow::slotAboutToShowForwardPopupMenu() } } -void DolphinMainWindow::slotGoForward(QAction* action) +void DolphinMainWindow::slotGoForward(QAction *action) { int gotoIndex = action->data().value(); const KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigatorInternalWithHistory(); @@ -875,10 +857,9 @@ void DolphinMainWindow::selectAll() // if the URL navigator is editable and focused, select the whole // URL instead of all items of the view - KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); - QLineEdit* lineEdit = urlNavigator->editor()->lineEdit(); - const bool selectUrl = urlNavigator->isUrlEditable() && - lineEdit->hasFocus(); + KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigator(); + QLineEdit *lineEdit = urlNavigator->editor()->lineEdit(); + const bool selectUrl = urlNavigator->isUrlEditable() && lineEdit->hasFocus(); if (selectUrl) { lineEdit->selectAll(); } else { @@ -894,7 +875,7 @@ void DolphinMainWindow::invertSelection() void DolphinMainWindow::toggleSplitView() { - DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); + DolphinTabPage *tabPage = m_tabWidget->currentTabPage(); tabPage->setSplitViewEnabled(!tabPage->splitViewEnabled(), WithAnimation); updateViewActions(); @@ -902,7 +883,7 @@ void DolphinMainWindow::toggleSplitView() void DolphinMainWindow::toggleSplitStash() { - DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); + DolphinTabPage *tabPage = m_tabWidget->currentTabPage(); tabPage->setSplitViewEnabled(false, WithAnimation); tabPage->setSplitViewEnabled(true, WithAnimation, QUrl("stash:/")); } @@ -967,7 +948,7 @@ void DolphinMainWindow::toggleFilterBar() const bool checked = !m_activeViewContainer->isFilterBarVisible(); m_activeViewContainer->setFilterBarVisible(checked); - QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); + QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); toggleFilterBarAction->setChecked(checked); } @@ -975,21 +956,19 @@ void DolphinMainWindow::toggleEditLocation() { clearStatusBar(); - QAction* action = actionCollection()->action(QStringLiteral("editable_location")); - KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); + QAction *action = actionCollection()->action(QStringLiteral("editable_location")); + KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigator(); urlNavigator->setUrlEditable(action->isChecked()); } void DolphinMainWindow::replaceLocation() { - KUrlNavigator* navigator = m_activeViewContainer->urlNavigator(); - QLineEdit* lineEdit = navigator->editor()->lineEdit(); + KUrlNavigator *navigator = m_activeViewContainer->urlNavigator(); + QLineEdit *lineEdit = navigator->editor()->lineEdit(); // If the text field currently has focus and everything is selected, // pressing the keyboard shortcut returns the whole thing to breadcrumb mode - if (navigator->isUrlEditable() - && lineEdit->hasFocus() - && lineEdit->selectedText() == lineEdit->text() ) { + if (navigator->isUrlEditable() && lineEdit->hasFocus() && lineEdit->selectedText() == lineEdit->text()) { navigator->setUrlEditable(false); } else { navigator->setUrlEditable(true); @@ -1002,8 +981,8 @@ void DolphinMainWindow::togglePanelLockState() { const bool newLockState = !GeneralSettings::lockPanels(); const auto childrenObjects = children(); - for (QObject* child : childrenObjects) { - DolphinDockWidget* dock = qobject_cast(child); + for (QObject *child : childrenObjects) { + DolphinDockWidget *dock = qobject_cast(child); if (dock) { dock->setLocked(newLockState); } @@ -1050,14 +1029,14 @@ void DolphinMainWindow::goHome() void DolphinMainWindow::goBackInNewTab() { - const KUrlNavigator* urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory(); + const KUrlNavigator *urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory(); const int index = urlNavigator->historyIndex() + 1; openNewTab(urlNavigator->locationUrl(index)); } void DolphinMainWindow::goForwardInNewTab() { - const KUrlNavigator* urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory(); + const KUrlNavigator *urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory(); const int index = urlNavigator->historyIndex() - 1; openNewTab(urlNavigator->locationUrl(index)); } @@ -1105,14 +1084,12 @@ void DolphinMainWindow::toggleShowMenuBar() QPointer DolphinMainWindow::preferredSearchTool() { m_searchTools.clear(); - KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames( - &m_searchTools, { "files-find" }, m_activeViewContainer->url() - ); - QList actions = m_searchTools.actions(); + KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames(&m_searchTools, {"files-find"}, m_activeViewContainer->url()); + QList actions = m_searchTools.actions(); if (actions.isEmpty()) { return nullptr; } - QAction* action = actions.first(); + QAction *action = actions.first(); if (action->isSeparator()) { return nullptr; } @@ -1121,7 +1098,7 @@ QPointer DolphinMainWindow::preferredSearchTool() void DolphinMainWindow::updateOpenPreferredSearchToolAction() { - QAction* openPreferredSearchTool = actionCollection()->action(QStringLiteral("open_preferred_search_tool")); + QAction *openPreferredSearchTool = actionCollection()->action(QStringLiteral("open_preferred_search_tool")); if (!openPreferredSearchTool) { return; } @@ -1159,7 +1136,7 @@ void DolphinMainWindow::openTerminalHere() { QList urls = {}; - for (const KFileItem& item : m_activeViewContainer->view()->selectedItems()) { + for (const KFileItem &item : m_activeViewContainer->view()->selectedItems()) { QUrl url = item.targetUrl(); if (item.isFile()) { url.setPath(QFileInfo(url.path()).absolutePath()); @@ -1176,16 +1153,20 @@ void DolphinMainWindow::openTerminalHere() } if (urls.count() > 5) { - QString question = i18np("Are you sure you want to open 1 terminal window?", - "Are you sure you want to open %1 terminal windows?", urls.count()); + QString question = i18np("Are you sure you want to open 1 terminal window?", "Are you sure you want to open %1 terminal windows?", urls.count()); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - const int answer = KMessageBox::warningTwoActions(this, question, {}, + const int answer = KMessageBox::warningTwoActions( + this, + question, + {}, #else - const int answer = KMessageBox::warningYesNo(this, question, {}, + const int answer = KMessageBox::warningYesNo( + this, + question, + {}, #endif - KGuiItem(i18ncp("@action:button", "Open %1 Terminal", "Open %1 Terminals", urls.count()), - QStringLiteral("utilities-terminal")), - KStandardGuiItem::cancel()); + KGuiItem(i18ncp("@action:button", "Open %1 Terminal", "Open %1 Terminals", urls.count()), QStringLiteral("utilities-terminal")), + KStandardGuiItem::cancel()); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) if (answer != KMessageBox::PrimaryAction) { #else @@ -1195,12 +1176,12 @@ void DolphinMainWindow::openTerminalHere() } } - for (const QUrl& url : urls) { + for (const QUrl &url : urls) { openTerminalJob(url); } } -void DolphinMainWindow::openTerminalJob(const QUrl& url) +void DolphinMainWindow::openTerminalJob(const QUrl &url) { if (url.isLocalFile()) { auto job = new KTerminalLauncherJob(QString()); @@ -1209,7 +1190,7 @@ void DolphinMainWindow::openTerminalJob(const QUrl& url) return; } - // Not a local file, with protocol Class ":local", try stat'ing + // Not a local file, with protocol Class ":local", try stat'ing if (KProtocolInfo::protocolClass(url.scheme()) == QLatin1String(":local")) { KIO::StatJob *job = KIO::mostLocalUrl(url); KJobWidgets::setWindow(job, this); @@ -1236,14 +1217,13 @@ void DolphinMainWindow::openTerminalJob(const QUrl& url) void DolphinMainWindow::editSettings() { if (!m_settingsDialog) { - DolphinViewContainer* container = activeViewContainer(); + DolphinViewContainer *container = activeViewContainer(); container->view()->writeSettings(); const QUrl url = container->url(); - DolphinSettingsDialog* settingsDialog = new DolphinSettingsDialog(url, this, actionCollection()); + DolphinSettingsDialog *settingsDialog = new DolphinSettingsDialog(url, this, actionCollection()); connect(settingsDialog, &DolphinSettingsDialog::settingsChanged, this, &DolphinMainWindow::refreshViews); - connect(settingsDialog, &DolphinSettingsDialog::settingsChanged, - &DolphinUrlNavigatorsController::slotReadSettings); + connect(settingsDialog, &DolphinSettingsDialog::settingsChanged, &DolphinUrlNavigatorsController::slotReadSettings); settingsDialog->setAttribute(Qt::WA_DeleteOnClose); settingsDialog->show(); m_settingsDialog = settingsDialog; @@ -1252,7 +1232,7 @@ void DolphinMainWindow::editSettings() } } -void DolphinMainWindow::handleUrl(const QUrl& url) +void DolphinMainWindow::handleUrl(const QUrl &url) { delete m_lastHandleUrlOpenJob; m_lastHandleUrlOpenJob = nullptr; @@ -1268,14 +1248,13 @@ void DolphinMainWindow::handleUrl(const QUrl& url) #endif m_lastHandleUrlOpenJob->setShowOpenOrExecuteDialog(true); - connect(m_lastHandleUrlOpenJob, &KIO::OpenUrlJob::mimeTypeFound, this, - [this, url](const QString &mimetype) { - if (mimetype == QLatin1String("inode/directory")) { - // If it's a dir, we'll take it from here - m_lastHandleUrlOpenJob->kill(); - m_lastHandleUrlOpenJob = nullptr; - activeViewContainer()->setUrl(url); - } + connect(m_lastHandleUrlOpenJob, &KIO::OpenUrlJob::mimeTypeFound, this, [this, url](const QString &mimetype) { + if (mimetype == QLatin1String("inode/directory")) { + // If it's a dir, we'll take it from here + m_lastHandleUrlOpenJob->kill(); + m_lastHandleUrlOpenJob = nullptr; + activeViewContainer()->setUrl(url); + } }); connect(m_lastHandleUrlOpenJob, &KIO::OpenUrlJob::result, this, [this]() { @@ -1293,10 +1272,7 @@ void DolphinMainWindow::slotWriteStateChanged(bool isFolderWritable) newFileMenu()->setEnabled(isFolderWritable && m_activeViewContainer->url().scheme() != QLatin1String("trash")); } -void DolphinMainWindow::openContextMenu(const QPoint& pos, - const KFileItem& item, - const KFileItemList &selectedItems, - const QUrl& url) +void DolphinMainWindow::openContextMenu(const QPoint &pos, const KFileItem &item, const KFileItemList &selectedItems, const QUrl &url) { QPointer contextMenu = new DolphinContextMenu(this, item, selectedItems, url, &m_fileItemActions); contextMenu.data()->exec(pos); @@ -1319,9 +1295,8 @@ QMenu *DolphinMainWindow::createPopupMenu() void DolphinMainWindow::updateHamburgerMenu() { - KActionCollection* ac = actionCollection(); - auto hamburgerMenu = static_cast( - ac->action(KStandardAction::name(KStandardAction::HamburgerMenu))); + KActionCollection *ac = actionCollection(); + auto hamburgerMenu = static_cast(ac->action(KStandardAction::name(KStandardAction::HamburgerMenu))); auto menu = hamburgerMenu->menu(); if (!menu) { menu = new QMenu(this); @@ -1346,24 +1321,19 @@ void DolphinMainWindow::updateHamburgerMenu() menu->addAction(ac->action(QStringLiteral("go_forward"))); menu->addMenu(m_newFileMenu->menu()); - if (!toolBar()->isVisible() - || !toolbarActions.contains(ac->action(QStringLiteral("toggle_selection_mode_tool_bar"))) - ) { + if (!toolBar()->isVisible() || !toolbarActions.contains(ac->action(QStringLiteral("toggle_selection_mode_tool_bar")))) { menu->addAction(ac->action(QStringLiteral("toggle_selection_mode"))); } menu->addAction(ac->action(QStringLiteral("basic_actions"))); menu->addAction(ac->action(KStandardAction::name(KStandardAction::Undo))); if (!toolBar()->isVisible() || (!toolbarActions.contains(ac->action(QStringLiteral("toggle_search"))) - && !toolbarActions.contains(ac->action(QStringLiteral("open_preferred_search_tool")))) - ) { + && !toolbarActions.contains(ac->action(QStringLiteral("open_preferred_search_tool"))))) { menu->addAction(ac->action(KStandardAction::name(KStandardAction::Find))); // This way a search action will only be added if none of the three available // search actions is present on the toolbar. } - if (!toolBar()->isVisible() - || !toolbarActions.contains(ac->action(QStringLiteral("toggle_filter"))) - ) { + if (!toolBar()->isVisible() || !toolbarActions.contains(ac->action(QStringLiteral("toggle_filter")))) { menu->addAction(ac->action(QStringLiteral("show_filter_bar"))); // This way a filter action will only be added if none of the two available // filter actions is present on the toolbar. @@ -1383,11 +1353,8 @@ void DolphinMainWindow::updateHamburgerMenu() // The third group contains actions to change what one sees in the view // and to change the more general UI. if (!toolBar()->isVisible() - || (!toolbarActions.contains(ac->action(QStringLiteral("icons"))) - && !toolbarActions.contains(ac->action(QStringLiteral("compact"))) - && !toolbarActions.contains(ac->action(QStringLiteral("details"))) - && !toolbarActions.contains(ac->action(QStringLiteral("view_mode")))) - ) { + || (!toolbarActions.contains(ac->action(QStringLiteral("icons"))) && !toolbarActions.contains(ac->action(QStringLiteral("compact"))) + && !toolbarActions.contains(ac->action(QStringLiteral("details"))) && !toolbarActions.contains(ac->action(QStringLiteral("view_mode"))))) { menu->addAction(ac->action(QStringLiteral("view_mode"))); } menu->addAction(ac->action(QStringLiteral("show_hidden_files"))); @@ -1400,8 +1367,7 @@ void DolphinMainWindow::updateHamburgerMenu() // The "Configure" menu is not added to the actionCollection() because there is hardly // a good reason for users to put it on their toolbar. - auto configureMenu = menu->addMenu(QIcon::fromTheme(QStringLiteral("configure")), - i18nc("@action:inmenu menu for configure actions", "Configure")); + auto configureMenu = menu->addMenu(QIcon::fromTheme(QStringLiteral("configure")), i18nc("@action:inmenu menu for configure actions", "Configure")); configureMenu->addAction(ac->action(KStandardAction::name(KStandardAction::SwitchApplicationLanguage))); configureMenu->addAction(ac->action(KStandardAction::name(KStandardAction::KeyBindings))); configureMenu->addAction(ac->action(KStandardAction::name(KStandardAction::ConfigureToolbars))); @@ -1409,9 +1375,9 @@ void DolphinMainWindow::updateHamburgerMenu() hamburgerMenu->hideActionsOf(configureMenu); } -void DolphinMainWindow::slotPlaceActivated(const QUrl& url) +void DolphinMainWindow::slotPlaceActivated(const QUrl &url) { - DolphinViewContainer* view = activeViewContainer(); + DolphinViewContainer *view = activeViewContainer(); if (view->url() == url) { view->clearFilterBar(); // Fixes bug 259382. @@ -1431,15 +1397,15 @@ void DolphinMainWindow::closedTabsCountChanged(unsigned int count) actionCollection()->action(QStringLiteral("undo_close_tab"))->setEnabled(count > 0); } -void DolphinMainWindow::activeViewChanged(DolphinViewContainer* viewContainer) +void DolphinMainWindow::activeViewChanged(DolphinViewContainer *viewContainer) { - DolphinViewContainer* oldViewContainer = m_activeViewContainer; + DolphinViewContainer *oldViewContainer = m_activeViewContainer; Q_ASSERT(viewContainer); m_activeViewContainer = viewContainer; if (oldViewContainer) { - const QAction* toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search")); + const QAction *toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search")); toggleSearchAction->disconnect(oldViewContainer); // Disconnect all signals between the old view container (container, @@ -1447,20 +1413,20 @@ void DolphinMainWindow::activeViewChanged(DolphinViewContainer* viewContainer) oldViewContainer->disconnect(this); oldViewContainer->view()->disconnect(this); oldViewContainer->urlNavigatorInternalWithHistory()->disconnect(this); - auto navigators = static_cast - (actionCollection()->action(QStringLiteral("url_navigators"))); + auto navigators = static_cast(actionCollection()->action(QStringLiteral("url_navigators"))); navigators->primaryUrlNavigator()->disconnect(this); if (auto secondaryUrlNavigator = navigators->secondaryUrlNavigator()) { secondaryUrlNavigator->disconnect(this); } // except the requestItemInfo so that on hover the information panel can still be updated - connect(oldViewContainer->view(), &DolphinView::requestItemInfo, - this, &DolphinMainWindow::requestItemInfo); + connect(oldViewContainer->view(), &DolphinView::requestItemInfo, this, &DolphinMainWindow::requestItemInfo); // Disconnect other slots. - disconnect(nullptr, &DolphinViewContainer::selectionModeChanged, - actionCollection()->action(QStringLiteral("toggle_selection_mode")), &QAction::setChecked); + disconnect(nullptr, + &DolphinViewContainer::selectionModeChanged, + actionCollection()->action(QStringLiteral("toggle_selection_mode")), + &QAction::setChecked); } connectViewSignals(viewContainer); @@ -1497,7 +1463,7 @@ void DolphinMainWindow::updateWindowTitle() } } -void DolphinMainWindow::slotStorageTearDownFromPlacesRequested(const QString& mountPath) +void DolphinMainWindow::slotStorageTearDownFromPlacesRequested(const QString &mountPath) { connect(m_placesPanel, &PlacesPanel::storageTearDownSuccessful, this, [this, mountPath]() { setViewsToHomeIfMountPathOpen(mountPath); @@ -1512,7 +1478,7 @@ void DolphinMainWindow::slotStorageTearDownFromPlacesRequested(const QString& mo } } -void DolphinMainWindow::slotStorageTearDownExternallyRequested(const QString& mountPath) +void DolphinMainWindow::slotStorageTearDownExternallyRequested(const QString &mountPath) { connect(m_placesPanel, &PlacesPanel::storageTearDownSuccessful, this, [this, mountPath]() { setViewsToHomeIfMountPathOpen(mountPath); @@ -1537,9 +1503,9 @@ void DolphinMainWindow::slotKeyBindings() dialog.configure(); } -void DolphinMainWindow::setViewsToHomeIfMountPathOpen(const QString& mountPath) +void DolphinMainWindow::setViewsToHomeIfMountPathOpen(const QString &mountPath) { - const QVector theViewContainers = viewContainers(); + const QVector theViewContainers = viewContainers(); for (DolphinViewContainer *viewContainer : theViewContainers) { if (viewContainer && viewContainer->url().toLocalFile().startsWith(mountPath)) { viewContainer->setUrl(QUrl::fromLocalFile(QDir::homePath())); @@ -1554,110 +1520,121 @@ void DolphinMainWindow::setupActions() // setup 'File' menu m_newFileMenu = new DolphinNewFileMenu(actionCollection(), this); - QMenu* menu = m_newFileMenu->menu(); + QMenu *menu = m_newFileMenu->menu(); menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New")); menu->setIcon(QIcon::fromTheme(QStringLiteral("list-add"))); m_newFileMenu->setPopupMode(QToolButton::InstantPopup); - connect(menu, &QMenu::aboutToShow, - this, &DolphinMainWindow::updateNewMenu); + connect(menu, &QMenu::aboutToShow, this, &DolphinMainWindow::updateNewMenu); - QAction* newWindow = KStandardAction::openNew(this, &DolphinMainWindow::openNewMainWindow, actionCollection()); + QAction *newWindow = KStandardAction::openNew(this, &DolphinMainWindow::openNewMainWindow, actionCollection()); newWindow->setText(i18nc("@action:inmenu File", "New &Window")); newWindow->setToolTip(i18nc("@info", "Open a new Dolphin window")); - newWindow->setWhatsThis(xi18nc("@info:whatsthis", "This opens a new " - "window just like this one with the current location and view." - "You can drag and drop items between windows.")); + newWindow->setWhatsThis(xi18nc("@info:whatsthis", + "This opens a new " + "window just like this one with the current location and view." + "You can drag and drop items between windows.")); newWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); - QAction* newTab = actionCollection()->addAction(QStringLiteral("new_tab")); + QAction *newTab = actionCollection()->addAction(QStringLiteral("new_tab")); newTab->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); newTab->setText(i18nc("@action:inmenu File", "New Tab")); - newTab->setWhatsThis(xi18nc("@info:whatsthis", "This opens a new " - "Tab with the current location and view." - "A tab is an additional view within this window. " - "You can drag and drop items between tabs.")); + newTab->setWhatsThis(xi18nc("@info:whatsthis", + "This opens a new " + "Tab with the current location and view." + "A tab is an additional view within this window. " + "You can drag and drop items between tabs.")); actionCollection()->setDefaultShortcuts(newTab, {Qt::CTRL | Qt::Key_T, Qt::CTRL | Qt::SHIFT | Qt::Key_N}); connect(newTab, &QAction::triggered, this, &DolphinMainWindow::openNewActivatedTab); - QAction* addToPlaces = actionCollection()->addAction(QStringLiteral("add_to_places")); + QAction *addToPlaces = actionCollection()->addAction(QStringLiteral("add_to_places")); addToPlaces->setIcon(QIcon::fromTheme(QStringLiteral("bookmark-new"))); addToPlaces->setText(i18nc("@action:inmenu Add current folder to places", "Add to Places")); - addToPlaces->setWhatsThis(xi18nc("@info:whatsthis", "This adds the selected folder " - "to the Places panel.")); + addToPlaces->setWhatsThis(xi18nc("@info:whatsthis", + "This adds the selected folder " + "to the Places panel.")); connect(addToPlaces, &QAction::triggered, this, &DolphinMainWindow::addToPlaces); - QAction* closeTab = KStandardAction::close(m_tabWidget, QOverload<>::of(&DolphinTabWidget::closeTab), actionCollection()); + QAction *closeTab = KStandardAction::close(m_tabWidget, QOverload<>::of(&DolphinTabWidget::closeTab), actionCollection()); closeTab->setText(i18nc("@action:inmenu File", "Close Tab")); - closeTab->setWhatsThis(i18nc("@info:whatsthis", "This closes the " - "currently viewed tab. If no more tabs are left this window " - "will close instead.")); + closeTab->setWhatsThis(i18nc("@info:whatsthis", + "This closes the " + "currently viewed tab. If no more tabs are left this window " + "will close instead.")); - QAction* quitAction = KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection()); + QAction *quitAction = KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection()); quitAction->setWhatsThis(i18nc("@info:whatsthis quit", "This closes this window.")); // setup 'Edit' menu - KStandardAction::undo(this, - &DolphinMainWindow::undo, - actionCollection()); + KStandardAction::undo(this, &DolphinMainWindow::undo, actionCollection()); // i18n: This will be the last paragraph for the whatsthis for all three: // Cut, Copy and Paste - const QString cutCopyPastePara = xi18nc("@info:whatsthis", "Cut, " - "Copy and Paste work between many " - "applications and are among the most used commands. That's why their " - "keyboard shortcuts are prominently placed right " - "next to each other on the keyboard: Ctrl+X, " - "Ctrl+C and Ctrl+V."); - QAction* cutAction = KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection()); + const QString cutCopyPastePara = xi18nc("@info:whatsthis", + "Cut, " + "Copy and Paste work between many " + "applications and are among the most used commands. That's why their " + "keyboard shortcuts are prominently placed right " + "next to each other on the keyboard: Ctrl+X, " + "Ctrl+C and Ctrl+V."); + QAction *cutAction = KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection()); m_actionTextHelper->registerTextWhenNothingIsSelected(cutAction, i18nc("@action", "Cut…")); - cutAction->setWhatsThis(xi18nc("@info:whatsthis cut", "This copies the items " - "in your current selection to the clipboard." - "Use the Paste action afterwards to copy them from " - "the clipboard to a new location. The items will be removed from their " - "initial location.") + cutCopyPastePara); - QAction* copyAction = KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection()); + cutAction->setWhatsThis(xi18nc("@info:whatsthis cut", + "This copies the items " + "in your current selection to the clipboard." + "Use the Paste action afterwards to copy them from " + "the clipboard to a new location. The items will be removed from their " + "initial location.") + + cutCopyPastePara); + QAction *copyAction = KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection()); m_actionTextHelper->registerTextWhenNothingIsSelected(copyAction, i18nc("@action", "Copy…")); - copyAction->setWhatsThis(xi18nc("@info:whatsthis copy", "This copies the " - "items in your current selection to the clipboard." - "Use the Paste action afterwards to copy them " - "from the clipboard to a new location.") + cutCopyPastePara); - QAction* paste = KStandardAction::paste(this, &DolphinMainWindow::paste, actionCollection()); + copyAction->setWhatsThis(xi18nc("@info:whatsthis copy", + "This copies the " + "items in your current selection to the clipboard." + "Use the Paste action afterwards to copy them " + "from the clipboard to a new location.") + + cutCopyPastePara); + QAction *paste = KStandardAction::paste(this, &DolphinMainWindow::paste, actionCollection()); // The text of the paste-action is modified dynamically by Dolphin // (e. g. to "Paste One Folder"). To prevent that the size of the toolbar changes // due to the long text, the text "Paste" is used: paste->setIconText(i18nc("@action:inmenu Edit", "Paste")); - paste->setWhatsThis(xi18nc("@info:whatsthis paste", "This copies the items from " - "your clipboard to the currently viewed folder." - "If the items were added to the clipboard by the Cut " - "action they are removed from their old location.") + cutCopyPastePara); + paste->setWhatsThis(xi18nc("@info:whatsthis paste", + "This copies the items from " + "your clipboard to the currently viewed folder." + "If the items were added to the clipboard by the Cut " + "action they are removed from their old location.") + + cutCopyPastePara); - QAction* copyToOtherViewAction = actionCollection()->addAction(QStringLiteral("copy_to_inactive_split_view")); + QAction *copyToOtherViewAction = actionCollection()->addAction(QStringLiteral("copy_to_inactive_split_view")); copyToOtherViewAction->setText(i18nc("@action:inmenu", "Copy to Inactive Split View")); m_actionTextHelper->registerTextWhenNothingIsSelected(copyToOtherViewAction, i18nc("@action:inmenu", "Copy to Inactive Split View…")); - copyToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Copy", "This copies the selected items from " - "the active view to the inactive split view.")); + copyToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Copy", + "This copies the selected items from " + "the active view to the inactive split view.")); copyToOtherViewAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy"))); copyToOtherViewAction->setIconText(i18nc("@action:inmenu Edit", "Copy to Inactive Split View")); - actionCollection()->setDefaultShortcut(copyToOtherViewAction, Qt::SHIFT | Qt::Key_F5 ); + actionCollection()->setDefaultShortcut(copyToOtherViewAction, Qt::SHIFT | Qt::Key_F5); connect(copyToOtherViewAction, &QAction::triggered, this, &DolphinMainWindow::copyToInactiveSplitView); - QAction* moveToOtherViewAction = actionCollection()->addAction(QStringLiteral("move_to_inactive_split_view")); + QAction *moveToOtherViewAction = actionCollection()->addAction(QStringLiteral("move_to_inactive_split_view")); moveToOtherViewAction->setText(i18nc("@action:inmenu", "Move to Inactive Split View")); m_actionTextHelper->registerTextWhenNothingIsSelected(moveToOtherViewAction, i18nc("@action:inmenu", "Move to Inactive Split View…")); - moveToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Move", "This moves the selected items from " - "the active view to the inactive split view.")); + moveToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Move", + "This moves the selected items from " + "the active view to the inactive split view.")); moveToOtherViewAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-cut"))); moveToOtherViewAction->setIconText(i18nc("@action:inmenu Edit", "Move to Inactive Split View")); - actionCollection()->setDefaultShortcut(moveToOtherViewAction, Qt::SHIFT | Qt::Key_F6 ); + actionCollection()->setDefaultShortcut(moveToOtherViewAction, Qt::SHIFT | Qt::Key_F6); connect(moveToOtherViewAction, &QAction::triggered, this, &DolphinMainWindow::moveToInactiveSplitView); - QAction* showFilterBar = actionCollection()->addAction(QStringLiteral("show_filter_bar")); + QAction *showFilterBar = actionCollection()->addAction(QStringLiteral("show_filter_bar")); showFilterBar->setText(i18nc("@action:inmenu Tools", "Filter...")); showFilterBar->setToolTip(i18nc("@info:tooltip", "Show Filter Bar")); - showFilterBar->setWhatsThis(xi18nc("@info:whatsthis", "This opens the " - "Filter Bar at the bottom of the window. " - "There you can enter a text to filter the files and folders currently displayed. " - "Only those that contain the text in their name will be kept in view.")); + showFilterBar->setWhatsThis(xi18nc("@info:whatsthis", + "This opens the " + "Filter Bar at the bottom of the window. " + "There you can enter a text to filter the files and folders currently displayed. " + "Only those that contain the text in their name will be kept in view.")); showFilterBar->setIcon(QIcon::fromTheme(QStringLiteral("view-filter"))); actionCollection()->setDefaultShortcuts(showFilterBar, {Qt::CTRL | Qt::Key_I, Qt::Key_Slash}); connect(showFilterBar, &QAction::triggered, this, &DolphinMainWindow::showFilterBar); @@ -1677,12 +1654,13 @@ void DolphinMainWindow::setupActions() QAction *searchAction = KStandardAction::find(this, &DolphinMainWindow::find, actionCollection()); searchAction->setText(i18n("Search...")); searchAction->setToolTip(i18nc("@info:tooltip", "Search for files and folders")); - searchAction->setWhatsThis(xi18nc("@info:whatsthis find", "This helps you " - "find files and folders by opening a find bar. " - "There you can enter search terms and specify settings to find the " - "objects you are looking for.Use this help again on " - "the find bar so we can have a look at it while the settings are " - "explained.")); + searchAction->setWhatsThis(xi18nc("@info:whatsthis find", + "This helps you " + "find files and folders by opening a find bar. " + "There you can enter search terms and specify settings to find the " + "objects you are looking for.Use this help again on " + "the find bar so we can have a look at it while the settings are " + "explained.")); // toggle_search acts as a copy of the main searchAction to be used mainly // in the toolbar, with no default shortcut attached, to avoid messing with @@ -1701,7 +1679,9 @@ void DolphinMainWindow::setupActions() // i18n: Opens a selection mode for selecting files/folders. // The text is kept so unspecific because it will be shown on the toolbar where space is at a premium. toggleSelectionModeAction->setIconText(i18nc("@action:intoolbar", "Select")); - toggleSelectionModeAction->setWhatsThis(xi18nc("@info:whatsthis", "This application only knows which files or folders should be acted on if they are" + toggleSelectionModeAction->setWhatsThis(xi18nc( + "@info:whatsthis", + "This application only knows which files or folders should be acted on if they are" " selected first. Press this to toggle a Selection Mode which makes selecting and deselecting as easy as " "pressing an item once.While in this mode, a quick access bar at the bottom shows available actions for the currently selected items." "")); @@ -1711,7 +1691,8 @@ void DolphinMainWindow::setupActions() // A special version of the toggleSelectionModeAction for the toolbar that also contains a menu // with the selectAllAction and invertSelectionAction. - auto *toggleSelectionModeToolBarAction = new KToolBarPopupAction(toggleSelectionModeAction->icon(), toggleSelectionModeAction->iconText(), actionCollection()); + auto *toggleSelectionModeToolBarAction = + new KToolBarPopupAction(toggleSelectionModeAction->icon(), toggleSelectionModeAction->iconText(), actionCollection()); toggleSelectionModeToolBarAction->setToolTip(toggleSelectionModeAction->text()); toggleSelectionModeToolBarAction->setWhatsThis(toggleSelectionModeAction->whatsThis()); actionCollection()->addAction(QStringLiteral("toggle_selection_mode_tool_bar"), toggleSelectionModeToolBarAction); @@ -1720,14 +1701,16 @@ void DolphinMainWindow::setupActions() connect(toggleSelectionModeToolBarAction, &QAction::triggered, toggleSelectionModeAction, &QAction::trigger); connect(toggleSelectionModeAction, &QAction::toggled, toggleSelectionModeToolBarAction, &QAction::setChecked); - QAction* selectAllAction = KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection()); - selectAllAction->setWhatsThis(xi18nc("@info:whatsthis", "This selects all " - "files and folders in the current location.")); + QAction *selectAllAction = KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection()); + selectAllAction->setWhatsThis(xi18nc("@info:whatsthis", + "This selects all " + "files and folders in the current location.")); - QAction* invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection")); + QAction *invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection")); invertSelection->setText(i18nc("@action:inmenu Edit", "Invert Selection")); - invertSelection->setWhatsThis(xi18nc("@info:whatsthis invert", "This selects all " - "objects that you have currently not selected instead.")); + invertSelection->setWhatsThis(xi18nc("@info:whatsthis invert", + "This selects all " + "objects that you have currently not selected instead.")); invertSelection->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-invert"))); actionCollection()->setDefaultShortcut(invertSelection, Qt::CTRL | Qt::SHIFT | Qt::Key_A); connect(invertSelection, &QAction::triggered, this, &DolphinMainWindow::invertSelection); @@ -1740,15 +1723,16 @@ void DolphinMainWindow::setupActions() // setup 'View' menu // (note that most of it is set up in DolphinViewActionHandler) - QAction* split = actionCollection()->addAction(QStringLiteral("split_view")); - split->setWhatsThis(xi18nc("@info:whatsthis find", "This splits " - "the folder view below into two autonomous views.This " - "way you can see two locations at once and move items between them " - "quickly.Click this again afterwards to recombine the views.")); + QAction *split = actionCollection()->addAction(QStringLiteral("split_view")); + split->setWhatsThis(xi18nc("@info:whatsthis find", + "This splits " + "the folder view below into two autonomous views.This " + "way you can see two locations at once and move items between them " + "quickly.Click this again afterwards to recombine the views.")); actionCollection()->setDefaultShortcut(split, Qt::Key_F3); connect(split, &QAction::triggered, this, &DolphinMainWindow::toggleSplitView); - QAction* stashSplit = actionCollection()->addAction(QStringLiteral("split_stash")); + QAction *stashSplit = actionCollection()->addAction(QStringLiteral("split_stash")); actionCollection()->setDefaultShortcut(stashSplit, Qt::CTRL | Qt::Key_S); stashSplit->setText(i18nc("@action:intoolbar Stash", "Stash")); stashSplit->setToolTip(i18nc("@info", "Opens the stash virtual directory in a split window")); @@ -1760,31 +1744,31 @@ void DolphinMainWindow::setupActions() KStandardAction::redisplay(this, &DolphinMainWindow::reloadView, actionCollection()); - QAction* stop = actionCollection()->addAction(QStringLiteral("stop")); + QAction *stop = actionCollection()->addAction(QStringLiteral("stop")); stop->setText(i18nc("@action:inmenu View", "Stop")); stop->setToolTip(i18nc("@info", "Stop loading")); stop->setWhatsThis(i18nc("@info", "This stops the loading of the contents of the current folder.")); stop->setIcon(QIcon::fromTheme(QStringLiteral("process-stop"))); connect(stop, &QAction::triggered, this, &DolphinMainWindow::stopLoading); - KToggleAction* editableLocation = actionCollection()->add(QStringLiteral("editable_location")); + KToggleAction *editableLocation = actionCollection()->add(QStringLiteral("editable_location")); editableLocation->setText(i18nc("@action:inmenu Navigation Bar", "Editable Location")); editableLocation->setWhatsThis(xi18nc("@info:whatsthis", - "This toggles the Location Bar to be " - "editable so you can directly enter a location you want to go to." - "You can also switch to editing by clicking to the right of the " - "location and switch back by confirming the edited location.")); + "This toggles the Location Bar to be " + "editable so you can directly enter a location you want to go to." + "You can also switch to editing by clicking to the right of the " + "location and switch back by confirming the edited location.")); actionCollection()->setDefaultShortcut(editableLocation, Qt::Key_F6); connect(editableLocation, &KToggleAction::triggered, this, &DolphinMainWindow::toggleEditLocation); - QAction* replaceLocation = actionCollection()->addAction(QStringLiteral("replace_location")); + QAction *replaceLocation = actionCollection()->addAction(QStringLiteral("replace_location")); replaceLocation->setText(i18nc("@action:inmenu Navigation Bar", "Replace Location")); // i18n: "enter" is used both in the meaning of "writing" and "going to" a new location here. // Both meanings are useful but not necessary to understand the use of "Replace Location". // So you might want to be more verbose in your language to convey the meaning but it's up to you. replaceLocation->setWhatsThis(xi18nc("@info:whatsthis", - "This switches to editing the location and selects it " - "so you can quickly enter a different location.")); + "This switches to editing the location and selects it " + "so you can quickly enter a different location.")); actionCollection()->setDefaultShortcut(replaceLocation, Qt::CTRL | Qt::Key_L); connect(replaceLocation, &QAction::triggered, this, &DolphinMainWindow::replaceLocation); @@ -1805,31 +1789,28 @@ void DolphinMainWindow::setupActions() backShortcuts.append(QKeySequence(Qt::Key_Backspace)); actionCollection()->setDefaultShortcuts(m_backAction, backShortcuts); - DolphinRecentTabsMenu* recentTabsMenu = new DolphinRecentTabsMenu(this); + DolphinRecentTabsMenu *recentTabsMenu = new DolphinRecentTabsMenu(this); actionCollection()->addAction(QStringLiteral("closed_tabs"), recentTabsMenu); - connect(m_tabWidget, &DolphinTabWidget::rememberClosedTab, - recentTabsMenu, &DolphinRecentTabsMenu::rememberClosedTab); - connect(recentTabsMenu, &DolphinRecentTabsMenu::restoreClosedTab, - m_tabWidget, &DolphinTabWidget::restoreClosedTab); - connect(recentTabsMenu, &DolphinRecentTabsMenu::closedTabsCountChanged, - this, &DolphinMainWindow::closedTabsCountChanged); + connect(m_tabWidget, &DolphinTabWidget::rememberClosedTab, recentTabsMenu, &DolphinRecentTabsMenu::rememberClosedTab); + connect(recentTabsMenu, &DolphinRecentTabsMenu::restoreClosedTab, m_tabWidget, &DolphinTabWidget::restoreClosedTab); + connect(recentTabsMenu, &DolphinRecentTabsMenu::closedTabsCountChanged, this, &DolphinMainWindow::closedTabsCountChanged); - QAction* undoCloseTab = actionCollection()->addAction(QStringLiteral("undo_close_tab")); + QAction *undoCloseTab = actionCollection()->addAction(QStringLiteral("undo_close_tab")); undoCloseTab->setText(i18nc("@action:inmenu File", "Undo close tab")); - undoCloseTab->setWhatsThis(i18nc("@info:whatsthis undo close tab", - "This returns you to the previously closed tab.")); + undoCloseTab->setWhatsThis(i18nc("@info:whatsthis undo close tab", "This returns you to the previously closed tab.")); actionCollection()->setDefaultShortcut(undoCloseTab, Qt::CTRL | Qt::SHIFT | Qt::Key_T); undoCloseTab->setIcon(QIcon::fromTheme(QStringLiteral("edit-undo"))); undoCloseTab->setEnabled(false); connect(undoCloseTab, &QAction::triggered, recentTabsMenu, &DolphinRecentTabsMenu::undoCloseTab); auto undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); - undoAction->setWhatsThis(xi18nc("@info:whatsthis", "This undoes " - "the last change you made to files or folders." - "Such changes include creating, renaming " - "and moving them to a different location " - "or to the Trash. Changes that can't " - "be undone will ask for your confirmation.")); + undoAction->setWhatsThis(xi18nc("@info:whatsthis", + "This undoes " + "the last change you made to files or folders." + "Such changes include creating, renaming " + "and moving them to a different location " + "or to the Trash. Changes that can't " + "be undone will ask for your confirmation.")); undoAction->setEnabled(false); // undo should be disabled by default { @@ -1851,50 +1832,51 @@ void DolphinMainWindow::setupActions() m_backAction->menu()->installEventFilter(middleClickEventFilter); m_forwardAction->menu()->installEventFilter(middleClickEventFilter); KStandardAction::up(this, &DolphinMainWindow::goUp, actionCollection()); - QAction* homeAction = KStandardAction::home(this, &DolphinMainWindow::goHome, actionCollection()); - homeAction->setWhatsThis(xi18nc("@info:whatsthis", "Go to your " - "Home folder.Every user account " - "has their own Home that contains their data " - "including folders that contain personal application data.")); + QAction *homeAction = KStandardAction::home(this, &DolphinMainWindow::goHome, actionCollection()); + homeAction->setWhatsThis(xi18nc("@info:whatsthis", + "Go to your " + "Home folder.Every user account " + "has their own Home that contains their data " + "including folders that contain personal application data.")); // setup 'Tools' menu - QAction* compareFiles = actionCollection()->addAction(QStringLiteral("compare_files")); + QAction *compareFiles = actionCollection()->addAction(QStringLiteral("compare_files")); compareFiles->setText(i18nc("@action:inmenu Tools", "Compare Files")); compareFiles->setIcon(QIcon::fromTheme(QStringLiteral("kompare"))); compareFiles->setEnabled(false); connect(compareFiles, &QAction::triggered, this, &DolphinMainWindow::compareFiles); - QAction* openPreferredSearchTool = actionCollection()->addAction(QStringLiteral("open_preferred_search_tool")); + QAction *openPreferredSearchTool = actionCollection()->addAction(QStringLiteral("open_preferred_search_tool")); openPreferredSearchTool->setText(i18nc("@action:inmenu Tools", "Open Preferred Search Tool")); openPreferredSearchTool->setWhatsThis(xi18nc("@info:whatsthis", - "This opens a preferred search tool for the viewed location." - "Use More Search Tools menu to configure it.")); + "This opens a preferred search tool for the viewed location." + "Use More Search Tools menu to configure it.")); openPreferredSearchTool->setIcon(QIcon::fromTheme(QStringLiteral("search"))); actionCollection()->setDefaultShortcut(openPreferredSearchTool, Qt::CTRL | Qt::SHIFT | Qt::Key_F); connect(openPreferredSearchTool, &QAction::triggered, this, &DolphinMainWindow::openPreferredSearchTool); if (KAuthorized::authorize(QStringLiteral("shell_access"))) { - QAction* openTerminal = actionCollection()->addAction(QStringLiteral("open_terminal")); + QAction *openTerminal = actionCollection()->addAction(QStringLiteral("open_terminal")); openTerminal->setText(i18nc("@action:inmenu Tools", "Open Terminal")); openTerminal->setWhatsThis(xi18nc("@info:whatsthis", - "This opens a terminal application for the viewed location." - "To learn more about terminals use the help in the terminal application.")); + "This opens a terminal application for the viewed location." + "To learn more about terminals use the help in the terminal application.")); openTerminal->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); actionCollection()->setDefaultShortcut(openTerminal, Qt::SHIFT | Qt::Key_F4); connect(openTerminal, &QAction::triggered, this, &DolphinMainWindow::openTerminal); - QAction* openTerminalHere = actionCollection()->addAction(QStringLiteral("open_terminal_here")); + QAction *openTerminalHere = actionCollection()->addAction(QStringLiteral("open_terminal_here")); // i18n: "Here" refers to the location(s) of the currently selected item(s) or the currently viewed location if nothing is selected. openTerminalHere->setText(i18nc("@action:inmenu Tools", "Open Terminal Here")); openTerminalHere->setWhatsThis(xi18nc("@info:whatsthis", - "This opens terminal applications for the selected items' locations." - "To learn more about terminals use the help in the terminal application.")); + "This opens terminal applications for the selected items' locations." + "To learn more about terminals use the help in the terminal application.")); openTerminalHere->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); actionCollection()->setDefaultShortcut(openTerminalHere, Qt::SHIFT | Qt::ALT | Qt::Key_F4); connect(openTerminalHere, &QAction::triggered, this, &DolphinMainWindow::openTerminalHere); #if HAVE_TERMINAL - QAction* focusTerminalPanel = actionCollection()->addAction(QStringLiteral("focus_terminal_panel")); + QAction *focusTerminalPanel = actionCollection()->addAction(QStringLiteral("focus_terminal_panel")); focusTerminalPanel->setText(i18nc("@action:inmenu Tools", "Focus Terminal Panel")); focusTerminalPanel->setIcon(QIcon::fromTheme(QStringLiteral("swap-panels"))); actionCollection()->setDefaultShortcut(focusTerminalPanel, Qt::CTRL | Qt::SHIFT | Qt::Key_F4); @@ -1911,18 +1893,22 @@ void DolphinMainWindow::setupActions() actionCollection()->addAction(QStringLiteral("bookmarks"), bookmarkMenu); // setup 'Settings' menu - KToggleAction* showMenuBar = KStandardAction::showMenubar(nullptr, nullptr, actionCollection()); + KToggleAction *showMenuBar = KStandardAction::showMenubar(nullptr, nullptr, actionCollection()); showMenuBar->setWhatsThis(xi18nc("@info:whatsthis", - "This switches between having a Menubar " - "and having a %1 button. Both " - "contain mostly the same actions and configuration options." - "The Menubar takes up more space but allows for fast and organised access to all " - "actions an application has to offer.The %1 button " - "is simpler and small which makes triggering advanced actions more time consuming.", hamburgerMenuAction->text().replace('&', ""))); - connect(showMenuBar, &KToggleAction::triggered, // Fixes #286822 - this, &DolphinMainWindow::toggleShowMenuBar, Qt::QueuedConnection); + "This switches between having a Menubar " + "and having a %1 button. Both " + "contain mostly the same actions and configuration options." + "The Menubar takes up more space but allows for fast and organised access to all " + "actions an application has to offer.The %1 button " + "is simpler and small which makes triggering advanced actions more time consuming.", + hamburgerMenuAction->text().replace('&', ""))); + connect(showMenuBar, + &KToggleAction::triggered, // Fixes #286822 + this, + &DolphinMainWindow::toggleShowMenuBar, + Qt::QueuedConnection); - KToggleAction* showStatusBar = KStandardAction::showStatusbar(nullptr, nullptr, actionCollection()); + KToggleAction *showStatusBar = KStandardAction::showStatusbar(nullptr, nullptr, actionCollection()); showStatusBar->setChecked(GeneralSettings::showStatusBar()); connect(GeneralSettings::self(), &GeneralSettings::showStatusBarChanged, showStatusBar, &KToggleAction::setChecked); connect(showStatusBar, &KToggleAction::triggered, this, [this](bool checked) { @@ -1941,10 +1927,12 @@ void DolphinMainWindow::setupActions() prevTabKeys.append(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Tab)); for (int i = 0; i < MaxActivateTabShortcuts; ++i) { - QAction* activateTab = actionCollection()->addAction(QStringLiteral("activate_tab_%1").arg(i)); + QAction *activateTab = actionCollection()->addAction(QStringLiteral("activate_tab_%1").arg(i)); activateTab->setText(i18nc("@action:inmenu", "Activate Tab %1", i + 1)); activateTab->setEnabled(false); - connect(activateTab, &QAction::triggered, this, [this, i]() { m_tabWidget->activateTab(i); }); + connect(activateTab, &QAction::triggered, this, [this, i]() { + m_tabWidget->activateTab(i); + }); // only add default shortcuts for the first 9 tabs regardless of MaxActivateTabShortcuts if (i < 9) { @@ -1952,20 +1940,20 @@ void DolphinMainWindow::setupActions() } } - QAction* activateLastTab = actionCollection()->addAction(QStringLiteral("activate_last_tab")); + QAction *activateLastTab = actionCollection()->addAction(QStringLiteral("activate_last_tab")); activateLastTab->setText(i18nc("@action:inmenu", "Activate Last Tab")); activateLastTab->setEnabled(false); connect(activateLastTab, &QAction::triggered, m_tabWidget, &DolphinTabWidget::activateLastTab); actionCollection()->setDefaultShortcut(activateLastTab, Qt::ALT | Qt::Key_0); - QAction* activateNextTab = actionCollection()->addAction(QStringLiteral("activate_next_tab")); + QAction *activateNextTab = actionCollection()->addAction(QStringLiteral("activate_next_tab")); activateNextTab->setIconText(i18nc("@action:inmenu", "Next Tab")); activateNextTab->setText(i18nc("@action:inmenu", "Activate Next Tab")); activateNextTab->setEnabled(false); connect(activateNextTab, &QAction::triggered, m_tabWidget, &DolphinTabWidget::activateNextTab); actionCollection()->setDefaultShortcuts(activateNextTab, nextTabKeys); - QAction* activatePrevTab = actionCollection()->addAction(QStringLiteral("activate_prev_tab")); + QAction *activatePrevTab = actionCollection()->addAction(QStringLiteral("activate_prev_tab")); activatePrevTab->setIconText(i18nc("@action:inmenu", "Previous Tab")); activatePrevTab->setText(i18nc("@action:inmenu", "Activate Previous Tab")); activatePrevTab->setEnabled(false); @@ -1973,23 +1961,23 @@ void DolphinMainWindow::setupActions() actionCollection()->setDefaultShortcuts(activatePrevTab, prevTabKeys); // for context menu - QAction* showTarget = actionCollection()->addAction(QStringLiteral("show_target")); + QAction *showTarget = actionCollection()->addAction(QStringLiteral("show_target")); showTarget->setText(i18nc("@action:inmenu", "Show Target")); showTarget->setIcon(QIcon::fromTheme(QStringLiteral("document-open-folder"))); showTarget->setEnabled(false); connect(showTarget, &QAction::triggered, this, &DolphinMainWindow::showTarget); - QAction* openInNewTab = actionCollection()->addAction(QStringLiteral("open_in_new_tab")); + QAction *openInNewTab = actionCollection()->addAction(QStringLiteral("open_in_new_tab")); openInNewTab->setText(i18nc("@action:inmenu", "Open in New Tab")); openInNewTab->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); connect(openInNewTab, &QAction::triggered, this, &DolphinMainWindow::openInNewTab); - QAction* openInNewTabs = actionCollection()->addAction(QStringLiteral("open_in_new_tabs")); + QAction *openInNewTabs = actionCollection()->addAction(QStringLiteral("open_in_new_tabs")); openInNewTabs->setText(i18nc("@action:inmenu", "Open in New Tabs")); openInNewTabs->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); connect(openInNewTabs, &QAction::triggered, this, &DolphinMainWindow::openInNewTab); - QAction* openInNewWindow = actionCollection()->addAction(QStringLiteral("open_in_new_window")); + QAction *openInNewWindow = actionCollection()->addAction(QStringLiteral("open_in_new_window")); openInNewWindow->setText(i18nc("@action:inmenu", "Open in New Window")); openInNewWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); connect(openInNewWindow, &QAction::triggered, this, &DolphinMainWindow::openInNewWindow); @@ -2001,104 +1989,105 @@ void DolphinMainWindow::setupDockWidgets() DolphinPlacesModelSingleton::instance().placesModel()->setPanelsLocked(lock); - KDualAction* lockLayoutAction = actionCollection()->add(QStringLiteral("lock_panels")); + KDualAction *lockLayoutAction = actionCollection()->add(QStringLiteral("lock_panels")); lockLayoutAction->setActiveText(i18nc("@action:inmenu Panels", "Unlock Panels")); lockLayoutAction->setActiveIcon(QIcon::fromTheme(QStringLiteral("object-unlocked"))); lockLayoutAction->setInactiveText(i18nc("@action:inmenu Panels", "Lock Panels")); lockLayoutAction->setInactiveIcon(QIcon::fromTheme(QStringLiteral("object-locked"))); - lockLayoutAction->setWhatsThis(xi18nc("@info:whatsthis", "This " - "switches between having panels locked or " - "unlocked.Unlocked panels can be " - "dragged to the other side of the window and have a close " - "button.Locked panels are embedded more cleanly.")); + lockLayoutAction->setWhatsThis(xi18nc("@info:whatsthis", + "This " + "switches between having panels locked or " + "unlocked.Unlocked panels can be " + "dragged to the other side of the window and have a close " + "button.Locked panels are embedded more cleanly.")); lockLayoutAction->setActive(lock); connect(lockLayoutAction, &KDualAction::triggered, this, &DolphinMainWindow::togglePanelLockState); // Setup "Information" - DolphinDockWidget* infoDock = new DolphinDockWidget(i18nc("@title:window", "Information")); + DolphinDockWidget *infoDock = new DolphinDockWidget(i18nc("@title:window", "Information")); infoDock->setLocked(lock); infoDock->setObjectName(QStringLiteral("infoDock")); infoDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); #if HAVE_BALOO - InformationPanel* infoPanel = new InformationPanel(infoDock); + InformationPanel *infoPanel = new InformationPanel(infoDock); infoPanel->setCustomContextMenuActions({lockLayoutAction}); connect(infoPanel, &InformationPanel::urlActivated, this, &DolphinMainWindow::handleUrl); infoDock->setWidget(infoPanel); - QAction* infoAction = infoDock->toggleViewAction(); + QAction *infoAction = infoDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("dialog-information")), Qt::Key_F11, infoAction, QStringLiteral("show_information_panel")); addDockWidget(Qt::RightDockWidgetArea, infoDock); - connect(this, &DolphinMainWindow::urlChanged, - infoPanel, &InformationPanel::setUrl); - connect(this, &DolphinMainWindow::selectionChanged, - infoPanel, &InformationPanel::setSelection); - connect(this, &DolphinMainWindow::requestItemInfo, - infoPanel, &InformationPanel::requestDelayedItemInfo); - connect(this, &DolphinMainWindow::fileItemsChanged, - infoPanel, &InformationPanel::slotFilesItemChanged); + connect(this, &DolphinMainWindow::urlChanged, infoPanel, &InformationPanel::setUrl); + connect(this, &DolphinMainWindow::selectionChanged, infoPanel, &InformationPanel::setSelection); + connect(this, &DolphinMainWindow::requestItemInfo, infoPanel, &InformationPanel::requestDelayedItemInfo); + connect(this, &DolphinMainWindow::fileItemsChanged, infoPanel, &InformationPanel::slotFilesItemChanged); #endif // i18n: This is the last paragraph for the "What's This"-texts of all four panels. - const QString panelWhatsThis = xi18nc("@info:whatsthis", "To show or " - "hide panels like this go to Menu|Panels " - "or View|Panels."); + const QString panelWhatsThis = xi18nc("@info:whatsthis", + "To show or " + "hide panels like this go to Menu|Panels " + "or View|Panels."); #if HAVE_BALOO - actionCollection()->action(QStringLiteral("show_information_panel")) - ->setWhatsThis(xi18nc("@info:whatsthis", " This toggles the " - "information panel at the right side of the " - "window.The panel provides in-depth information " - "about the items your mouse is hovering over or about the selected " - "items. Otherwise it informs you about the currently viewed folder." - "For single items a preview of their contents is provided.")); + actionCollection() + ->action(QStringLiteral("show_information_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", + " This toggles the " + "information panel at the right side of the " + "window.The panel provides in-depth information " + "about the items your mouse is hovering over or about the selected " + "items. Otherwise it informs you about the currently viewed folder." + "For single items a preview of their contents is provided.")); #endif - infoDock->setWhatsThis(xi18nc("@info:whatsthis", "This panel " - "provides in-depth information about the items your mouse is " - "hovering over or about the selected items. Otherwise it informs " - "you about the currently viewed folder.For single items a " - "preview of their contents is provided.You can configure " - "which and how details are given here by right-clicking.") + panelWhatsThis); + infoDock->setWhatsThis(xi18nc("@info:whatsthis", + "This panel " + "provides in-depth information about the items your mouse is " + "hovering over or about the selected items. Otherwise it informs " + "you about the currently viewed folder.For single items a " + "preview of their contents is provided.You can configure " + "which and how details are given here by right-clicking.") + + panelWhatsThis); // Setup "Folders" - DolphinDockWidget* foldersDock = new DolphinDockWidget(i18nc("@title:window", "Folders")); + DolphinDockWidget *foldersDock = new DolphinDockWidget(i18nc("@title:window", "Folders")); foldersDock->setLocked(lock); foldersDock->setObjectName(QStringLiteral("foldersDock")); foldersDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); - FoldersPanel* foldersPanel = new FoldersPanel(foldersDock); + FoldersPanel *foldersPanel = new FoldersPanel(foldersDock); foldersPanel->setCustomContextMenuActions({lockLayoutAction}); foldersDock->setWidget(foldersPanel); - QAction* foldersAction = foldersDock->toggleViewAction(); + QAction *foldersAction = foldersDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("folder")), Qt::Key_F7, foldersAction, QStringLiteral("show_folders_panel")); addDockWidget(Qt::LeftDockWidgetArea, foldersDock); - connect(this, &DolphinMainWindow::urlChanged, - foldersPanel, &FoldersPanel::setUrl); - connect(foldersPanel, &FoldersPanel::folderActivated, - this, &DolphinMainWindow::changeUrl); - connect(foldersPanel, &FoldersPanel::folderInNewTab, - this, &DolphinMainWindow::openNewTab); - connect(foldersPanel, &FoldersPanel::folderInNewActiveTab, - this, &DolphinMainWindow::openNewTabAndActivate); - connect(foldersPanel, &FoldersPanel::errorMessage, - this, &DolphinMainWindow::showErrorMessage); + connect(this, &DolphinMainWindow::urlChanged, foldersPanel, &FoldersPanel::setUrl); + connect(foldersPanel, &FoldersPanel::folderActivated, this, &DolphinMainWindow::changeUrl); + connect(foldersPanel, &FoldersPanel::folderInNewTab, this, &DolphinMainWindow::openNewTab); + connect(foldersPanel, &FoldersPanel::folderInNewActiveTab, this, &DolphinMainWindow::openNewTabAndActivate); + connect(foldersPanel, &FoldersPanel::errorMessage, this, &DolphinMainWindow::showErrorMessage); - actionCollection()->action(QStringLiteral("show_folders_panel")) - ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the " - "folders panel at the left side of the window." - "It shows the folders of the file system" - " in a tree view.")); - foldersDock->setWhatsThis(xi18nc("@info:whatsthis", "This panel " - "shows the folders of the file system in a " - "tree view.Click a folder to go " - "there. Click the arrow to the left of a folder to see its subfolders. " - "This allows quick switching between any folders.") + panelWhatsThis); + actionCollection() + ->action(QStringLiteral("show_folders_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", + "This toggles the " + "folders panel at the left side of the window." + "It shows the folders of the file system" + " in a tree view.")); + foldersDock->setWhatsThis(xi18nc("@info:whatsthis", + "This panel " + "shows the folders of the file system in a " + "tree view.Click a folder to go " + "there. Click the arrow to the left of a folder to see its subfolders. " + "This allows quick switching between any folders.") + + panelWhatsThis); // Setup "Terminal" #if HAVE_TERMINAL if (KAuthorized::authorize(QStringLiteral("shell_access"))) { - DolphinDockWidget* terminalDock = new DolphinDockWidget(i18nc("@title:window Shell terminal", "Terminal")); + DolphinDockWidget *terminalDock = new DolphinDockWidget(i18nc("@title:window Shell terminal", "Terminal")); terminalDock->setLocked(lock); terminalDock->setObjectName(QStringLiteral("terminalDock")); m_terminalPanel = new TerminalPanel(terminalDock); @@ -2107,37 +2096,38 @@ void DolphinMainWindow::setupDockWidgets() connect(m_terminalPanel, &TerminalPanel::hideTerminalPanel, terminalDock, &DolphinDockWidget::hide); connect(m_terminalPanel, &TerminalPanel::changeUrl, this, &DolphinMainWindow::slotTerminalDirectoryChanged); - connect(terminalDock, &DolphinDockWidget::visibilityChanged, - m_terminalPanel, &TerminalPanel::dockVisibilityChanged); - connect(terminalDock, &DolphinDockWidget::visibilityChanged, - this, &DolphinMainWindow::slotTerminalPanelVisibilityChanged); + connect(terminalDock, &DolphinDockWidget::visibilityChanged, m_terminalPanel, &TerminalPanel::dockVisibilityChanged); + connect(terminalDock, &DolphinDockWidget::visibilityChanged, this, &DolphinMainWindow::slotTerminalPanelVisibilityChanged); - QAction* terminalAction = terminalDock->toggleViewAction(); + QAction *terminalAction = terminalDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("dialog-scripts")), Qt::Key_F4, terminalAction, QStringLiteral("show_terminal_panel")); addDockWidget(Qt::BottomDockWidgetArea, terminalDock); - connect(this, &DolphinMainWindow::urlChanged, - m_terminalPanel, &TerminalPanel::setUrl); + connect(this, &DolphinMainWindow::urlChanged, m_terminalPanel, &TerminalPanel::setUrl); if (GeneralSettings::version() < 200) { terminalDock->hide(); } - actionCollection()->action(QStringLiteral("show_terminal_panel")) - ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the " - "terminal panel at the bottom of the window." - "The location in the terminal will always match the folder " - "view so you can navigate using either.The terminal " - "panel is not needed for basic computer usage but can be useful " - "for advanced tasks. To learn more about terminals use the help " - "in a standalone terminal application like Konsole.")); - terminalDock->setWhatsThis(xi18nc("@info:whatsthis", "This is " - "the terminal panel. It behaves like a " - "normal terminal but will match the location of the folder view " - "so you can navigate using either.The terminal panel " - "is not needed for basic computer usage but can be useful for " - "advanced tasks. To learn more about terminals use the help in a " - "standalone terminal application like Konsole.") + panelWhatsThis); + actionCollection() + ->action(QStringLiteral("show_terminal_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", + "This toggles the " + "terminal panel at the bottom of the window." + "The location in the terminal will always match the folder " + "view so you can navigate using either.The terminal " + "panel is not needed for basic computer usage but can be useful " + "for advanced tasks. To learn more about terminals use the help " + "in a standalone terminal application like Konsole.")); + terminalDock->setWhatsThis(xi18nc("@info:whatsthis", + "This is " + "the terminal panel. It behaves like a " + "normal terminal but will match the location of the folder view " + "so you can navigate using either.The terminal panel " + "is not needed for basic computer usage but can be useful for " + "advanced tasks. To learn more about terminals use the help in a " + "standalone terminal application like Konsole.") + + panelWhatsThis); } #endif @@ -2147,7 +2137,7 @@ void DolphinMainWindow::setupDockWidgets() } // Setup "Places" - DolphinDockWidget* placesDock = new DolphinDockWidget(i18nc("@title:window", "Places")); + DolphinDockWidget *placesDock = new DolphinDockWidget(i18nc("@title:window", "Places")); placesDock->setLocked(lock); placesDock->setObjectName(QStringLiteral("placesDock")); placesDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); @@ -2160,66 +2150,62 @@ void DolphinMainWindow::setupDockWidgets() createPanelAction(QIcon::fromTheme(QStringLiteral("compass")), Qt::Key_F9, placesAction, QStringLiteral("show_places_panel")); addDockWidget(Qt::LeftDockWidgetArea, placesDock); - connect(m_placesPanel, &PlacesPanel::placeActivated, - this, &DolphinMainWindow::slotPlaceActivated); - connect(m_placesPanel, &PlacesPanel::tabRequested, - this, &DolphinMainWindow::openNewTab); - connect(m_placesPanel, &PlacesPanel::activeTabRequested, - this, &DolphinMainWindow::openNewTabAndActivate); + connect(m_placesPanel, &PlacesPanel::placeActivated, this, &DolphinMainWindow::slotPlaceActivated); + connect(m_placesPanel, &PlacesPanel::tabRequested, this, &DolphinMainWindow::openNewTab); + connect(m_placesPanel, &PlacesPanel::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate); connect(m_placesPanel, &PlacesPanel::newWindowRequested, this, [this](const QUrl &url) { Dolphin::openNewWindow({url}, this); }); - connect(m_placesPanel, &PlacesPanel::errorMessage, - this, &DolphinMainWindow::showErrorMessage); - connect(this, &DolphinMainWindow::urlChanged, - m_placesPanel, &PlacesPanel::setUrl); - connect(placesDock, &DolphinDockWidget::visibilityChanged, - &DolphinUrlNavigatorsController::slotPlacesPanelVisibilityChanged); - connect(this, &DolphinMainWindow::settingsChanged, - m_placesPanel, &PlacesPanel::readSettings); - connect(m_placesPanel, &PlacesPanel::storageTearDownRequested, - this, &DolphinMainWindow::slotStorageTearDownFromPlacesRequested); - connect(m_placesPanel, &PlacesPanel::storageTearDownExternallyRequested, - this, &DolphinMainWindow::slotStorageTearDownExternallyRequested); + connect(m_placesPanel, &PlacesPanel::errorMessage, this, &DolphinMainWindow::showErrorMessage); + connect(this, &DolphinMainWindow::urlChanged, m_placesPanel, &PlacesPanel::setUrl); + connect(placesDock, &DolphinDockWidget::visibilityChanged, &DolphinUrlNavigatorsController::slotPlacesPanelVisibilityChanged); + connect(this, &DolphinMainWindow::settingsChanged, m_placesPanel, &PlacesPanel::readSettings); + connect(m_placesPanel, &PlacesPanel::storageTearDownRequested, this, &DolphinMainWindow::slotStorageTearDownFromPlacesRequested); + connect(m_placesPanel, &PlacesPanel::storageTearDownExternallyRequested, this, &DolphinMainWindow::slotStorageTearDownExternallyRequested); DolphinUrlNavigatorsController::slotPlacesPanelVisibilityChanged(m_placesPanel->isVisible()); auto actionShowAllPlaces = new QAction(QIcon::fromTheme(QStringLiteral("view-hidden")), i18nc("@item:inmenu", "Show Hidden Places"), this); actionShowAllPlaces->setCheckable(true); actionShowAllPlaces->setDisabled(true); - actionShowAllPlaces->setWhatsThis(i18nc("@info:whatsthis", "This displays " - "all places in the places panel that have been hidden. They will " - "appear semi-transparent unless you uncheck their hide property.")); + actionShowAllPlaces->setWhatsThis(i18nc("@info:whatsthis", + "This displays " + "all places in the places panel that have been hidden. They will " + "appear semi-transparent unless you uncheck their hide property.")); - connect(actionShowAllPlaces, &QAction::triggered, this, [actionShowAllPlaces, this](bool checked){ + connect(actionShowAllPlaces, &QAction::triggered, this, [actionShowAllPlaces, this](bool checked) { m_placesPanel->setShowAll(checked); }); connect(m_placesPanel, &PlacesPanel::allPlacesShownChanged, actionShowAllPlaces, &QAction::setChecked); - actionCollection()->action(QStringLiteral("show_places_panel")) - ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the " - "places panel at the left side of the window." - "It allows you to go to locations you have " - "bookmarked and to access disk or media attached to the computer " - "or to the network. It also contains sections to find recently " - "saved files or files of a certain type.")); - placesDock->setWhatsThis(xi18nc("@info:whatsthis", "This is the " - "Places panel. It allows you to go to locations " - "you have bookmarked and to access disk or media attached to the " - "computer or to the network. It also contains sections to find " - "recently saved files or files of a certain type." - "Click on an entry to go there. Click with the right mouse button " - "instead to open any entry in a new tab or new window." - "New entries can be added by dragging folders onto this panel. " - "Right-click any section or entry to hide it. Right-click an empty " - "space on this panel and select Show Hidden Places" - " to display it again.") + panelWhatsThis); + actionCollection() + ->action(QStringLiteral("show_places_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", + "This toggles the " + "places panel at the left side of the window." + "It allows you to go to locations you have " + "bookmarked and to access disk or media attached to the computer " + "or to the network. It also contains sections to find recently " + "saved files or files of a certain type.")); + placesDock->setWhatsThis(xi18nc("@info:whatsthis", + "This is the " + "Places panel. It allows you to go to locations " + "you have bookmarked and to access disk or media attached to the " + "computer or to the network. It also contains sections to find " + "recently saved files or files of a certain type." + "Click on an entry to go there. Click with the right mouse button " + "instead to open any entry in a new tab or new window." + "New entries can be added by dragging folders onto this panel. " + "Right-click any section or entry to hide it. Right-click an empty " + "space on this panel and select Show Hidden Places" + " to display it again.") + + panelWhatsThis); // Add actions into the "Panels" menu - KActionMenu* panelsMenu = new KActionMenu(i18nc("@action:inmenu View", "Show Panels"), this); + KActionMenu *panelsMenu = new KActionMenu(i18nc("@action:inmenu View", "Show Panels"), this); actionCollection()->addAction(QStringLiteral("panels"), panelsMenu); panelsMenu->setIcon(QIcon::fromTheme(QStringLiteral("view-sidetree"))); panelsMenu->setPopupMode(QToolButton::InstantPopup); - const KActionCollection* ac = actionCollection(); + const KActionCollection *ac = actionCollection(); panelsMenu->addAction(ac->action(QStringLiteral("show_places_panel"))); #if HAVE_BALOO panelsMenu->addAction(ac->action(QStringLiteral("show_information_panel"))); @@ -2230,27 +2216,26 @@ void DolphinMainWindow::setupDockWidgets() panelsMenu->addAction(actionShowAllPlaces); panelsMenu->addAction(lockLayoutAction); - connect(panelsMenu->menu(), &QMenu::aboutToShow, this, [actionShowAllPlaces, this]{ + connect(panelsMenu->menu(), &QMenu::aboutToShow, this, [actionShowAllPlaces, this] { actionShowAllPlaces->setEnabled(DolphinPlacesModelSingleton::instance().placesModel()->hiddenCount()); }); } - void DolphinMainWindow::updateFileAndEditActions() { const KFileItemList list = m_activeViewContainer->view()->selectedItems(); - const KActionCollection* col = actionCollection(); + const KActionCollection *col = actionCollection(); KFileItemListProperties capabilitiesSource(list); - QAction* renameAction = col->action(KStandardAction::name(KStandardAction::RenameFile)); - QAction* moveToTrashAction = col->action(KStandardAction::name(KStandardAction::MoveToTrash)); - QAction* deleteAction = col->action(KStandardAction::name(KStandardAction::DeleteFile)); - QAction* cutAction = col->action(KStandardAction::name(KStandardAction::Cut)); - QAction* duplicateAction = col->action(QStringLiteral("duplicate")); // see DolphinViewActionHandler - QAction* addToPlacesAction = col->action(QStringLiteral("add_to_places")); - QAction* copyToOtherViewAction = col->action(QStringLiteral("copy_to_inactive_split_view")); - QAction* moveToOtherViewAction = col->action(QStringLiteral("move_to_inactive_split_view")); - QAction* copyLocation = col->action(QString("copy_location")); + QAction *renameAction = col->action(KStandardAction::name(KStandardAction::RenameFile)); + QAction *moveToTrashAction = col->action(KStandardAction::name(KStandardAction::MoveToTrash)); + QAction *deleteAction = col->action(KStandardAction::name(KStandardAction::DeleteFile)); + QAction *cutAction = col->action(KStandardAction::name(KStandardAction::Cut)); + QAction *duplicateAction = col->action(QStringLiteral("duplicate")); // see DolphinViewActionHandler + QAction *addToPlacesAction = col->action(QStringLiteral("add_to_places")); + QAction *copyToOtherViewAction = col->action(QStringLiteral("copy_to_inactive_split_view")); + QAction *moveToOtherViewAction = col->action(QStringLiteral("move_to_inactive_split_view")); + QAction *copyLocation = col->action(QString("copy_location")); if (list.isEmpty()) { stateChanged(QStringLiteral("has_no_selection")); @@ -2270,8 +2255,8 @@ void DolphinMainWindow::updateFileAndEditActions() m_actionTextHelper->textsWhenNothingIsSelectedEnabled(false); stateChanged(QStringLiteral("has_selection")); - QAction* deleteWithTrashShortcut = col->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler - QAction* showTarget = col->action(QStringLiteral("show_target")); + QAction *deleteWithTrashShortcut = col->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler + QAction *showTarget = col->action(QStringLiteral("show_target")); if (list.length() == 1 && list.first().isDir()) { addToPlacesAction->setEnabled(true); @@ -2292,7 +2277,7 @@ void DolphinMainWindow::updateFileAndEditActions() } if (m_tabWidget->currentTabPage()->splitViewEnabled()) { - DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); + DolphinTabPage *tabPage = m_tabWidget->currentTabPage(); KFileItem capabilitiesDestination; if (tabPage->primaryViewActive()) { @@ -2313,7 +2298,7 @@ void DolphinMainWindow::updateViewActions() { m_actionHandler->updateViewActions(); - QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); + QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter")); toggleFilterBarAction->setChecked(m_activeViewContainer->isFilterBarVisible()); updateSplitAction(); @@ -2321,18 +2306,19 @@ void DolphinMainWindow::updateViewActions() void DolphinMainWindow::updateGoActions() { - QAction* goUpAction = actionCollection()->action(KStandardAction::name(KStandardAction::Up)); + QAction *goUpAction = actionCollection()->action(KStandardAction::name(KStandardAction::Up)); const QUrl currentUrl = m_activeViewContainer->url(); // I think this is one of the best places to firstly be confronted // with a file system and its hierarchy. Talking about the root // directory might seem too much here but it is the question that // naturally arises in this context. - goUpAction->setWhatsThis(xi18nc("@info:whatsthis", "Go to " - "the folder that contains the currently viewed one." - "All files and folders are organized in a hierarchical " - "file system. At the top of this hierarchy is " - "a directory that contains all data connected to this computer" - "—the root directory.")); + goUpAction->setWhatsThis(xi18nc("@info:whatsthis", + "Go to " + "the folder that contains the currently viewed one." + "All files and folders are organized in a hierarchical " + "file system. At the top of this hierarchy is " + "a directory that contains all data connected to this computer" + "—the root directory.")); goUpAction->setEnabled(KIO::upUrl(currentUrl) != currentUrl); } @@ -2354,88 +2340,58 @@ void DolphinMainWindow::clearStatusBar() m_activeViewContainer->statusBar()->resetToDefaultText(); } -void DolphinMainWindow::connectViewSignals(DolphinViewContainer* container) +void DolphinMainWindow::connectViewSignals(DolphinViewContainer *container) { - connect(container, &DolphinViewContainer::showFilterBarChanged, - this, &DolphinMainWindow::updateFilterBarAction); - connect(container, &DolphinViewContainer::writeStateChanged, - this, &DolphinMainWindow::slotWriteStateChanged); - connect(container, &DolphinViewContainer::searchModeEnabledChanged, - this, &DolphinMainWindow::updateSearchAction); - connect(container, &DolphinViewContainer::captionChanged, - this, &DolphinMainWindow::updateWindowTitle); - connect(container, &DolphinViewContainer::tabRequested, - this, &DolphinMainWindow::openNewTab); - connect(container, &DolphinViewContainer::activeTabRequested, - this, &DolphinMainWindow::openNewTabAndActivate); + connect(container, &DolphinViewContainer::showFilterBarChanged, this, &DolphinMainWindow::updateFilterBarAction); + connect(container, &DolphinViewContainer::writeStateChanged, this, &DolphinMainWindow::slotWriteStateChanged); + connect(container, &DolphinViewContainer::searchModeEnabledChanged, this, &DolphinMainWindow::updateSearchAction); + connect(container, &DolphinViewContainer::captionChanged, this, &DolphinMainWindow::updateWindowTitle); + connect(container, &DolphinViewContainer::tabRequested, this, &DolphinMainWindow::openNewTab); + connect(container, &DolphinViewContainer::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate); - const QAction* toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search")); + const QAction *toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search")); connect(toggleSearchAction, &QAction::triggered, container, &DolphinViewContainer::setSearchModeEnabled); // Make the toggled state of the selection mode actions visually follow the selection mode state of the view. auto toggleSelectionModeAction = actionCollection()->action(QStringLiteral("toggle_selection_mode")); toggleSelectionModeAction->setChecked(m_activeViewContainer->isSelectionModeEnabled()); - connect(m_activeViewContainer, &DolphinViewContainer::selectionModeChanged, - toggleSelectionModeAction, &QAction::setChecked); + connect(m_activeViewContainer, &DolphinViewContainer::selectionModeChanged, toggleSelectionModeAction, &QAction::setChecked); - const DolphinView* view = container->view(); - connect(view, &DolphinView::selectionChanged, - this, &DolphinMainWindow::slotSelectionChanged); - connect(view, &DolphinView::requestItemInfo, - this, &DolphinMainWindow::requestItemInfo); - connect(view, &DolphinView::fileItemsChanged, - this, &DolphinMainWindow::fileItemsChanged); - connect(view, &DolphinView::tabRequested, - this, &DolphinMainWindow::openNewTab); - connect(view, &DolphinView::activeTabRequested, - this, &DolphinMainWindow::openNewTabAndActivate); - connect(view, &DolphinView::windowRequested, - this, &DolphinMainWindow::openNewWindow); - connect(view, &DolphinView::requestContextMenu, - this, &DolphinMainWindow::openContextMenu); - connect(view, &DolphinView::directoryLoadingStarted, - this, &DolphinMainWindow::enableStopAction); - connect(view, &DolphinView::directoryLoadingCompleted, - this, &DolphinMainWindow::disableStopAction); - connect(view, &DolphinView::directoryLoadingCompleted, - this, &DolphinMainWindow::slotDirectoryLoadingCompleted); - connect(view, &DolphinView::goBackRequested, - this, &DolphinMainWindow::goBack); - connect(view, &DolphinView::goForwardRequested, - this, &DolphinMainWindow::goForward); - connect(view, &DolphinView::urlActivated, - this, &DolphinMainWindow::handleUrl); - connect(view, &DolphinView::goUpRequested, - this, &DolphinMainWindow::goUp); + const DolphinView *view = container->view(); + connect(view, &DolphinView::selectionChanged, this, &DolphinMainWindow::slotSelectionChanged); + connect(view, &DolphinView::requestItemInfo, this, &DolphinMainWindow::requestItemInfo); + connect(view, &DolphinView::fileItemsChanged, this, &DolphinMainWindow::fileItemsChanged); + connect(view, &DolphinView::tabRequested, this, &DolphinMainWindow::openNewTab); + connect(view, &DolphinView::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate); + connect(view, &DolphinView::windowRequested, this, &DolphinMainWindow::openNewWindow); + connect(view, &DolphinView::requestContextMenu, this, &DolphinMainWindow::openContextMenu); + connect(view, &DolphinView::directoryLoadingStarted, this, &DolphinMainWindow::enableStopAction); + connect(view, &DolphinView::directoryLoadingCompleted, this, &DolphinMainWindow::disableStopAction); + connect(view, &DolphinView::directoryLoadingCompleted, this, &DolphinMainWindow::slotDirectoryLoadingCompleted); + connect(view, &DolphinView::goBackRequested, this, &DolphinMainWindow::goBack); + connect(view, &DolphinView::goForwardRequested, this, &DolphinMainWindow::goForward); + connect(view, &DolphinView::urlActivated, this, &DolphinMainWindow::handleUrl); + connect(view, &DolphinView::goUpRequested, this, &DolphinMainWindow::goUp); - connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::urlChanged, - this, &DolphinMainWindow::changeUrl); - connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::historyChanged, - this, &DolphinMainWindow::updateHistory); + connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::urlChanged, this, &DolphinMainWindow::changeUrl); + connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::historyChanged, this, &DolphinMainWindow::updateHistory); - auto navigators = static_cast - (actionCollection()->action(QStringLiteral("url_navigators"))); - const KUrlNavigator *navigator = m_tabWidget->currentTabPage()->primaryViewActive() ? - navigators->primaryUrlNavigator() : - navigators->secondaryUrlNavigator(); + auto navigators = static_cast(actionCollection()->action(QStringLiteral("url_navigators"))); + const KUrlNavigator *navigator = + m_tabWidget->currentTabPage()->primaryViewActive() ? navigators->primaryUrlNavigator() : navigators->secondaryUrlNavigator(); QAction *editableLocactionAction = actionCollection()->action(QStringLiteral("editable_location")); editableLocactionAction->setChecked(navigator->isUrlEditable()); - connect(navigator, &KUrlNavigator::editableStateChanged, - this, &DolphinMainWindow::slotEditableStateChanged); - connect(navigator, &KUrlNavigator::tabRequested, - this, &DolphinMainWindow::openNewTab); - connect(navigator, &KUrlNavigator::activeTabRequested, - this, &DolphinMainWindow::openNewTabAndActivate); - connect(navigator, &KUrlNavigator::newWindowRequested, - this, &DolphinMainWindow::openNewWindow); - + connect(navigator, &KUrlNavigator::editableStateChanged, this, &DolphinMainWindow::slotEditableStateChanged); + connect(navigator, &KUrlNavigator::tabRequested, this, &DolphinMainWindow::openNewTab); + connect(navigator, &KUrlNavigator::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate); + connect(navigator, &KUrlNavigator::newWindowRequested, this, &DolphinMainWindow::openNewWindow); } void DolphinMainWindow::updateSplitAction() { - QAction* splitAction = actionCollection()->action(QStringLiteral("split_view")); - const DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); + QAction *splitAction = actionCollection()->action(QStringLiteral("split_view")); + const DolphinTabPage *tabPage = m_tabWidget->currentTabPage(); if (tabPage->splitViewEnabled()) { if (GeneralSettings::closeActiveSplitView() ? tabPage->primaryViewActive() : !tabPage->primaryViewActive()) { splitAction->setText(i18nc("@action:intoolbar Close left view", "Close")); @@ -2455,12 +2411,10 @@ void DolphinMainWindow::updateSplitAction() void DolphinMainWindow::updateAllowedToolbarAreas() { - auto navigators = static_cast - (actionCollection()->action(QStringLiteral("url_navigators"))); + auto navigators = static_cast(actionCollection()->action(QStringLiteral("url_navigators"))); if (toolBar()->actions().contains(navigators)) { toolBar()->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); - if (toolBarArea(toolBar()) == Qt::LeftToolBarArea || - toolBarArea(toolBar()) == Qt::RightToolBarArea) { + if (toolBarArea(toolBar()) == Qt::LeftToolBarArea || toolBarArea(toolBar()) == Qt::RightToolBarArea) { addToolBar(Qt::TopToolBarArea, toolBar()); } } else { @@ -2481,12 +2435,9 @@ bool DolphinMainWindow::isKompareInstalled() const return installed; } -void DolphinMainWindow::createPanelAction(const QIcon& icon, - const QKeySequence& shortcut, - QAction* dockAction, - const QString& actionName) +void DolphinMainWindow::createPanelAction(const QIcon &icon, const QKeySequence &shortcut, QAction *dockAction, const QString &actionName) { - QAction* panelAction = actionCollection()->addAction(actionName); + QAction *panelAction = actionCollection()->addAction(actionName); panelAction->setCheckable(true); panelAction->setChecked(dockAction->isChecked()); panelAction->setText(dockAction->text()); @@ -2497,7 +2448,7 @@ void DolphinMainWindow::createPanelAction(const QIcon& icon, connect(panelAction, &QAction::triggered, dockAction, &QAction::trigger); connect(dockAction, &QAction::toggled, panelAction, &QAction::setChecked); } - +// clang-format off void DolphinMainWindow::setupWhatsThis() { // main widgets @@ -2612,6 +2563,7 @@ void DolphinMainWindow::setupWhatsThis() "If you like using this application but don't know " "about KDE or want to see a cute dragon have a look!")); } +// clang-format on bool DolphinMainWindow::addHamburgerMenuToToolbar() { @@ -2647,14 +2599,12 @@ void DolphinMainWindow::saveNewToolbarConfig() KXmlGuiWindow::saveNewToolbarConfig(); // Applies the new config. This has to be called first // because the rest of this method decides things // based on the new config. - auto navigators = static_cast - (actionCollection()->action(QStringLiteral("url_navigators"))); + auto navigators = static_cast(actionCollection()->action(QStringLiteral("url_navigators"))); if (!toolBar()->actions().contains(navigators)) { m_tabWidget->currentTabPage()->insertNavigatorsWidget(navigators); } updateAllowedToolbarAreas(); - (static_cast(actionCollection()->action(KStandardAction::name( - KStandardAction::HamburgerMenu))))->hideActionsOf(toolBar()); + (static_cast(actionCollection()->action(KStandardAction::name(KStandardAction::HamburgerMenu))))->hideActionsOf(toolBar()); } void DolphinMainWindow::focusTerminalPanel() @@ -2673,8 +2623,8 @@ void DolphinMainWindow::focusTerminalPanel() } } -DolphinMainWindow::UndoUiInterface::UndoUiInterface() : - KIO::FileUndoManager::UiInterface() +DolphinMainWindow::UndoUiInterface::UndoUiInterface() + : KIO::FileUndoManager::UiInterface() { } @@ -2682,11 +2632,11 @@ DolphinMainWindow::UndoUiInterface::~UndoUiInterface() { } -void DolphinMainWindow::UndoUiInterface::jobError(KIO::Job* job) +void DolphinMainWindow::UndoUiInterface::jobError(KIO::Job *job) { - DolphinMainWindow* mainWin= qobject_cast(parentWidget()); + DolphinMainWindow *mainWin = qobject_cast(parentWidget()); if (mainWin) { - DolphinViewContainer* container = mainWin->activeViewContainer(); + DolphinViewContainer *container = mainWin->activeViewContainer(); container->showMessage(job->errorString(), DolphinViewContainer::Error); } else { KIO::FileUndoManager::UiInterface::jobError(job); diff --git a/src/dolphinmainwindow.h b/src/dolphinmainwindow.h index bf74b77b72..3a97f557c0 100644 --- a/src/dolphinmainwindow.h +++ b/src/dolphinmainwindow.h @@ -9,15 +9,15 @@ #ifndef DOLPHIN_MAINWINDOW_H #define DOLPHIN_MAINWINDOW_H +#include "config-dolphin.h" #include "dolphintabwidget.h" #include "selectionmode/bottombar.h" -#include "config-dolphin.h" #include #include #include #if HAVE_BALOO - #include "panels/information/informationpanel.h" +#include "panels/information/informationpanel.h" #endif #include @@ -44,11 +44,13 @@ class QToolButton; class PlacesPanel; class TerminalPanel; -namespace KIO { - class OpenUrlJob; +namespace KIO +{ +class OpenUrlJob; } -namespace SelectionMode { - class ActionTextHelper; +namespace SelectionMode +{ +class ActionTextHelper; } /** @@ -56,7 +58,7 @@ namespace SelectionMode { * * Handles the menus, toolbars and Dolphin views. */ -class DolphinMainWindow: public KXmlGuiWindow +class DolphinMainWindow : public KXmlGuiWindow { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.dolphin.MainWindow") @@ -71,12 +73,12 @@ public: * having a split view setup, the nonactive view * is usually shown in darker colors. */ - DolphinViewContainer* activeViewContainer() const; + DolphinViewContainer *activeViewContainer() const; /** * Returns view container for all tabs */ - QVector viewContainers() const; + QVector viewContainers() const; /** * Opens each directory in \p dirs in a separate tab. If \a splitView is set, @@ -90,13 +92,13 @@ public: * If \a splitView is set, 2 directories are collected within one tab. * \pre \a files must contain at least one url. */ - void openFiles(const QList& files, bool splitView); + void openFiles(const QList &files, bool splitView); /** * Returns the 'Create New...' sub menu which also can be shared * with other menus (e. g. a context menu). */ - KNewFileMenu* newFileMenu() const; + KNewFileMenu *newFileMenu() const; /** * Augments Qt's build-in QMainWindow context menu to add @@ -112,7 +114,7 @@ public: * This typically done after unmounting a disk at mountPath to ensure that * the window is not displaying an invalid location. */ - void setViewsToHomeIfMountPathOpen(const QString& mountPath); + void setViewsToHomeIfMountPathOpen(const QString &mountPath); bool isFoldersPanelEnabled() const; bool isInformationPanelEnabled() const; @@ -159,7 +161,6 @@ public Q_SLOTS: */ bool isItemVisibleInAnyView(const QString &urlOfItem); - /** * Pastes the clipboard data into the currently selected folder * of the active view. If not exactly one folder is selected, @@ -172,14 +173,14 @@ public Q_SLOTS: * Inform all affected dolphin components (panels, views) of an URL * change. */ - void changeUrl(const QUrl& url); + void changeUrl(const QUrl &url); /** * The current directory of the Terminal Panel has changed, probably because * the user entered a 'cd' command. This slot calls changeUrl(url) and makes * sure that the panel keeps the keyboard focus. */ - void slotTerminalDirectoryChanged(const QUrl& url); + void slotTerminalDirectoryChanged(const QUrl &url); /** Stores all settings and quits Dolphin. */ void quit(); @@ -187,7 +188,7 @@ public Q_SLOTS: /** * Opens a new tab in the background showing the URL \a url. */ - void openNewTab(const QUrl& url); + void openNewTab(const QUrl &url); /** * Opens a new tab showing the URL \a url and activate it. @@ -207,19 +208,19 @@ Q_SIGNALS: * Is sent if the selection of the currently active view has * been changed. */ - void selectionChanged(const KFileItemList& selection); + void selectionChanged(const KFileItemList &selection); /** * Is sent if the url of the currently active view has * been changed. */ - void urlChanged(const QUrl& url); + void urlChanged(const QUrl &url); /** * Is emitted if information of an item is requested to be shown e. g. in the panel. * If item is null, no item information request is pending. */ - void requestItemInfo(const KFileItem& item); + void requestItemInfo(const KFileItem &item); /** * It is emitted when in the current view, files are changed, @@ -234,16 +235,16 @@ Q_SIGNALS: protected: /** @see QWidget::showEvent() */ - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; /** @see QMainWindow::closeEvent() */ - void closeEvent(QCloseEvent* event) override; + void closeEvent(QCloseEvent *event) override; /** @see KMainWindow::saveProperties() */ - void saveProperties(KConfigGroup& group) override; + void saveProperties(KConfigGroup &group) override; /** @see KMainWindow::readProperties() */ - void readProperties(const KConfigGroup& group) override; + void readProperties(const KConfigGroup &group) override; /** Sets a sane initial window size **/ QSize sizeHint() const override; @@ -271,7 +272,7 @@ private Q_SLOTS: void createDirectory(); /** Shows the error message in the status bar of the active view. */ - void showErrorMessage(const QString& message); + void showErrorMessage(const QString &message); /** * Updates the state of the 'Undo' menu action dependent @@ -280,7 +281,7 @@ private Q_SLOTS: void slotUndoAvailable(bool available); /** Sets the text of the 'Undo' menu action to \a text. */ - void slotUndoTextChanged(const QString& text); + void slotUndoTextChanged(const QString &text); /** Performs the current undo operation. */ void undo(); @@ -421,7 +422,7 @@ private Q_SLOTS: void openTerminalHere(); /** Opens a terminal window for the URL. */ - void openTerminalJob(const QUrl& url); + void openTerminalJob(const QUrl &url); /** Focus a Terminal Panel. */ void focusTerminalPanel(); @@ -436,7 +437,7 @@ private Q_SLOTS: * Updates the state of the 'Edit' menu actions and emits * the signal selectionChanged(). */ - void slotSelectionChanged(const KFileItemList& selection); + void slotSelectionChanged(const KFileItemList &selection); /** * Updates the state of the 'Back' and 'Forward' menu @@ -486,7 +487,7 @@ private Q_SLOTS: * If the URL can be listed, open it in the current view, otherwise * run it through KRun. */ - void handleUrl(const QUrl& url); + void handleUrl(const QUrl &url); /** * Is invoked when the write state of a folder has been changed and @@ -503,7 +504,7 @@ private Q_SLOTS: * is opened. This list generally includes \a item. * @url URL which contains \a item. */ - void openContextMenu(const QPoint& pos, const KFileItem& item, const KFileItemList &selectedItems, const QUrl& url); + void openContextMenu(const QPoint &pos, const KFileItem &item, const KFileItemList &selectedItems, const QUrl &url); /** * Updates the menu that is by default at the right end of the toolbar. @@ -520,7 +521,7 @@ private Q_SLOTS: * Reloads the view if \a url is the current URL already, and changes the * current URL otherwise. */ - void slotPlaceActivated(const QUrl& url); + void slotPlaceActivated(const QUrl &url); /** * Is called if the another view has been activated by changing the current @@ -530,7 +531,7 @@ private Q_SLOTS: * to this view. When having a split view setup, the nonactive view is * usually shown in darker colors. */ - void activeViewChanged(DolphinViewContainer* viewContainer); + void activeViewChanged(DolphinViewContainer *viewContainer); void closedTabsCountChanged(unsigned int count); @@ -549,7 +550,7 @@ private Q_SLOTS: * This slot is called when the user requested to unmount a removable media * from the places menu */ - void slotStorageTearDownFromPlacesRequested(const QString& mountPath); + void slotStorageTearDownFromPlacesRequested(const QString &mountPath); /** * This slot is called when the user requested to unmount a removable media @@ -558,7 +559,7 @@ private Q_SLOTS: * Solid::StorageAccess::teardownRequested(const QString & udi) * signal through the places panel. */ - void slotStorageTearDownExternallyRequested(const QString& mountPath); + void slotStorageTearDownExternallyRequested(const QString &mountPath); /** * Is called when the view has finished loading the directory. @@ -584,7 +585,7 @@ private Q_SLOTS: * history index. The QAction::data will carry an int with the index * to go to. */ - void slotGoBack(QAction* action); + void slotGoBack(QAction *action); /** * Middle clicking Back/Forward will open the resulting folder in a new tab. @@ -602,7 +603,7 @@ private Q_SLOTS: * history index. The QAction::data will carry an int with the index * to go to. */ - void slotGoForward(QAction* action); + void slotGoForward(QAction *action); /** * Is called when configuring the keyboard shortcuts @@ -630,7 +631,7 @@ private: * the DolphinMainWindow. This method must be invoked each * time a DolphinView has been created. */ - void connectViewSignals(DolphinViewContainer* container); + void connectViewSignals(DolphinViewContainer *container); /** * Updates the text of the split action: @@ -653,10 +654,7 @@ private: * as the action for toggling the dock visibility is done by Qt which * is no KAction instance. */ - void createPanelAction(const QIcon &icon, - const QKeySequence& shortcut, - QAction* dockAction, - const QString& actionName); + void createPanelAction(const QIcon &icon, const QKeySequence &shortcut, QAction *dockAction, const QString &actionName); /** Adds "What's This?" texts to many widgets and StandardActions. */ void setupWhatsThis(); @@ -688,27 +686,27 @@ private: public: UndoUiInterface(); ~UndoUiInterface() override; - void jobError(KIO::Job* job) override; + void jobError(KIO::Job *job) override; }; - KNewFileMenu* m_newFileMenu; - DolphinTabWidget* m_tabWidget; - DolphinViewContainer* m_activeViewContainer; + KNewFileMenu *m_newFileMenu; + DolphinTabWidget *m_tabWidget; + DolphinViewContainer *m_activeViewContainer; - DolphinViewActionHandler* m_actionHandler; - DolphinRemoteEncoding* m_remoteEncoding; + DolphinViewActionHandler *m_actionHandler; + DolphinRemoteEncoding *m_remoteEncoding; QPointer m_settingsDialog; - DolphinBookmarkHandler* m_bookmarkHandler; - SelectionMode::ActionTextHelper* m_actionTextHelper; + DolphinBookmarkHandler *m_bookmarkHandler; + SelectionMode::ActionTextHelper *m_actionTextHelper; KIO::OpenUrlJob *m_lastHandleUrlOpenJob; - TerminalPanel* m_terminalPanel; - PlacesPanel* m_placesPanel; + TerminalPanel *m_terminalPanel; + PlacesPanel *m_placesPanel; bool m_tearDownFromPlacesRequested; - KToolBarPopupAction* m_backAction; - KToolBarPopupAction* m_forwardAction; + KToolBarPopupAction *m_backAction; + KToolBarPopupAction *m_forwardAction; QMenu m_searchTools; KFileItemActions m_fileItemActions; @@ -716,15 +714,14 @@ private: friend class DolphinMainWindowTest; }; -inline DolphinViewContainer* DolphinMainWindow::activeViewContainer() const +inline DolphinViewContainer *DolphinMainWindow::activeViewContainer() const { return m_activeViewContainer; } -inline KNewFileMenu* DolphinMainWindow::newFileMenu() const +inline KNewFileMenu *DolphinMainWindow::newFileMenu() const { return m_newFileMenu; } #endif // DOLPHIN_MAINWINDOW_H - diff --git a/src/dolphinnavigatorswidgetaction.cpp b/src/dolphinnavigatorswidgetaction.cpp index 332d04d25d..47a2a23034 100644 --- a/src/dolphinnavigatorswidgetaction.cpp +++ b/src/dolphinnavigatorswidgetaction.cpp @@ -22,11 +22,11 @@ #include -DolphinNavigatorsWidgetAction::DolphinNavigatorsWidgetAction(QWidget *parent) : - QWidgetAction{parent}, - m_splitter{new QSplitter(Qt::Horizontal)}, - m_adjustSpacingTimer{new QTimer(this)}, - m_viewGeometriesHelper{m_splitter.get(), this} +DolphinNavigatorsWidgetAction::DolphinNavigatorsWidgetAction(QWidget *parent) + : QWidgetAction{parent} + , m_splitter{new QSplitter(Qt::Horizontal)} + , m_adjustSpacingTimer{new QTimer(this)} + , m_viewGeometriesHelper{m_splitter.get(), this} { updateText(); setIcon(QIcon::fromTheme(QStringLiteral("dialog-scripts"))); @@ -37,8 +37,7 @@ DolphinNavigatorsWidgetAction::DolphinNavigatorsWidgetAction(QWidget *parent) : m_adjustSpacingTimer->setInterval(100); m_adjustSpacingTimer->setSingleShot(true); - connect(m_adjustSpacingTimer.get(), &QTimer::timeout, - this, &DolphinNavigatorsWidgetAction::adjustSpacing); + connect(m_adjustSpacingTimer.get(), &QTimer::timeout, this, &DolphinNavigatorsWidgetAction::adjustSpacing); } void DolphinNavigatorsWidgetAction::adjustSpacing() @@ -46,8 +45,7 @@ void DolphinNavigatorsWidgetAction::adjustSpacing() m_previousWindowWidth = parentWidget()->window()->width(); auto viewGeometries = m_viewGeometriesHelper.viewGeometries(); const int widthOfSplitterPrimary = viewGeometries.globalXOfPrimary + viewGeometries.widthOfPrimary - viewGeometries.globalXOfNavigatorsWidget; - const QList splitterSizes = {widthOfSplitterPrimary, - m_splitter->width() - widthOfSplitterPrimary}; + const QList splitterSizes = {widthOfSplitterPrimary, m_splitter->width() - widthOfSplitterPrimary}; m_splitter->setSizes(splitterSizes); // primary side of m_splitter @@ -55,11 +53,8 @@ void DolphinNavigatorsWidgetAction::adjustSpacing() if (leadingSpacing < 0) { leadingSpacing = 0; } - int trailingSpacing = (viewGeometries.globalXOfNavigatorsWidget + m_splitter->width()) - - (viewGeometries.globalXOfPrimary + viewGeometries.widthOfPrimary); - if (trailingSpacing < 0 || emptyTrashButton(Primary)->isVisible() - || networkFolderButton(Primary)->isVisible() - ) { + int trailingSpacing = (viewGeometries.globalXOfNavigatorsWidget + m_splitter->width()) - (viewGeometries.globalXOfPrimary + viewGeometries.widthOfPrimary); + if (trailingSpacing < 0 || emptyTrashButton(Primary)->isVisible() || networkFolderButton(Primary)->isVisible()) { trailingSpacing = 0; } const int widthLeftForUrlNavigator = m_splitter->widget(0)->width() - leadingSpacing - trailingSpacing; @@ -84,11 +79,8 @@ void DolphinNavigatorsWidgetAction::adjustSpacing() } spacing(Primary, Trailing)->setFixedWidth(0); - trailingSpacing = (viewGeometries.globalXOfNavigatorsWidget + m_splitter->width()) - - (viewGeometries.globalXOfSecondary + viewGeometries.widthOfSecondary); - if (trailingSpacing < 0 || emptyTrashButton(Secondary)->isVisible() - || networkFolderButton(Secondary)->isVisible() - ) { + trailingSpacing = (viewGeometries.globalXOfNavigatorsWidget + m_splitter->width()) - (viewGeometries.globalXOfSecondary + viewGeometries.widthOfSecondary); + if (trailingSpacing < 0 || emptyTrashButton(Secondary)->isVisible() || networkFolderButton(Secondary)->isVisible()) { trailingSpacing = 0; } else { const int widthLeftForUrlNavigator2 = m_splitter->widget(1)->width() - trailingSpacing; @@ -111,8 +103,7 @@ void DolphinNavigatorsWidgetAction::createSecondaryUrlNavigator() updateText(); } -void DolphinNavigatorsWidgetAction::followViewContainersGeometry(QWidget *primaryViewContainer, - QWidget *secondaryViewContainer) +void DolphinNavigatorsWidgetAction::followViewContainersGeometry(QWidget *primaryViewContainer, QWidget *secondaryViewContainer) { m_viewGeometriesHelper.setViewContainers(primaryViewContainer, secondaryViewContainer); adjustSpacing(); @@ -123,13 +114,13 @@ bool DolphinNavigatorsWidgetAction::isInToolbar() const return qobject_cast(m_splitter->parentWidget()); } -DolphinUrlNavigator* DolphinNavigatorsWidgetAction::primaryUrlNavigator() const +DolphinUrlNavigator *DolphinNavigatorsWidgetAction::primaryUrlNavigator() const { Q_ASSERT(m_splitter); return m_splitter->widget(0)->findChild(); } -DolphinUrlNavigator* DolphinNavigatorsWidgetAction::secondaryUrlNavigator() const +DolphinUrlNavigator *DolphinNavigatorsWidgetAction::secondaryUrlNavigator() const { Q_ASSERT(m_splitter); if (m_splitter->count() < 2) { @@ -193,31 +184,36 @@ QWidget *DolphinNavigatorsWidgetAction::createNavigatorWidget(Side side) const auto networkFolderButton = newNetworkFolderButton(urlNavigator, navigatorWidget); layout->addWidget(networkFolderButton); - connect(urlNavigator, &KUrlNavigator::urlChanged, this, [urlNavigator, this]() { - // Update URL navigator to show a server URL entry placeholder text if we - // just loaded the remote:/ page, to make it easier for users to figure out - // that they can enter arbitrary remote URLs. See bug 414670 - if (urlNavigator->locationUrl().scheme() == QLatin1String("remote")) { - if (!urlNavigator->isUrlEditable()) { - urlNavigator->setUrlEditable(true); + connect( + urlNavigator, + &KUrlNavigator::urlChanged, + this, + [urlNavigator, this]() { + // Update URL navigator to show a server URL entry placeholder text if we + // just loaded the remote:/ page, to make it easier for users to figure out + // that they can enter arbitrary remote URLs. See bug 414670 + if (urlNavigator->locationUrl().scheme() == QLatin1String("remote")) { + if (!urlNavigator->isUrlEditable()) { + urlNavigator->setUrlEditable(true); + } + urlNavigator->clearText(); + urlNavigator->setPlaceholderText(i18n("Enter server URL (e.g. smb://[ip address])")); + } else { + urlNavigator->setPlaceholderText(QString()); } - urlNavigator->clearText(); - urlNavigator->setPlaceholderText(i18n("Enter server URL (e.g. smb://[ip address])")); - } else { - urlNavigator->setPlaceholderText(QString()); - } - // We have to wait for DolphinUrlNavigator::sizeHint() to update which - // happens a little bit later than when urlChanged is emitted. - this->m_adjustSpacingTimer->start(); - }, Qt::QueuedConnection); + // We have to wait for DolphinUrlNavigator::sizeHint() to update which + // happens a little bit later than when urlChanged is emitted. + this->m_adjustSpacingTimer->start(); + }, + Qt::QueuedConnection); auto trailingSpacing = new QWidget{navigatorWidget}; layout->addWidget(trailingSpacing); return navigatorWidget; } -QPushButton * DolphinNavigatorsWidgetAction::emptyTrashButton(DolphinNavigatorsWidgetAction::Side side) +QPushButton *DolphinNavigatorsWidgetAction::emptyTrashButton(DolphinNavigatorsWidgetAction::Side side) { int sideIndex = (side == Primary ? 0 : 1); if (side == Primary) { @@ -228,15 +224,14 @@ QPushButton * DolphinNavigatorsWidgetAction::emptyTrashButton(DolphinNavigatorsW QPushButton *DolphinNavigatorsWidgetAction::newEmptyTrashButton(const DolphinUrlNavigator *urlNavigator, QWidget *parent) const { - auto emptyTrashButton = new QPushButton(QIcon::fromTheme(QStringLiteral("user-trash")), - i18nc("@action:button", "Empty Trash"), parent); + auto emptyTrashButton = new QPushButton(QIcon::fromTheme(QStringLiteral("user-trash")), i18nc("@action:button", "Empty Trash"), parent); emptyTrashButton->setToolTip(i18n("Empties Trash to create free space")); emptyTrashButton->setFlat(true); - connect(emptyTrashButton, &QPushButton::clicked, - this, [parent]() { Trash::empty(parent); }); - connect(&Trash::instance(), &Trash::emptinessChanged, - emptyTrashButton, &QPushButton::setDisabled); + connect(emptyTrashButton, &QPushButton::clicked, this, [parent]() { + Trash::empty(parent); + }); + connect(&Trash::instance(), &Trash::emptinessChanged, emptyTrashButton, &QPushButton::setDisabled); emptyTrashButton->hide(); connect(urlNavigator, &KUrlNavigator::urlChanged, this, [emptyTrashButton, urlNavigator]() { emptyTrashButton->setVisible(urlNavigator->locationUrl().scheme() == QLatin1String("trash")); @@ -256,18 +251,16 @@ QPushButton *DolphinNavigatorsWidgetAction::networkFolderButton(DolphinNavigator QPushButton *DolphinNavigatorsWidgetAction::newNetworkFolderButton(const DolphinUrlNavigator *urlNavigator, QWidget *parent) const { - auto networkFolderButton = new QPushButton(QIcon::fromTheme(QStringLiteral("folder-add")), - i18nc("@action:button", "Add Network Folder"), parent); + auto networkFolderButton = new QPushButton(QIcon::fromTheme(QStringLiteral("folder-add")), i18nc("@action:button", "Add Network Folder"), parent); networkFolderButton->setFlat(true); KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("org.kde.knetattach")); - connect(networkFolderButton, &QPushButton::clicked, - this, [networkFolderButton, service]() { - auto *job = new KIO::ApplicationLauncherJob(service, networkFolderButton); - auto *delegate = new KNotificationJobUiDelegate; - delegate->setAutoErrorHandlingEnabled(true); - job->setUiDelegate(delegate); - job->start(); - }); + connect(networkFolderButton, &QPushButton::clicked, this, [networkFolderButton, service]() { + auto *job = new KIO::ApplicationLauncherJob(service, networkFolderButton); + auto *delegate = new KNotificationJobUiDelegate; + delegate->setAutoErrorHandlingEnabled(true); + job->setUiDelegate(delegate); + job->start(); + }); networkFolderButton->hide(); connect(urlNavigator, &KUrlNavigator::urlChanged, this, [networkFolderButton, urlNavigator, service]() { networkFolderButton->setVisible(service && urlNavigator->locationUrl().scheme() == QLatin1String("remote")); @@ -290,15 +283,13 @@ QWidget *DolphinNavigatorsWidgetAction::spacing(Side side, Position position) co void DolphinNavigatorsWidgetAction::updateText() { - const int urlNavigatorsAmount = m_splitter->count() > 1 && m_splitter->widget(1)->isVisible() ? - 2 : 1; + const int urlNavigatorsAmount = m_splitter->count() > 1 && m_splitter->widget(1)->isVisible() ? 2 : 1; setText(i18ncp("@action:inmenu", "Location Bar", "Location Bars", urlNavigatorsAmount)); } -DolphinNavigatorsWidgetAction::ViewGeometriesHelper::ViewGeometriesHelper - (QWidget *navigatorsWidget, DolphinNavigatorsWidgetAction *navigatorsWidgetAction) : - m_navigatorsWidget{navigatorsWidget}, - m_navigatorsWidgetAction{navigatorsWidgetAction} +DolphinNavigatorsWidgetAction::ViewGeometriesHelper::ViewGeometriesHelper(QWidget *navigatorsWidget, DolphinNavigatorsWidgetAction *navigatorsWidgetAction) + : m_navigatorsWidget{navigatorsWidget} + , m_navigatorsWidgetAction{navigatorsWidgetAction} { Q_CHECK_PTR(navigatorsWidget); Q_CHECK_PTR(navigatorsWidgetAction); @@ -323,8 +314,7 @@ bool DolphinNavigatorsWidgetAction::ViewGeometriesHelper::eventFilter(QObject *w return QObject::eventFilter(watched, event); } -void DolphinNavigatorsWidgetAction::ViewGeometriesHelper::setViewContainers(QWidget *primaryViewContainer, - QWidget *secondaryViewContainer) +void DolphinNavigatorsWidgetAction::ViewGeometriesHelper::setViewContainers(QWidget *primaryViewContainer, QWidget *secondaryViewContainer) { Q_CHECK_PTR(primaryViewContainer); if (m_primaryViewContainer) { @@ -338,8 +328,7 @@ void DolphinNavigatorsWidgetAction::ViewGeometriesHelper::setViewContainers(QWid m_secondaryViewContainer = secondaryViewContainer; } -DolphinNavigatorsWidgetAction::ViewGeometriesHelper::Geometries - DolphinNavigatorsWidgetAction::ViewGeometriesHelper::viewGeometries() +DolphinNavigatorsWidgetAction::ViewGeometriesHelper::Geometries DolphinNavigatorsWidgetAction::ViewGeometriesHelper::viewGeometries() { Q_ASSERT(m_primaryViewContainer); Geometries geometries; @@ -354,20 +343,17 @@ DolphinNavigatorsWidgetAction::ViewGeometriesHelper::Geometries // globalX if (QApplication::layoutDirection() == Qt::LeftToRight) { - geometries.globalXOfNavigatorsWidget = m_navigatorsWidget->mapToGlobal(QPoint(0,0)).x(); - geometries.globalXOfPrimary = m_primaryViewContainer->mapToGlobal(QPoint(0,0)).x(); - geometries.globalXOfSecondary = !m_secondaryViewContainer ? INT_MIN : - m_secondaryViewContainer->mapToGlobal(QPoint(0,0)).x(); + geometries.globalXOfNavigatorsWidget = m_navigatorsWidget->mapToGlobal(QPoint(0, 0)).x(); + geometries.globalXOfPrimary = m_primaryViewContainer->mapToGlobal(QPoint(0, 0)).x(); + geometries.globalXOfSecondary = !m_secondaryViewContainer ? INT_MIN : m_secondaryViewContainer->mapToGlobal(QPoint(0, 0)).x(); } else { // When the direction is reversed, globalX does not change. // For the adjustSpacing() code to work we need globalX to measure from right to left // and to measure up to the rightmost point of a widget instead of the leftmost. - geometries.globalXOfNavigatorsWidget = - (-1) * (m_navigatorsWidget->mapToGlobal(QPoint(0,0)).x() + m_navigatorsWidget->width()); - geometries.globalXOfPrimary = - (-1) * (m_primaryViewContainer->mapToGlobal(QPoint(0,0)).x() + geometries.widthOfPrimary); - geometries.globalXOfSecondary = !m_secondaryViewContainer ? INT_MIN : - (-1) * (m_secondaryViewContainer->mapToGlobal(QPoint(0,0)).x() + geometries.widthOfSecondary); + geometries.globalXOfNavigatorsWidget = (-1) * (m_navigatorsWidget->mapToGlobal(QPoint(0, 0)).x() + m_navigatorsWidget->width()); + geometries.globalXOfPrimary = (-1) * (m_primaryViewContainer->mapToGlobal(QPoint(0, 0)).x() + geometries.widthOfPrimary); + geometries.globalXOfSecondary = + !m_secondaryViewContainer ? INT_MIN : (-1) * (m_secondaryViewContainer->mapToGlobal(QPoint(0, 0)).x() + geometries.widthOfSecondary); } return geometries; } diff --git a/src/dolphinnavigatorswidgetaction.h b/src/dolphinnavigatorswidgetaction.h index d33482201a..67c93d22dc 100644 --- a/src/dolphinnavigatorswidgetaction.h +++ b/src/dolphinnavigatorswidgetaction.h @@ -65,8 +65,7 @@ public: * Notify this widget of changes in geometry of the ViewContainers it tries to be * aligned with. */ - void followViewContainersGeometry(QWidget *primaryViewContainer, - QWidget *secondaryViewContainer = nullptr); + void followViewContainersGeometry(QWidget *primaryViewContainer, QWidget *secondaryViewContainer = nullptr); bool isInToolbar() const; @@ -104,10 +103,7 @@ private: /** * In Left-to-right languages the Primary side will be the left one. */ - enum Side { - Primary, - Secondary - }; + enum Side { Primary, Secondary }; /** * Used to create the navigatorWidgets for both sides of the QSplitter. */ @@ -142,10 +138,7 @@ private: */ QPushButton *newNetworkFolderButton(const DolphinUrlNavigator *urlNavigator, QWidget *parent) const; - enum Position { - Leading, - Trailing - }; + enum Position { Leading, Trailing }; /** * Used to retrieve both the leading and trailing spacing for the navigatorWidgets * on both sides. A secondary leading spacing does not exist. @@ -191,8 +184,7 @@ private: /** * Sets the ViewContainers whose geometry is obtained when viewGeometries() is called. */ - void setViewContainers(QWidget *primaryViewContainer, - QWidget *secondaryViewContainer = nullptr); + void setViewContainers(QWidget *primaryViewContainer, QWidget *secondaryViewContainer = nullptr); struct Geometries { int globalXOfNavigatorsWidget; diff --git a/src/dolphinnewfilemenu.cpp b/src/dolphinnewfilemenu.cpp index 9b6b53b2e6..8de4347b80 100644 --- a/src/dolphinnewfilemenu.cpp +++ b/src/dolphinnewfilemenu.cpp @@ -11,8 +11,8 @@ #include #include -DolphinNewFileMenu::DolphinNewFileMenu(KActionCollection* collection, QObject* parent) : - KNewFileMenu(collection, QStringLiteral("new_menu"), parent) +DolphinNewFileMenu::DolphinNewFileMenu(KActionCollection *collection, QObject *parent) + : KNewFileMenu(collection, QStringLiteral("new_menu"), parent) { DolphinNewFileMenuObserver::instance().attach(this); } @@ -22,7 +22,7 @@ DolphinNewFileMenu::~DolphinNewFileMenu() DolphinNewFileMenuObserver::instance().detach(this); } -void DolphinNewFileMenu::slotResult(KJob* job) +void DolphinNewFileMenu::slotResult(KJob *job) { if (job->error() && job->error() != KIO::ERR_USER_CANCELED) { Q_EMIT errorMessage(job->errorString()); @@ -30,4 +30,3 @@ void DolphinNewFileMenu::slotResult(KJob* job) KNewFileMenu::slotResult(job); } } - diff --git a/src/dolphinnewfilemenu.h b/src/dolphinnewfilemenu.h index 650863cb11..4fa173ef9d 100644 --- a/src/dolphinnewfilemenu.h +++ b/src/dolphinnewfilemenu.h @@ -25,15 +25,15 @@ class DOLPHIN_EXPORT DolphinNewFileMenu : public KNewFileMenu Q_OBJECT public: - DolphinNewFileMenu(KActionCollection* collection, QObject* parent); + DolphinNewFileMenu(KActionCollection *collection, QObject *parent); ~DolphinNewFileMenu() override; Q_SIGNALS: - void errorMessage(const QString& error); + void errorMessage(const QString &error); protected Q_SLOTS: /** @see KNewFileMenu::slotResult() */ - void slotResult(KJob* job) override; + void slotResult(KJob *job) override; }; #endif diff --git a/src/dolphinpart.cpp b/src/dolphinpart.cpp index 575c304178..64c829c2d2 100644 --- a/src/dolphinpart.cpp +++ b/src/dolphinpart.cpp @@ -48,11 +48,10 @@ K_PLUGIN_CLASS_WITH_JSON(DolphinPart, "dolphinpart.json") -DolphinPart::DolphinPart(QWidget* parentWidget, QObject* parent, - const KPluginMetaData& metaData, const QVariantList& args) +DolphinPart::DolphinPart(QWidget *parentWidget, QObject *parent, const KPluginMetaData &metaData, const QVariantList &args) : KParts::ReadOnlyPart(parent) - ,m_openTerminalAction(nullptr) - ,m_removeAction(nullptr) + , m_openTerminalAction(nullptr) + , m_removeAction(nullptr) { Q_UNUSED(args) setMetaData(metaData); @@ -66,8 +65,7 @@ DolphinPart::DolphinPart(QWidget* parentWidget, QObject* parent, m_view->setTabsForFilesEnabled(true); setWidget(m_view); - connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage, - this, &DolphinPart::slotErrorMessage); + connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage, this, &DolphinPart::slotErrorMessage); connect(m_view, &DolphinView::directoryLoadingCompleted, this, &KParts::ReadOnlyPart::completed); connect(m_view, &DolphinView::directoryLoadingCompleted, this, &DolphinPart::updatePasteAction); @@ -76,51 +74,37 @@ DolphinPart::DolphinPart(QWidget* parentWidget, QObject* parent, setXMLFile(QStringLiteral("dolphinpart.rc")); - connect(m_view, &DolphinView::infoMessage, - this, &DolphinPart::slotMessage); - connect(m_view, &DolphinView::operationCompletedMessage, - this, &DolphinPart::slotMessage); - connect(m_view, &DolphinView::errorMessage, - this, &DolphinPart::slotErrorMessage); - connect(m_view, &DolphinView::itemActivated, - this, &DolphinPart::slotItemActivated); - connect(m_view, &DolphinView::itemsActivated, - this, &DolphinPart::slotItemsActivated); + connect(m_view, &DolphinView::infoMessage, this, &DolphinPart::slotMessage); + connect(m_view, &DolphinView::operationCompletedMessage, this, &DolphinPart::slotMessage); + connect(m_view, &DolphinView::errorMessage, this, &DolphinPart::slotErrorMessage); + connect(m_view, &DolphinView::itemActivated, this, &DolphinPart::slotItemActivated); + connect(m_view, &DolphinView::itemsActivated, this, &DolphinPart::slotItemsActivated); connect(m_view, &DolphinView::statusBarTextChanged, this, [this](const QString &text) { const QString escapedText = Qt::convertFromPlainText(text); Q_EMIT ReadOnlyPart::setStatusBarText(QStringLiteral("%1").arg(escapedText)); }); - connect(m_view, &DolphinView::tabRequested, - this, &DolphinPart::createNewWindow); - connect(m_view, &DolphinView::requestContextMenu, - this, &DolphinPart::slotOpenContextMenu); - connect(m_view, &DolphinView::selectionChanged, - m_extension, &KParts::BrowserExtension::selectionInfo); - connect(m_view, &DolphinView::selectionChanged, - this, &DolphinPart::slotSelectionChanged); - connect(m_view, &DolphinView::requestItemInfo, - this, &DolphinPart::slotRequestItemInfo); - connect(m_view, &DolphinView::modeChanged, - this, &DolphinPart::viewModeChanged); // relay signal - connect(m_view, &DolphinView::redirection, - this, &DolphinPart::slotDirectoryRedirection); + connect(m_view, &DolphinView::tabRequested, this, &DolphinPart::createNewWindow); + connect(m_view, &DolphinView::requestContextMenu, this, &DolphinPart::slotOpenContextMenu); + connect(m_view, &DolphinView::selectionChanged, m_extension, &KParts::BrowserExtension::selectionInfo); + connect(m_view, &DolphinView::selectionChanged, this, &DolphinPart::slotSelectionChanged); + connect(m_view, &DolphinView::requestItemInfo, this, &DolphinPart::slotRequestItemInfo); + connect(m_view, &DolphinView::modeChanged, this, &DolphinPart::viewModeChanged); // relay signal + connect(m_view, &DolphinView::redirection, this, &DolphinPart::slotDirectoryRedirection); // Watch for changes that should result in updates to the // status bar text. connect(m_view, &DolphinView::itemCountChanged, this, &DolphinPart::updateStatusBar); - connect(m_view, &DolphinView::selectionChanged, this, &DolphinPart::updateStatusBar); + connect(m_view, &DolphinView::selectionChanged, this, &DolphinPart::updateStatusBar); m_actionHandler = new DolphinViewActionHandler(actionCollection(), nullptr, this); m_actionHandler->setCurrentView(m_view); connect(m_actionHandler, &DolphinViewActionHandler::createDirectoryTriggered, this, &DolphinPart::createDirectory); m_remoteEncoding = new DolphinRemoteEncoding(this, m_actionHandler); - connect(this, &DolphinPart::aboutToOpenURL, - m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl); + connect(this, &DolphinPart::aboutToOpenURL, m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl); - QClipboard* clipboard = QApplication::clipboard(); - connect(clipboard, &QClipboard::dataChanged, - this, &DolphinPart::updatePasteAction); + QClipboard *clipboard = QApplication::clipboard(); + connect(clipboard, &QClipboard::dataChanged, this, &DolphinPart::updatePasteAction); // Create file info and listing filter extensions. // NOTE: Listing filter needs to be instantiated after the creation of the view. @@ -128,9 +112,9 @@ DolphinPart::DolphinPart(QWidget* parentWidget, QObject* parent, new DolphinPartListingFilterExtension(this); - KDirLister* lister = m_view->m_model->m_dirLister; + KDirLister *lister = m_view->m_model->m_dirLister; if (lister) { - DolphinPartListingNotificationExtension* notifyExt = new DolphinPartListingNotificationExtension(this); + DolphinPartListingNotificationExtension *notifyExt = new DolphinPartListingNotificationExtension(this); connect(lister, &KDirLister::newItems, notifyExt, &DolphinPartListingNotificationExtension::slotNewItems); connect(lister, &KDirLister::itemsDeleted, notifyExt, &DolphinPartListingNotificationExtension::slotItemsDeleted); } else { @@ -159,29 +143,28 @@ void DolphinPart::createActions() m_newFileMenu = new DolphinNewFileMenu(actionCollection(), this); m_newFileMenu->setParentWidget(widget()); - connect(m_newFileMenu->menu(), &QMenu::aboutToShow, - this, &DolphinPart::updateNewMenu); + connect(m_newFileMenu->menu(), &QMenu::aboutToShow, this, &DolphinPart::updateNewMenu); - QAction *editMimeTypeAction = actionCollection()->addAction( QStringLiteral("editMimeType") ); - editMimeTypeAction->setText( i18nc("@action:inmenu Edit", "&Edit File Type..." ) ); + QAction *editMimeTypeAction = actionCollection()->addAction(QStringLiteral("editMimeType")); + editMimeTypeAction->setText(i18nc("@action:inmenu Edit", "&Edit File Type...")); connect(editMimeTypeAction, &QAction::triggered, this, &DolphinPart::slotEditMimeType); - QAction* selectItemsMatching = actionCollection()->addAction(QStringLiteral("select_items_matching")); + QAction *selectItemsMatching = actionCollection()->addAction(QStringLiteral("select_items_matching")); selectItemsMatching->setText(i18nc("@action:inmenu Edit", "Select Items Matching...")); actionCollection()->setDefaultShortcut(selectItemsMatching, Qt::CTRL | Qt::Key_S); connect(selectItemsMatching, &QAction::triggered, this, &DolphinPart::slotSelectItemsMatchingPattern); - QAction* unselectItemsMatching = actionCollection()->addAction(QStringLiteral("unselect_items_matching")); + QAction *unselectItemsMatching = actionCollection()->addAction(QStringLiteral("unselect_items_matching")); unselectItemsMatching->setText(i18nc("@action:inmenu Edit", "Unselect Items Matching...")); connect(unselectItemsMatching, &QAction::triggered, this, &DolphinPart::slotUnselectItemsMatchingPattern); KStandardAction::selectAll(m_view, &DolphinView::selectAll, actionCollection()); - QAction* unselectAll = actionCollection()->addAction(QStringLiteral("unselect_all")); + QAction *unselectAll = actionCollection()->addAction(QStringLiteral("unselect_all")); unselectAll->setText(i18nc("@action:inmenu Edit", "Unselect All")); connect(unselectAll, &QAction::triggered, m_view, &DolphinView::clearSelection); - QAction* invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection")); + QAction *invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection")); invertSelection->setText(i18nc("@action:inmenu Edit", "Invert Selection")); actionCollection()->setDefaultShortcut(invertSelection, Qt::CTRL | Qt::SHIFT | Qt::Key_A); connect(invertSelection, &QAction::triggered, m_view, &DolphinView::invertSelection); @@ -190,21 +173,16 @@ void DolphinPart::createActions() // Go menu - QActionGroup* goActionGroup = new QActionGroup(this); - connect(goActionGroup, &QActionGroup::triggered, - this, &DolphinPart::slotGoTriggered); + QActionGroup *goActionGroup = new QActionGroup(this); + connect(goActionGroup, &QActionGroup::triggered, this, &DolphinPart::slotGoTriggered); - createGoAction("go_applications", "start-here-kde", - i18nc("@action:inmenu Go", "App&lications"), QStringLiteral("programs:/"), - goActionGroup); - createGoAction("go_network_folders", "folder-remote", - i18nc("@action:inmenu Go", "&Network Folders"), QStringLiteral("remote:/"), - goActionGroup); - createGoAction("go_trash", "user-trash", - i18nc("@action:inmenu Go", "Trash"), QStringLiteral("trash:/"), - goActionGroup); - createGoAction("go_autostart", "", - i18nc("@action:inmenu Go", "Autostart"), QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + "/autostart", + createGoAction("go_applications", "start-here-kde", i18nc("@action:inmenu Go", "App&lications"), QStringLiteral("programs:/"), goActionGroup); + createGoAction("go_network_folders", "folder-remote", i18nc("@action:inmenu Go", "&Network Folders"), QStringLiteral("remote:/"), goActionGroup); + createGoAction("go_trash", "user-trash", i18nc("@action:inmenu Go", "Trash"), QStringLiteral("trash:/"), goActionGroup); + createGoAction("go_autostart", + "", + i18nc("@action:inmenu Go", "Autostart"), + QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + "/autostart", goActionGroup); // Tools menu @@ -222,33 +200,31 @@ void DolphinPart::createActions() #endif } -void DolphinPart::createGoAction(const char* name, const char* iconName, - const QString& text, const QString& url, - QActionGroup* actionGroup) +void DolphinPart::createGoAction(const char *name, const char *iconName, const QString &text, const QString &url, QActionGroup *actionGroup) { - QAction* action = actionCollection()->addAction(name); + QAction *action = actionCollection()->addAction(name); action->setIcon(QIcon::fromTheme(iconName)); action->setText(text); action->setData(url); action->setActionGroup(actionGroup); } -void DolphinPart::slotGoTriggered(QAction* action) +void DolphinPart::slotGoTriggered(QAction *action) { const QString url = action->data().toString(); Q_EMIT m_extension->openUrlRequest(QUrl(url)); } -void DolphinPart::slotSelectionChanged(const KFileItemList& selection) +void DolphinPart::slotSelectionChanged(const KFileItemList &selection) { const bool hasSelection = !selection.isEmpty(); - QAction* renameAction = actionCollection()->action(KStandardAction::name(KStandardAction::RenameFile)); - QAction* moveToTrashAction = actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)); - QAction* deleteAction = actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)); - QAction* editMimeTypeAction = actionCollection()->action(QStringLiteral("editMimeType")); - QAction* propertiesAction = actionCollection()->action(QStringLiteral("properties")); - QAction* deleteWithTrashShortcut = actionCollection()->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler + QAction *renameAction = actionCollection()->action(KStandardAction::name(KStandardAction::RenameFile)); + QAction *moveToTrashAction = actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)); + QAction *deleteAction = actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)); + QAction *editMimeTypeAction = actionCollection()->action(QStringLiteral("editMimeType")); + QAction *propertiesAction = actionCollection()->action(QStringLiteral("properties")); + QAction *deleteWithTrashShortcut = actionCollection()->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler if (!hasSelection) { stateChanged(QStringLiteral("has_no_selection")); @@ -279,13 +255,13 @@ void DolphinPart::slotSelectionChanged(const KFileItemList& selection) void DolphinPart::updatePasteAction() { QPair pasteInfo = m_view->pasteInfo(); - Q_EMIT m_extension->enableAction( "paste", pasteInfo.first ); - Q_EMIT m_extension->setActionText( "paste", pasteInfo.second ); + Q_EMIT m_extension->enableAction("paste", pasteInfo.first); + Q_EMIT m_extension->setActionText("paste", pasteInfo.second); } QString DolphinPart::urlToLocalFilePath(const QUrl &url) { - KIO::StatJob* statJob = KIO::mostLocalUrl(url); + KIO::StatJob *statJob = KIO::mostLocalUrl(url); KJobWidgets::setWindow(statJob, widget()); statJob->exec(); QUrl localUrl = statJob->mostLocalUrl(); @@ -331,19 +307,19 @@ bool DolphinPart::openUrl(const QUrl &url) return true; } -void DolphinPart::slotMessage(const QString& msg) +void DolphinPart::slotMessage(const QString &msg) { Q_EMIT setStatusBarText(msg); } -void DolphinPart::slotErrorMessage(const QString& msg) +void DolphinPart::slotErrorMessage(const QString &msg) { qCDebug(DolphinDebug) << msg; Q_EMIT canceled(msg); //KMessageBox::error(m_view, msg); } -void DolphinPart::slotRequestItemInfo(const KFileItem& item) +void DolphinPart::slotRequestItemInfo(const KFileItem &item) { Q_EMIT m_extension->mouseOverInfo(item); if (item.isNull()) { @@ -354,7 +330,7 @@ void DolphinPart::slotRequestItemInfo(const KFileItem& item) } } -void DolphinPart::slotItemActivated(const KFileItem& item) +void DolphinPart::slotItemActivated(const KFileItem &item) { KParts::OpenUrlArguments args; // Forget about the known mimetype if a target URL is used. @@ -370,28 +346,24 @@ void DolphinPart::slotItemActivated(const KFileItem& item) Q_EMIT m_extension->openUrlRequest(item.targetUrl(), args, browserArgs); } -void DolphinPart::slotItemsActivated(const KFileItemList& items) +void DolphinPart::slotItemsActivated(const KFileItemList &items) { - for (const KFileItem& item : items) { + for (const KFileItem &item : items) { slotItemActivated(item); } } -void DolphinPart::createNewWindow(const QUrl& url) +void DolphinPart::createNewWindow(const QUrl &url) { // TODO: Check issue N176832 for the missing QAIV signal; task 177399 - maybe this code // should be moved into DolphinPart::slotItemActivated() Q_EMIT m_extension->createNewWindow(url); } -void DolphinPart::slotOpenContextMenu(const QPoint& pos, - const KFileItem& _item, - const KFileItemList &selectedItems, - const QUrl &) +void DolphinPart::slotOpenContextMenu(const QPoint &pos, const KFileItem &_item, const KFileItemList &selectedItems, const QUrl &) { - KParts::BrowserExtension::PopupFlags popupFlags = KParts::BrowserExtension::DefaultPopupItems - | KParts::BrowserExtension::ShowProperties - | KParts::BrowserExtension::ShowUrlOperations; + KParts::BrowserExtension::PopupFlags popupFlags = + KParts::BrowserExtension::DefaultPopupItems | KParts::BrowserExtension::ShowProperties | KParts::BrowserExtension::ShowUrlOperations; KFileItem item(_item); @@ -420,8 +392,7 @@ void DolphinPart::slotOpenContextMenu(const QPoint& pos, const bool supportsMoving = capabilities.supportsMoving(); if (capabilities.supportsDeleting()) { - const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) || - !item.isLocalFile()); + const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) || !item.isLocalFile()); const bool showMoveToTrashAction = capabilities.isLocal() && supportsMoving; if (showDeleteAction && showMoveToTrashAction) { @@ -450,17 +421,11 @@ void DolphinPart::slotOpenContextMenu(const QPoint& pos, // But in treeview mode we should allow it. if (m_view->itemsExpandable()) popupFlags |= KParts::BrowserExtension::ShowCreateDirectory; - } actionGroups.insert(QStringLiteral("editactions"), editActions); - Q_EMIT m_extension->popupMenu(pos, - items, - KParts::OpenUrlArguments(), - KParts::BrowserArguments(), - popupFlags, - actionGroups); + Q_EMIT m_extension->popupMenu(pos, items, KParts::OpenUrlArguments(), KParts::BrowserArguments(), popupFlags, actionGroups); } void DolphinPart::slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl) @@ -473,7 +438,6 @@ void DolphinPart::slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUr } } - void DolphinPart::slotEditMimeType() { const KFileItemList items = m_view->selectedItems(); @@ -484,19 +448,15 @@ void DolphinPart::slotEditMimeType() void DolphinPart::slotSelectItemsMatchingPattern() { - openSelectionDialog(i18nc("@title:window", "Select"), - i18n("Select all items matching this pattern:"), - true); + openSelectionDialog(i18nc("@title:window", "Select"), i18n("Select all items matching this pattern:"), true); } void DolphinPart::slotUnselectItemsMatchingPattern() { - openSelectionDialog(i18nc("@title:window", "Unselect"), - i18n("Unselect all items matching this pattern:"), - false); + openSelectionDialog(i18nc("@title:window", "Unselect"), i18n("Unselect all items matching this pattern:"), false); } -void DolphinPart::openSelectionDialog(const QString& title, const QString& text, bool selectItems) +void DolphinPart::openSelectionDialog(const QString &title, const QString &text, bool selectItems) { auto *dialog = new QInputDialog(m_view); dialog->setAttribute(Qt::WA_DeleteOnClose, true); @@ -532,9 +492,9 @@ void DolphinPart::openSelectionDialog(const QString& title, const QString& text, dialog->open(); } -void DolphinPart::setCurrentViewMode(const QString& viewModeName) +void DolphinPart::setCurrentViewMode(const QString &viewModeName) { - QAction* action = actionCollection()->action(viewModeName); + QAction *action = actionCollection()->action(viewModeName); Q_ASSERT(action); action->trigger(); } @@ -544,7 +504,7 @@ QString DolphinPart::currentViewMode() const return m_actionHandler->currentViewModeActionName(); } -void DolphinPart::setNameFilter(const QString& nameFilter) +void DolphinPart::setNameFilter(const QString &nameFilter) { // This is the "/home/dfaure/*.diff" kind of name filter (KDirLister::setNameFilter) // which is unrelated to DolphinView::setNameFilter which is substring filtering in a proxy. @@ -571,10 +531,8 @@ void DolphinPart::slotOpenTerminal() void DolphinPart::slotFindFile() { QMenu searchTools; - KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames( - &searchTools, { "files-find" }, QUrl::fromLocalFile(localFilePathOrHome()) - ); - QList actions = searchTools.actions(); + KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames(&searchTools, {"files-find"}, QUrl::fromLocalFile(localFilePathOrHome())); + QList actions = searchTools.actions(); if (!(actions.isEmpty())) { actions.first()->trigger(); } else { @@ -617,7 +575,7 @@ void DolphinPart::createDirectory() m_newFileMenu->createDirectory(); } -void DolphinPart::setFilesToSelect(const QList& files) +void DolphinPart::setFilesToSelect(const QList &files) { if (files.isEmpty()) { return; @@ -627,15 +585,15 @@ void DolphinPart::setFilesToSelect(const QList& files) m_view->markUrlAsCurrent(files.at(0)); } -bool DolphinPart::eventFilter(QObject* obj, QEvent* event) +bool DolphinPart::eventFilter(QObject *obj, QEvent *event) { using ShiftState = DolphinRemoveAction::ShiftState; const int type = event->type(); if ((type == QEvent::KeyPress || type == QEvent::KeyRelease) && m_removeAction) { - QMenu* menu = qobject_cast(obj); + QMenu *menu = qobject_cast(obj); if (menu && menu->parent() == m_view) { - QKeyEvent* ev = static_cast(event); + QKeyEvent *ev = static_cast(event); if (ev->key() == Qt::Key_Shift) { m_removeAction->update(type == QEvent::KeyPress ? ShiftState::Pressed : ShiftState::Released); } diff --git a/src/dolphinpart.h b/src/dolphinpart.h index a49603ca87..94f83d0ef4 100644 --- a/src/dolphinpart.h +++ b/src/dolphinpart.h @@ -29,29 +29,31 @@ class DolphinPart : public KParts::ReadOnlyPart // Used by konqueror. Technically it means "we want undo enabled if // there are things in the undo history and the current part is a dolphin part". // Even though it's konqueror doing the undo... - Q_PROPERTY( bool supportsUndo READ supportsUndo ) + Q_PROPERTY(bool supportsUndo READ supportsUndo) - Q_PROPERTY( QString currentViewMode READ currentViewMode WRITE setCurrentViewMode ) + Q_PROPERTY(QString currentViewMode READ currentViewMode WRITE setCurrentViewMode) // Used by konqueror when typing something like /home/dfaure/*.diff in the location bar - Q_PROPERTY( QString nameFilter READ nameFilter WRITE setNameFilter ) + Q_PROPERTY(QString nameFilter READ nameFilter WRITE setNameFilter) // Used by konqueror to implement the --select command-line option - Q_PROPERTY( QList filesToSelect READ filesToSelect WRITE setFilesToSelect ) + Q_PROPERTY(QList filesToSelect READ filesToSelect WRITE setFilesToSelect) public: - explicit DolphinPart(QWidget* parentWidget, QObject* parent, - const KPluginMetaData& metaData, const QVariantList& args); + explicit DolphinPart(QWidget *parentWidget, QObject *parent, const KPluginMetaData &metaData, const QVariantList &args); ~DolphinPart() override; /** * Standard KParts::ReadOnlyPart openUrl method. * Called by Konqueror to view a directory in DolphinPart. */ - bool openUrl(const QUrl& url) override; + bool openUrl(const QUrl &url) override; /// see the supportsUndo property - bool supportsUndo() const { return true; } + bool supportsUndo() const + { + return true; + } /** * Used by konqueror for setting the view mode @@ -59,7 +61,7 @@ public: * Those names come from the Actions line in dolphinpart.desktop, * and have to match the name of the KActions. */ - void setCurrentViewMode(const QString& viewModeName); + void setCurrentViewMode(const QString &viewModeName); /** * Used by konqueror for displaying the current view mode. @@ -68,23 +70,32 @@ public: QString currentViewMode() const; /// Returns the view owned by this part; used by DolphinPartBrowserExtension - DolphinView* view() { return m_view; } + DolphinView *view() + { + return m_view; + } /** * Sets a name filter, like *.diff */ - void setNameFilter(const QString& nameFilter); + void setNameFilter(const QString &nameFilter); /** * Returns the current name filter. Used by konqueror to show it in the URL. */ - QString nameFilter() const { return m_nameFilter; } + QString nameFilter() const + { + return m_nameFilter; + } protected: /** * We reimplement openUrl so no need to implement openFile. */ - bool openFile() override { return true; } + bool openFile() override + { + return true; + } Q_SIGNALS: /** @@ -92,28 +103,27 @@ Q_SIGNALS: */ void viewModeChanged(); - /** * Emitted whenever the current URL is about to be changed. */ void aboutToOpenURL(); private Q_SLOTS: - void slotMessage(const QString& msg); - void slotErrorMessage(const QString& msg); + void slotMessage(const QString &msg); + void slotErrorMessage(const QString &msg); /** * Shows the information for the item \a item inside the statusbar. If the * item is null, the default statusbar information is shown. */ - void slotRequestItemInfo(const KFileItem& item); + void slotRequestItemInfo(const KFileItem &item); /** * Handles clicking on an item */ - void slotItemActivated(const KFileItem& item); + void slotItemActivated(const KFileItem &item); /** * Handles activation of multiple items */ - void slotItemsActivated(const KFileItemList& items); + void slotItemsActivated(const KFileItemList &items); /** * Creates a new window showing the content of \a url. */ @@ -135,13 +145,13 @@ private Q_SLOTS: * Testcase 1: fish://localhost * Testcase 2: showing a directory that is being renamed by another window (#180156) */ - void slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl); + void slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl); /** * Updates the state of the 'Edit' menu actions and emits * the signal selectionChanged(). */ - void slotSelectionChanged(const KFileItemList& selection); + void slotSelectionChanged(const KFileItemList &selection); /** * Updates the text of the paste action dependent from @@ -152,7 +162,7 @@ private Q_SLOTS: /** * Connected to all "Go" menu actions provided by DolphinPart */ - void slotGoTriggered(QAction* action); + void slotGoTriggered(QAction *action); /** * Connected to the "editMimeType" action @@ -193,9 +203,9 @@ private Q_SLOTS: */ void updateStatusBar(); - /** - * Notify container of folder loading progress. - */ + /** + * Notify container of folder loading progress. + */ void updateProgress(int percent); void createDirectory(); @@ -204,31 +214,31 @@ private Q_SLOTS: * Called by konqueror --select */ void setFilesToSelect(const QList &files); - QList filesToSelect() const { return QList(); } // silence moc + QList filesToSelect() const + { + return QList(); + } // silence moc - bool eventFilter(QObject*, QEvent*) override; + bool eventFilter(QObject *, QEvent *) override; private: void createActions(); - void createGoAction(const char* name, const char* iconName, - const QString& text, const QString& url, - QActionGroup* actionGroup); + void createGoAction(const char *name, const char *iconName, const QString &text, const QString &url, QActionGroup *actionGroup); - void openSelectionDialog(const QString& title, const QString& text, - bool selectItems); + void openSelectionDialog(const QString &title, const QString &text, bool selectItems); QString urlToLocalFilePath(const QUrl &url); QString localFilePathOrHome() const; private: - DolphinView* m_view; - DolphinViewActionHandler* m_actionHandler; - DolphinRemoteEncoding* m_remoteEncoding; - DolphinPartBrowserExtension* m_extension; - DolphinNewFileMenu* m_newFileMenu; - QAction* m_findFileAction; - QAction* m_openTerminalAction; + DolphinView *m_view; + DolphinViewActionHandler *m_actionHandler; + DolphinRemoteEncoding *m_remoteEncoding; + DolphinPartBrowserExtension *m_extension; + DolphinNewFileMenu *m_newFileMenu; + QAction *m_findFileAction; + QAction *m_openTerminalAction; QString m_nameFilter; - DolphinRemoveAction* m_removeAction; + DolphinRemoveAction *m_removeAction; Q_DISABLE_COPY(DolphinPart) }; diff --git a/src/dolphinpart_ext.cpp b/src/dolphinpart_ext.cpp index a6d52e5836..9028b0358c 100644 --- a/src/dolphinpart_ext.cpp +++ b/src/dolphinpart_ext.cpp @@ -9,11 +9,10 @@ #include "dolphinpart.h" #include "views/dolphinview.h" -DolphinPartBrowserExtension::DolphinPartBrowserExtension(DolphinPart* part) - :KParts::BrowserExtension( part ) - ,m_part(part) +DolphinPartBrowserExtension::DolphinPartBrowserExtension(DolphinPart *part) + : KParts::BrowserExtension(part) + , m_part(part) { - } void DolphinPartBrowserExtension::restoreState(QDataStream &stream) @@ -43,7 +42,7 @@ void DolphinPartBrowserExtension::paste() m_part->view()->paste(); } -void DolphinPartBrowserExtension::pasteTo(const QUrl&) +void DolphinPartBrowserExtension::pasteTo(const QUrl &) { m_part->view()->pasteIntoFolder(); } @@ -53,10 +52,9 @@ void DolphinPartBrowserExtension::reparseConfiguration() m_part->view()->readSettings(); } - -DolphinPartFileInfoExtension::DolphinPartFileInfoExtension(DolphinPart* part) - :KParts::FileInfoExtension(part) - ,m_part(part) +DolphinPartFileInfoExtension::DolphinPartFileInfoExtension(DolphinPart *part) + : KParts::FileInfoExtension(part) + , m_part(part) { } @@ -75,26 +73,26 @@ KFileItemList DolphinPartFileInfoExtension::queryFor(KParts::FileInfoExtension:: KFileItemList list; if (mode == KParts::FileInfoExtension::None) - return list; + return list; if (!(supportedQueryModes() & mode)) - return list; + return list; switch (mode) { - case KParts::FileInfoExtension::SelectedItems: - if (hasSelection()) - return m_part->view()->selectedItems(); - break; - case KParts::FileInfoExtension::AllItems: - return m_part->view()->items(); - default: - break; + case KParts::FileInfoExtension::SelectedItems: + if (hasSelection()) + return m_part->view()->selectedItems(); + break; + case KParts::FileInfoExtension::AllItems: + return m_part->view()->items(); + default: + break; } return list; } -DolphinPartListingFilterExtension::DolphinPartListingFilterExtension(DolphinPart* part) +DolphinPartListingFilterExtension::DolphinPartListingFilterExtension(DolphinPart *part) : KParts::ListingFilterExtension(part) , m_part(part) { @@ -102,9 +100,7 @@ DolphinPartListingFilterExtension::DolphinPartListingFilterExtension(DolphinPart KParts::ListingFilterExtension::FilterModes DolphinPartListingFilterExtension::supportedFilterModes() const { - return (KParts::ListingFilterExtension::MimeType | - KParts::ListingFilterExtension::SubString | - KParts::ListingFilterExtension::WildCard); + return (KParts::ListingFilterExtension::MimeType | KParts::ListingFilterExtension::SubString | KParts::ListingFilterExtension::WildCard); } bool DolphinPartListingFilterExtension::supportsMultipleFilters(KParts::ListingFilterExtension::FilterMode mode) const @@ -134,7 +130,7 @@ QVariant DolphinPartListingFilterExtension::filter(KParts::ListingFilterExtensio return result; } -void DolphinPartListingFilterExtension::setFilter(KParts::ListingFilterExtension::FilterMode mode, const QVariant& filter) +void DolphinPartListingFilterExtension::setFilter(KParts::ListingFilterExtension::FilterMode mode, const QVariant &filter) { switch (mode) { case KParts::ListingFilterExtension::MimeType: @@ -151,24 +147,22 @@ void DolphinPartListingFilterExtension::setFilter(KParts::ListingFilterExtension //// -DolphinPartListingNotificationExtension::DolphinPartListingNotificationExtension(DolphinPart* part) +DolphinPartListingNotificationExtension::DolphinPartListingNotificationExtension(DolphinPart *part) : KParts::ListingNotificationExtension(part) { } KParts::ListingNotificationExtension::NotificationEventTypes DolphinPartListingNotificationExtension::supportedNotificationEventTypes() const { - return (KParts::ListingNotificationExtension::ItemsAdded | - KParts::ListingNotificationExtension::ItemsDeleted); + return (KParts::ListingNotificationExtension::ItemsAdded | KParts::ListingNotificationExtension::ItemsDeleted); } -void DolphinPartListingNotificationExtension::slotNewItems(const KFileItemList& items) +void DolphinPartListingNotificationExtension::slotNewItems(const KFileItemList &items) { Q_EMIT listingEvent(KParts::ListingNotificationExtension::ItemsAdded, items); } -void DolphinPartListingNotificationExtension::slotItemsDeleted(const KFileItemList& items) +void DolphinPartListingNotificationExtension::slotItemsDeleted(const KFileItemList &items) { Q_EMIT listingEvent(KParts::ListingNotificationExtension::ItemsDeleted, items); } - diff --git a/src/dolphinpart_ext.h b/src/dolphinpart_ext.h index 009bba9fe2..615f14252a 100644 --- a/src/dolphinpart_ext.h +++ b/src/dolphinpart_ext.h @@ -20,7 +20,7 @@ class DolphinPartBrowserExtension : public KParts::BrowserExtension { Q_OBJECT public: - explicit DolphinPartBrowserExtension( DolphinPart* part ); + explicit DolphinPartBrowserExtension(DolphinPart *part); void restoreState(QDataStream &stream) override; void saveState(QDataStream &stream) override; @@ -32,7 +32,7 @@ public Q_SLOTS: void reparseConfiguration(); private: - DolphinPart* m_part; + DolphinPart *m_part; }; class DolphinPartFileInfoExtension : public KParts::FileInfoExtension @@ -40,7 +40,7 @@ class DolphinPartFileInfoExtension : public KParts::FileInfoExtension Q_OBJECT public: - explicit DolphinPartFileInfoExtension(DolphinPart* part); + explicit DolphinPartFileInfoExtension(DolphinPart *part); QueryModes supportedQueryModes() const override; bool hasSelection() const override; @@ -48,7 +48,7 @@ public: KFileItemList queryFor(QueryMode mode) const override; private: - DolphinPart* m_part; + DolphinPart *m_part; }; class DolphinPartListingFilterExtension : public KParts::ListingFilterExtension @@ -56,14 +56,14 @@ class DolphinPartListingFilterExtension : public KParts::ListingFilterExtension Q_OBJECT public: - explicit DolphinPartListingFilterExtension(DolphinPart* part); + explicit DolphinPartListingFilterExtension(DolphinPart *part); FilterModes supportedFilterModes() const override; bool supportsMultipleFilters(FilterMode mode) const override; QVariant filter(FilterMode mode) const override; - void setFilter(FilterMode mode, const QVariant& filter) override; + void setFilter(FilterMode mode, const QVariant &filter) override; private: - DolphinPart* m_part; + DolphinPart *m_part; }; class DolphinPartListingNotificationExtension : public KParts::ListingNotificationExtension @@ -71,12 +71,12 @@ class DolphinPartListingNotificationExtension : public KParts::ListingNotificati Q_OBJECT public: - explicit DolphinPartListingNotificationExtension(DolphinPart* part); + explicit DolphinPartListingNotificationExtension(DolphinPart *part); NotificationEventTypes supportedNotificationEventTypes() const override; public Q_SLOTS: - void slotNewItems(const KFileItemList&); - void slotItemsDeleted(const KFileItemList&); + void slotNewItems(const KFileItemList &); + void slotItemsDeleted(const KFileItemList &); }; #endif diff --git a/src/dolphinplacesmodelsingleton.cpp b/src/dolphinplacesmodelsingleton.cpp index 5ce70edbac..2d8d3572d3 100644 --- a/src/dolphinplacesmodelsingleton.cpp +++ b/src/dolphinplacesmodelsingleton.cpp @@ -51,8 +51,7 @@ void DolphinPlacesModel::setPanelsLocked(bool locked) QStringList DolphinPlacesModel::mimeTypes() const { QStringList types = KFilePlacesModel::mimeTypes(); - types << DragAndDropHelper::arkDndServiceMimeType() - << DragAndDropHelper::arkDndPathMimeType(); + types << DragAndDropHelper::arkDndServiceMimeType() << DragAndDropHelper::arkDndPathMimeType(); return types; } @@ -121,7 +120,6 @@ bool DolphinPlacesModel::isTrash(const QModelIndex &index) const DolphinPlacesModelSingleton::DolphinPlacesModelSingleton() : m_placesModel(new DolphinPlacesModel(KAboutData::applicationData().componentName() + applicationNameSuffix())) { - } DolphinPlacesModelSingleton &DolphinPlacesModelSingleton::instance() diff --git a/src/dolphinplacesmodelsingleton.h b/src/dolphinplacesmodelsingleton.h index 13e1193423..a0524068f5 100644 --- a/src/dolphinplacesmodelsingleton.h +++ b/src/dolphinplacesmodelsingleton.h @@ -7,8 +7,8 @@ #ifndef DOLPHINPLACESMODELSINGLETON_H #define DOLPHINPLACESMODELSINGLETON_H -#include #include +#include #include @@ -50,17 +50,16 @@ private: */ class DolphinPlacesModelSingleton { - public: - static DolphinPlacesModelSingleton& instance(); + static DolphinPlacesModelSingleton &instance(); DolphinPlacesModel *placesModel() const; /** A suffix to the application-name of the stored bookmarks is added, which is only read by PlacesItemModel. */ static QString applicationNameSuffix(); - DolphinPlacesModelSingleton(const DolphinPlacesModelSingleton&) = delete; - DolphinPlacesModelSingleton& operator=(const DolphinPlacesModelSingleton&) = delete; + DolphinPlacesModelSingleton(const DolphinPlacesModelSingleton &) = delete; + DolphinPlacesModelSingleton &operator=(const DolphinPlacesModelSingleton &) = delete; private: DolphinPlacesModelSingleton(); diff --git a/src/dolphinrecenttabsmenu.cpp b/src/dolphinrecenttabsmenu.cpp index adc6a8edad..902325a1e9 100644 --- a/src/dolphinrecenttabsmenu.cpp +++ b/src/dolphinrecenttabsmenu.cpp @@ -12,8 +12,8 @@ #include -DolphinRecentTabsMenu::DolphinRecentTabsMenu(QObject* parent) : - KActionMenu(QIcon::fromTheme(QStringLiteral("edit-undo")), i18n("Recently Closed Tabs"), parent) +DolphinRecentTabsMenu::DolphinRecentTabsMenu(QObject *parent) + : KActionMenu(QIcon::fromTheme(QStringLiteral("edit-undo")), i18n("Recently Closed Tabs"), parent) { setPopupMode(QToolButton::InstantPopup); setEnabled(false); @@ -24,13 +24,12 @@ DolphinRecentTabsMenu::DolphinRecentTabsMenu(QObject* parent) : addSeparator(); - connect(menu(), &QMenu::triggered, - this, &DolphinRecentTabsMenu::handleAction); + connect(menu(), &QMenu::triggered, this, &DolphinRecentTabsMenu::handleAction); } -void DolphinRecentTabsMenu::rememberClosedTab(const QUrl& url, const QByteArray& state) +void DolphinRecentTabsMenu::rememberClosedTab(const QUrl &url, const QByteArray &state) { - QAction* action = new QAction(menu()); + QAction *action = new QAction(menu()); action->setText(url.path()); action->setData(state); const QString iconName = KIO::iconNameForUrl(url); @@ -59,12 +58,12 @@ void DolphinRecentTabsMenu::undoCloseTab() handleAction(menu()->actions().at(2)); } -void DolphinRecentTabsMenu::handleAction(QAction* action) +void DolphinRecentTabsMenu::handleAction(QAction *action) { if (action == m_clearListAction) { // Clear all actions except the "Empty Recently Closed Tabs" // action and the separator - QList actions = menu()->actions(); + QList actions = menu()->actions(); const int count = actions.size(); for (int i = count - 1; i >= 2; i--) { removeAction(actions.at(i)); diff --git a/src/dolphinrecenttabsmenu.h b/src/dolphinrecenttabsmenu.h index 74a7727d33..c4eaa3f6ad 100644 --- a/src/dolphinrecenttabsmenu.h +++ b/src/dolphinrecenttabsmenu.h @@ -18,21 +18,21 @@ class DolphinRecentTabsMenu : public KActionMenu Q_OBJECT public: - explicit DolphinRecentTabsMenu(QObject* parent); + explicit DolphinRecentTabsMenu(QObject *parent); public Q_SLOTS: - void rememberClosedTab(const QUrl& url, const QByteArray& state); + void rememberClosedTab(const QUrl &url, const QByteArray &state); void undoCloseTab(); Q_SIGNALS: - void restoreClosedTab(const QByteArray& state); + void restoreClosedTab(const QByteArray &state); void closedTabsCountChanged(unsigned int count); private Q_SLOTS: - void handleAction(QAction* action); + void handleAction(QAction *action); private: - QAction* m_clearListAction; + QAction *m_clearListAction; }; #endif diff --git a/src/dolphinremoveaction.cpp b/src/dolphinremoveaction.cpp index 811ae73c29..000a96e922 100644 --- a/src/dolphinremoveaction.cpp +++ b/src/dolphinremoveaction.cpp @@ -9,9 +9,9 @@ #include -DolphinRemoveAction::DolphinRemoveAction(QObject* parent, KActionCollection* collection) : - QAction(parent), - m_collection(collection) +DolphinRemoveAction::DolphinRemoveAction(QObject *parent, KActionCollection *collection) + : QAction(parent) + , m_collection(collection) { update(); connect(this, &DolphinRemoveAction::triggered, this, &DolphinRemoveAction::slotRemoveActionTriggered); diff --git a/src/dolphinremoveaction.h b/src/dolphinremoveaction.h index 7c3b49279e..645359da08 100644 --- a/src/dolphinremoveaction.h +++ b/src/dolphinremoveaction.h @@ -24,16 +24,11 @@ */ class DOLPHIN_EXPORT DolphinRemoveAction : public QAction { - Q_OBJECT + Q_OBJECT public: + enum class ShiftState { Unknown, Pressed, Released }; - enum class ShiftState { - Unknown, - Pressed, - Released - }; - - DolphinRemoveAction(QObject* parent, KActionCollection* collection); + DolphinRemoveAction(QObject *parent, KActionCollection *collection); /** * Updates this action key based on @p shiftState. diff --git a/src/dolphintabbar.cpp b/src/dolphintabbar.cpp index d3dc96393f..82695ac21a 100644 --- a/src/dolphintabbar.cpp +++ b/src/dolphintabbar.cpp @@ -13,10 +13,10 @@ #include #include -DolphinTabBar::DolphinTabBar(QWidget* parent) : - QTabBar(parent), - m_autoActivationIndex(-1), - m_tabToBeClosedOnMiddleMouseButtonRelease(-1) +DolphinTabBar::DolphinTabBar(QWidget *parent) + : QTabBar(parent) + , m_autoActivationIndex(-1) + , m_tabToBeClosedOnMiddleMouseButtonRelease(-1) { setAcceptDrops(true); setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab); @@ -26,13 +26,12 @@ DolphinTabBar::DolphinTabBar(QWidget* parent) : m_autoActivationTimer = new QTimer(this); m_autoActivationTimer->setSingleShot(true); m_autoActivationTimer->setInterval(800); - connect(m_autoActivationTimer, &QTimer::timeout, - this, &DolphinTabBar::slotAutoActivationTimeout); + connect(m_autoActivationTimer, &QTimer::timeout, this, &DolphinTabBar::slotAutoActivationTimeout); } -void DolphinTabBar::dragEnterEvent(QDragEnterEvent* event) +void DolphinTabBar::dragEnterEvent(QDragEnterEvent *event) { - const QMimeData* mimeData = event->mimeData(); + const QMimeData *mimeData = event->mimeData(); const int index = tabAt(event->pos()); if (mimeData->hasUrls()) { @@ -43,16 +42,16 @@ void DolphinTabBar::dragEnterEvent(QDragEnterEvent* event) QTabBar::dragEnterEvent(event); } -void DolphinTabBar::dragLeaveEvent(QDragLeaveEvent* event) +void DolphinTabBar::dragLeaveEvent(QDragLeaveEvent *event) { updateAutoActivationTimer(-1); QTabBar::dragLeaveEvent(event); } -void DolphinTabBar::dragMoveEvent(QDragMoveEvent* event) +void DolphinTabBar::dragMoveEvent(QDragMoveEvent *event) { - const QMimeData* mimeData = event->mimeData(); + const QMimeData *mimeData = event->mimeData(); const int index = tabAt(event->pos()); if (mimeData->hasUrls()) { @@ -62,12 +61,12 @@ void DolphinTabBar::dragMoveEvent(QDragMoveEvent* event) QTabBar::dragMoveEvent(event); } -void DolphinTabBar::dropEvent(QDropEvent* event) +void DolphinTabBar::dropEvent(QDropEvent *event) { // Disable the auto activation timer updateAutoActivationTimer(-1); - const QMimeData* mimeData = event->mimeData(); + const QMimeData *mimeData = event->mimeData(); const int index = tabAt(event->pos()); if (mimeData->hasUrls()) { @@ -77,7 +76,7 @@ void DolphinTabBar::dropEvent(QDropEvent* event) QTabBar::dropEvent(event); } -void DolphinTabBar::mousePressEvent(QMouseEvent* event) +void DolphinTabBar::mousePressEvent(QMouseEvent *event) { const int index = tabAt(event->pos()); @@ -93,8 +92,7 @@ void DolphinTabBar::mouseReleaseEvent(QMouseEvent *event) { const int index = tabAt(event->pos()); - if (index >= 0 && index == m_tabToBeClosedOnMiddleMouseButtonRelease - && event->button() == Qt::MiddleButton) { + if (index >= 0 && index == m_tabToBeClosedOnMiddleMouseButtonRelease && event->button() == Qt::MiddleButton) { // Mouse middle click on a tab closes this tab. Q_EMIT tabCloseRequested(index); return; @@ -103,7 +101,7 @@ void DolphinTabBar::mouseReleaseEvent(QMouseEvent *event) QTabBar::mouseReleaseEvent(event); } -void DolphinTabBar::mouseDoubleClickEvent(QMouseEvent* event) +void DolphinTabBar::mouseDoubleClickEvent(QMouseEvent *event) { const int index = tabAt(event->pos()); @@ -117,7 +115,7 @@ void DolphinTabBar::mouseDoubleClickEvent(QMouseEvent* event) QTabBar::mouseDoubleClickEvent(event); } -void DolphinTabBar::contextMenuEvent(QContextMenuEvent* event) +void DolphinTabBar::contextMenuEvent(QContextMenuEvent *event) { const int index = tabAt(event->pos()); @@ -125,12 +123,12 @@ void DolphinTabBar::contextMenuEvent(QContextMenuEvent* event) // Tab context menu QMenu menu(this); - QAction* newTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-new")), i18nc("@action:inmenu", "New Tab")); - QAction* detachTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-detach")), i18nc("@action:inmenu", "Detach Tab")); - QAction* closeOtherTabsAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-close-other")), i18nc("@action:inmenu", "Close Other Tabs")); - QAction* closeTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-close")), i18nc("@action:inmenu", "Close Tab")); + QAction *newTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-new")), i18nc("@action:inmenu", "New Tab")); + QAction *detachTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-detach")), i18nc("@action:inmenu", "Detach Tab")); + QAction *closeOtherTabsAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-close-other")), i18nc("@action:inmenu", "Close Other Tabs")); + QAction *closeTabAction = menu.addAction(QIcon::fromTheme(QStringLiteral("tab-close")), i18nc("@action:inmenu", "Close Tab")); - QAction* selectedAction = menu.exec(event->globalPos()); + QAction *selectedAction = menu.exec(event->globalPos()); if (selectedAction == newTabAction) { Q_EMIT openNewActivatedTab(index); } else if (selectedAction == detachTabAction) { diff --git a/src/dolphintabbar.h b/src/dolphintabbar.h index d601b0a9c3..1177cda934 100644 --- a/src/dolphintabbar.h +++ b/src/dolphintabbar.h @@ -14,26 +14,26 @@ class DolphinTabBar : public QTabBar Q_OBJECT public: - explicit DolphinTabBar(QWidget* parent); + explicit DolphinTabBar(QWidget *parent); Q_SIGNALS: void openNewActivatedTab(int index); - void tabDropEvent(int index, QDropEvent* event); + void tabDropEvent(int index, QDropEvent *event); void tabDetachRequested(int index); protected: - void dragEnterEvent(QDragEnterEvent* event) override; - void dragLeaveEvent(QDragLeaveEvent* event) override; - void dragMoveEvent(QDragMoveEvent* event) override; - void dropEvent(QDropEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; - void mouseDoubleClickEvent(QMouseEvent* event) override; + void dragEnterEvent(QDragEnterEvent *event) override; + void dragLeaveEvent(QDragLeaveEvent *event) override; + void dragMoveEvent(QDragMoveEvent *event) override; + void dropEvent(QDropEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void mouseDoubleClickEvent(QMouseEvent *event) override; /** * Opens a context menu for the tab on the \a event position. */ - void contextMenuEvent(QContextMenuEvent* event) override; + void contextMenuEvent(QContextMenuEvent *event) override; private Q_SLOTS: void slotAutoActivationTimeout(); @@ -46,7 +46,7 @@ private: void updateAutoActivationTimer(const int index); private: - QTimer* m_autoActivationTimer; + QTimer *m_autoActivationTimer; int m_autoActivationIndex; int m_tabToBeClosedOnMiddleMouseButtonRelease; }; diff --git a/src/dolphintabpage.cpp b/src/dolphintabpage.cpp index f6d288e7d1..c8da707dfe 100644 --- a/src/dolphintabpage.cpp +++ b/src/dolphintabpage.cpp @@ -14,12 +14,12 @@ #include #include -DolphinTabPage::DolphinTabPage(const QUrl &primaryUrl, const QUrl &secondaryUrl, QWidget* parent) : - QWidget(parent), - m_expandingContainer{nullptr}, - m_primaryViewActive(true), - m_splitViewEnabled(false), - m_active(true) +DolphinTabPage::DolphinTabPage(const QUrl &primaryUrl, const QUrl &secondaryUrl, QWidget *parent) + : QWidget(parent) + , m_expandingContainer{nullptr} + , m_primaryViewActive(true) + , m_splitViewEnabled(false) + , m_active(true) { QGridLayout *layout = new QGridLayout(this); layout->setSpacing(0); @@ -27,17 +27,14 @@ DolphinTabPage::DolphinTabPage(const QUrl &primaryUrl, const QUrl &secondaryUrl, m_splitter = new DolphinTabPageSplitter(Qt::Horizontal, this); m_splitter->setChildrenCollapsible(false); - connect(m_splitter, &QSplitter::splitterMoved, - this, &DolphinTabPage::splitterMoved); + connect(m_splitter, &QSplitter::splitterMoved, this, &DolphinTabPage::splitterMoved); layout->addWidget(m_splitter, 1, 0); layout->setRowStretch(1, 1); // Create a new primary view m_primaryViewContainer = createViewContainer(primaryUrl); - connect(m_primaryViewContainer->view(), &DolphinView::urlChanged, - this, &DolphinTabPage::activeViewUrlChanged); - connect(m_primaryViewContainer->view(), &DolphinView::redirection, - this, &DolphinTabPage::slotViewUrlRedirection); + connect(m_primaryViewContainer->view(), &DolphinView::urlChanged, this, &DolphinTabPage::activeViewUrlChanged); + connect(m_primaryViewContainer->view(), &DolphinView::redirection, this, &DolphinTabPage::slotViewUrlRedirection); m_splitter->addWidget(m_primaryViewContainer); m_primaryViewContainer->show(); @@ -46,7 +43,7 @@ DolphinTabPage::DolphinTabPage(const QUrl &primaryUrl, const QUrl &secondaryUrl, // Provide a secondary view, if the given secondary url is valid or if the // startup settings are set this way (use the url of the primary view). m_splitViewEnabled = true; - const QUrl& url = secondaryUrl.isValid() ? secondaryUrl : primaryUrl; + const QUrl &url = secondaryUrl.isValid() ? secondaryUrl : primaryUrl; m_secondaryViewContainer = createViewContainer(url); m_splitter->addWidget(m_secondaryViewContainer); m_secondaryViewContainer->show(); @@ -69,9 +66,8 @@ void DolphinTabPage::setSplitViewEnabled(bool enabled, Animated animated, const { if (m_splitViewEnabled != enabled) { m_splitViewEnabled = enabled; - if (animated == WithAnimation && ( - style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) < 1 || - GlobalConfig::animationDurationFactor() <= 0.0)) { + if (animated == WithAnimation + && (style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) < 1 || GlobalConfig::animationDurationFactor() <= 0.0)) { animated = WithoutAnimation; } if (m_expandViewAnimation) { @@ -83,7 +79,7 @@ void DolphinTabPage::setSplitViewEnabled(bool enabled, Animated animated, const if (enabled) { QList splitterSizes = m_splitter->sizes(); - const QUrl& url = (secondaryUrl.isEmpty()) ? m_primaryViewContainer->url() : secondaryUrl; + const QUrl &url = (secondaryUrl.isEmpty()) ? m_primaryViewContainer->url() : secondaryUrl; m_secondaryViewContainer = createViewContainer(url); auto secondaryNavigator = m_navigatorsWidget->secondaryUrlNavigator(); @@ -93,8 +89,7 @@ void DolphinTabPage::setSplitViewEnabled(bool enabled, Animated animated, const } m_secondaryViewContainer->connectUrlNavigator(secondaryNavigator); m_navigatorsWidget->setSecondaryNavigatorVisible(true); - m_navigatorsWidget->followViewContainersGeometry(m_primaryViewContainer, - m_secondaryViewContainer); + m_navigatorsWidget->followViewContainersGeometry(m_primaryViewContainer, m_secondaryViewContainer); m_splitter->addWidget(m_secondaryViewContainer); m_secondaryViewContainer->setActive(true); @@ -110,13 +105,12 @@ void DolphinTabPage::setSplitViewEnabled(bool enabled, Animated animated, const m_navigatorsWidget->setSecondaryNavigatorVisible(false); m_secondaryViewContainer->disconnectUrlNavigator(); - DolphinViewContainer* view; + DolphinViewContainer *view; if (GeneralSettings::closeActiveSplitView()) { view = activeViewContainer(); if (m_primaryViewActive) { m_primaryViewContainer->disconnectUrlNavigator(); - m_secondaryViewContainer->connectUrlNavigator( - m_navigatorsWidget->primaryUrlNavigator()); + m_secondaryViewContainer->connectUrlNavigator(m_navigatorsWidget->primaryUrlNavigator()); // If the primary view is active, we have to swap the pointers // because the secondary view will be the new primary view. @@ -127,8 +121,7 @@ void DolphinTabPage::setSplitViewEnabled(bool enabled, Animated animated, const view = m_primaryViewActive ? m_secondaryViewContainer : m_primaryViewContainer; if (!m_primaryViewActive) { m_primaryViewContainer->disconnectUrlNavigator(); - m_secondaryViewContainer->connectUrlNavigator( - m_navigatorsWidget->primaryUrlNavigator()); + m_secondaryViewContainer->connectUrlNavigator(m_navigatorsWidget->primaryUrlNavigator()); // If the secondary view is active, we have to swap the pointers // because the secondary view will be the new primary view. @@ -156,20 +149,19 @@ void DolphinTabPage::setSplitViewEnabled(bool enabled, Animated animated, const } } -DolphinViewContainer* DolphinTabPage::primaryViewContainer() const +DolphinViewContainer *DolphinTabPage::primaryViewContainer() const { return m_primaryViewContainer; } -DolphinViewContainer* DolphinTabPage::secondaryViewContainer() const +DolphinViewContainer *DolphinTabPage::secondaryViewContainer() const { return m_secondaryViewContainer; } -DolphinViewContainer* DolphinTabPage::activeViewContainer() const +DolphinViewContainer *DolphinTabPage::activeViewContainer() const { - return m_primaryViewActive ? m_primaryViewContainer : - m_secondaryViewContainer; + return m_primaryViewActive ? m_primaryViewContainer : m_secondaryViewContainer; } KFileItemList DolphinTabPage::selectedItems() const @@ -200,8 +192,7 @@ void DolphinTabPage::connectNavigators(DolphinNavigatorsWidgetAction *navigators auto secondaryNavigator = navigatorsWidget->secondaryUrlNavigator(); m_secondaryViewContainer->connectUrlNavigator(secondaryNavigator); } - m_navigatorsWidget->followViewContainersGeometry(m_primaryViewContainer, - m_secondaryViewContainer); + m_navigatorsWidget->followViewContainersGeometry(m_primaryViewContainer, m_secondaryViewContainer); } void DolphinTabPage::disconnectNavigators() @@ -213,7 +204,7 @@ void DolphinTabPage::disconnectNavigators() } } -void DolphinTabPage::insertNavigatorsWidget(DolphinNavigatorsWidgetAction* navigatorsWidget) +void DolphinTabPage::insertNavigatorsWidget(DolphinNavigatorsWidgetAction *navigatorsWidget) { QGridLayout *gridLayout = static_cast(layout()); if (navigatorsWidget->isInToolbar()) { @@ -226,7 +217,7 @@ void DolphinTabPage::insertNavigatorsWidget(DolphinNavigatorsWidgetAction* navig } } -void DolphinTabPage::markUrlsAsSelected(const QList& urls) +void DolphinTabPage::markUrlsAsSelected(const QList &urls) { m_primaryViewContainer->view()->markUrlsAsSelected(urls); if (m_splitViewEnabled) { @@ -234,7 +225,7 @@ void DolphinTabPage::markUrlsAsSelected(const QList& urls) } } -void DolphinTabPage::markUrlAsCurrent(const QUrl& url) +void DolphinTabPage::markUrlAsCurrent(const QUrl &url) { m_primaryViewContainer->view()->markUrlAsCurrent(url); if (m_splitViewEnabled) { @@ -275,7 +266,7 @@ QByteArray DolphinTabPage::saveState() const return state; } -void DolphinTabPage::restoreState(const QByteArray& state) +void DolphinTabPage::restoreState(const QByteArray &state) { if (state.isEmpty()) { return; @@ -343,8 +334,7 @@ void DolphinTabPage::slotAnimationFinished() { for (int i = 0; i < m_splitter->count(); ++i) { QWidget *viewContainer = m_splitter->widget(i); - if (viewContainer != m_primaryViewContainer && - viewContainer != m_secondaryViewContainer) { + if (viewContainer != m_primaryViewContainer && viewContainer != m_secondaryViewContainer) { viewContainer->close(); viewContainer->deleteLater(); } @@ -356,7 +346,7 @@ void DolphinTabPage::slotAnimationFinished() m_expandingContainer = nullptr; } -void DolphinTabPage::slotAnimationValueChanged(const QVariant& value) +void DolphinTabPage::slotAnimationValueChanged(const QVariant &value) { Q_CHECK_PTR(m_expandingContainer); const int indexOfExpandingContainer = m_splitter->indexOf(m_expandingContainer); @@ -373,8 +363,7 @@ void DolphinTabPage::slotAnimationValueChanged(const QVariant& value) // Reduce the size of the other widgets to make space for the expandingContainer. for (int i = m_splitter->count() - 1; i >= 0; --i) { - if (m_splitter->widget(i) == m_primaryViewContainer || - m_splitter->widget(i) == m_secondaryViewContainer) { + if (m_splitter->widget(i) == m_primaryViewContainer || m_splitter->widget(i) == m_secondaryViewContainer) { continue; } newSplitterSizes[i] = oldSplitterSizes.at(i) - expansionWidthNeeded; @@ -404,10 +393,9 @@ void DolphinTabPage::slotAnimationValueChanged(const QVariant& value) } } - void DolphinTabPage::slotViewActivated() { - const DolphinView* oldActiveView = activeViewContainer()->view(); + const DolphinView *oldActiveView = activeViewContainer()->view(); // Set the view, which was active before, to inactive // and update the active view type, if tab is active @@ -423,25 +411,21 @@ void DolphinTabPage::slotViewActivated() } } - const DolphinView* newActiveView = activeViewContainer()->view(); + const DolphinView *newActiveView = activeViewContainer()->view(); if (newActiveView == oldActiveView) { return; } - disconnect(oldActiveView, &DolphinView::urlChanged, - this, &DolphinTabPage::activeViewUrlChanged); - disconnect(oldActiveView, &DolphinView::redirection, - this, &DolphinTabPage::slotViewUrlRedirection); - connect(newActiveView, &DolphinView::urlChanged, - this, &DolphinTabPage::activeViewUrlChanged); - connect(newActiveView, &DolphinView::redirection, - this, &DolphinTabPage::slotViewUrlRedirection); + disconnect(oldActiveView, &DolphinView::urlChanged, this, &DolphinTabPage::activeViewUrlChanged); + disconnect(oldActiveView, &DolphinView::redirection, this, &DolphinTabPage::slotViewUrlRedirection); + connect(newActiveView, &DolphinView::urlChanged, this, &DolphinTabPage::activeViewUrlChanged); + connect(newActiveView, &DolphinView::redirection, this, &DolphinTabPage::slotViewUrlRedirection); Q_EMIT activeViewChanged(activeViewContainer()); Q_EMIT activeViewUrlChanged(activeViewContainer()->url()); } -void DolphinTabPage::slotViewUrlRedirection(const QUrl& oldUrl, const QUrl& newUrl) +void DolphinTabPage::slotViewUrlRedirection(const QUrl &oldUrl, const QUrl &newUrl) { Q_UNUSED(oldUrl) @@ -454,23 +438,21 @@ void DolphinTabPage::switchActiveView() return; } if (m_primaryViewActive) { - m_secondaryViewContainer->setActive(true); + m_secondaryViewContainer->setActive(true); } else { - m_primaryViewContainer->setActive(true); + m_primaryViewContainer->setActive(true); } } -DolphinViewContainer* DolphinTabPage::createViewContainer(const QUrl& url) const +DolphinViewContainer *DolphinTabPage::createViewContainer(const QUrl &url) const { - DolphinViewContainer* container = new DolphinViewContainer(url, m_splitter); + DolphinViewContainer *container = new DolphinViewContainer(url, m_splitter); container->setActive(false); - const DolphinView* view = container->view(); - connect(view, &DolphinView::activated, - this, &DolphinTabPage::slotViewActivated); + const DolphinView *view = container->view(); + connect(view, &DolphinView::activated, this, &DolphinTabPage::slotViewActivated); - connect(view, &DolphinView::toggleActiveViewRequested, - this, &DolphinTabPage::switchActiveView); + connect(view, &DolphinView::toggleActiveViewRequested, this, &DolphinTabPage::switchActiveView); return container; } @@ -478,21 +460,16 @@ DolphinViewContainer* DolphinTabPage::createViewContainer(const QUrl& url) const void DolphinTabPage::startExpandViewAnimation(DolphinViewContainer *expandingContainer) { Q_CHECK_PTR(expandingContainer); - Q_ASSERT(expandingContainer == m_primaryViewContainer || - expandingContainer == m_secondaryViewContainer); + Q_ASSERT(expandingContainer == m_primaryViewContainer || expandingContainer == m_secondaryViewContainer); m_expandingContainer = expandingContainer; m_expandViewAnimation = new QVariantAnimation(m_splitter); - m_expandViewAnimation->setDuration(2 * - style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * - GlobalConfig::animationDurationFactor()); + m_expandViewAnimation->setDuration(2 * style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * GlobalConfig::animationDurationFactor()); for (int i = 0; i < m_splitter->count(); ++i) { m_splitter->widget(i)->setMinimumWidth(1); } - connect(m_expandViewAnimation, &QAbstractAnimation::finished, - this, &DolphinTabPage::slotAnimationFinished); - connect(m_expandViewAnimation, &QVariantAnimation::valueChanged, - this, &DolphinTabPage::slotAnimationValueChanged); + connect(m_expandViewAnimation, &QAbstractAnimation::finished, this, &DolphinTabPage::slotAnimationFinished); + connect(m_expandViewAnimation, &QVariantAnimation::valueChanged, this, &DolphinTabPage::slotAnimationValueChanged); m_expandViewAnimation->setStartValue(expandingContainer->width()); if (m_splitViewEnabled) { // A new viewContainer is being opened. @@ -508,7 +485,8 @@ void DolphinTabPage::startExpandViewAnimation(DolphinViewContainer *expandingCon DolphinTabPageSplitterHandle::DolphinTabPageSplitterHandle(Qt::Orientation orientation, QSplitter *parent) : QSplitterHandle(orientation, parent) , m_mouseReleaseWasReceived(false) -{} +{ +} bool DolphinTabPageSplitterHandle::event(QEvent *event) { @@ -542,9 +520,10 @@ void DolphinTabPageSplitterHandle::resetSplitterSizes() DolphinTabPageSplitter::DolphinTabPageSplitter(Qt::Orientation orientation, QWidget *parent) : QSplitter(orientation, parent) -{} +{ +} -QSplitterHandle* DolphinTabPageSplitter::createHandle() +QSplitterHandle *DolphinTabPageSplitter::createHandle() { return new DolphinTabPageSplitterHandle(orientation(), this); } diff --git a/src/dolphintabpage.h b/src/dolphintabpage.h index abe65843a3..1c8ae094b8 100644 --- a/src/dolphintabpage.h +++ b/src/dolphintabpage.h @@ -11,9 +11,9 @@ #include "global.h" #include +#include #include #include -#include class DolphinNavigatorsWidgetAction; class DolphinViewContainer; @@ -26,7 +26,7 @@ class DolphinTabPage : public QWidget Q_OBJECT public: - explicit DolphinTabPage(const QUrl& primaryUrl, const QUrl& secondaryUrl = QUrl(), QWidget* parent = nullptr); + explicit DolphinTabPage(const QUrl &primaryUrl, const QUrl &secondaryUrl = QUrl(), QWidget *parent = nullptr); /** * @return True if primary view is the active view in this tab. @@ -54,17 +54,17 @@ public: /** * @return The primary view container. */ - DolphinViewContainer* primaryViewContainer() const; + DolphinViewContainer *primaryViewContainer() const; /** * @return The secondary view container, can be 0 if split view is disabled. */ - DolphinViewContainer* secondaryViewContainer() const; + DolphinViewContainer *secondaryViewContainer() const; /** * @return DolphinViewContainer of the active view */ - DolphinViewContainer* activeViewContainer() const; + DolphinViewContainer *activeViewContainer() const; /** * Returns the selected items. The list is empty if no item has been @@ -105,7 +105,7 @@ public: * Marks the item indicated by \p url to be scrolled to and as the * current item after directory DolphinView::url() has been loaded. */ - void markUrlAsCurrent(const QUrl& url); + void markUrlAsCurrent(const QUrl &url); /** * Refreshes the views of the main window by recreating them according to @@ -124,7 +124,7 @@ public: * Restores all tab related properties (urls, splitter layout, ...) from * the given \a state. */ - void restoreState(const QByteArray& state); + void restoreState(const QByteArray &state); /** * Set whether the tab page is active @@ -133,8 +133,8 @@ public: void setActive(bool active); Q_SIGNALS: - void activeViewChanged(DolphinViewContainer* viewContainer); - void activeViewUrlChanged(const QUrl& url); + void activeViewChanged(DolphinViewContainer *viewContainer); + void activeViewUrlChanged(const QUrl &url); void splitterMoved(int pos, int index); private Q_SLOTS: @@ -162,7 +162,7 @@ private Q_SLOTS: * * It emits the activeViewUrlChanged signal with the url \a newUrl. */ - void slotViewUrlRedirection(const QUrl& oldUrl, const QUrl& newUrl); + void slotViewUrlRedirection(const QUrl &oldUrl, const QUrl &newUrl); void switchActiveView(); @@ -170,7 +170,7 @@ private: /** * Creates a new view container and does the default initialization. */ - DolphinViewContainer* createViewContainer(const QUrl& url) const; + DolphinViewContainer *createViewContainer(const QUrl &url) const; /** * Starts an animation that transitions between split view mode states. @@ -224,7 +224,7 @@ public: explicit DolphinTabPageSplitter(Qt::Orientation orientation, QWidget *parent); protected: - QSplitterHandle* createHandle() override; + QSplitterHandle *createHandle() override; }; #endif // DOLPHIN_TAB_PAGE_H diff --git a/src/dolphintabwidget.cpp b/src/dolphintabwidget.cpp index 8f78dc2270..bb3680f583 100644 --- a/src/dolphintabwidget.cpp +++ b/src/dolphintabwidget.cpp @@ -10,35 +10,30 @@ #include "dolphintabbar.h" #include "dolphinviewcontainer.h" +#include #include +#include +#include #include #include -#include -#include -#include #include #include -DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction *navigatorsWidget, QWidget* parent) : - QTabWidget(parent), - m_lastViewedTab(nullptr), - m_navigatorsWidget{navigatorsWidget} +DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction *navigatorsWidget, QWidget *parent) + : QTabWidget(parent) + , m_lastViewedTab(nullptr) + , m_navigatorsWidget{navigatorsWidget} { KAcceleratorManager::setNoAccel(this); - connect(this, &DolphinTabWidget::tabCloseRequested, - this, QOverload::of(&DolphinTabWidget::closeTab)); - connect(this, &DolphinTabWidget::currentChanged, - this, &DolphinTabWidget::currentTabChanged); + connect(this, &DolphinTabWidget::tabCloseRequested, this, QOverload::of(&DolphinTabWidget::closeTab)); + connect(this, &DolphinTabWidget::currentChanged, this, &DolphinTabWidget::currentTabChanged); - DolphinTabBar* tabBar = new DolphinTabBar(this); - connect(tabBar, &DolphinTabBar::openNewActivatedTab, - this, QOverload::of(&DolphinTabWidget::openNewActivatedTab)); - connect(tabBar, &DolphinTabBar::tabDropEvent, - this, &DolphinTabWidget::tabDropEvent); - connect(tabBar, &DolphinTabBar::tabDetachRequested, - this, &DolphinTabWidget::detachTab); + DolphinTabBar *tabBar = new DolphinTabBar(this); + connect(tabBar, &DolphinTabBar::openNewActivatedTab, this, QOverload::of(&DolphinTabWidget::openNewActivatedTab)); + connect(tabBar, &DolphinTabBar::tabDropEvent, this, &DolphinTabWidget::tabDropEvent); + connect(tabBar, &DolphinTabBar::tabDetachRequested, this, &DolphinTabWidget::detachTab); tabBar->hide(); setTabBar(tabBar); @@ -47,41 +42,41 @@ DolphinTabWidget::DolphinTabWidget(DolphinNavigatorsWidgetAction *navigatorsWidg setUsesScrollButtons(true); } -DolphinTabPage* DolphinTabWidget::currentTabPage() const +DolphinTabPage *DolphinTabWidget::currentTabPage() const { return tabPageAt(currentIndex()); } -DolphinTabPage* DolphinTabWidget::nextTabPage() const +DolphinTabPage *DolphinTabWidget::nextTabPage() const { const int index = currentIndex() + 1; return tabPageAt(index < count() ? index : 0); } -DolphinTabPage* DolphinTabWidget::prevTabPage() const +DolphinTabPage *DolphinTabWidget::prevTabPage() const { const int index = currentIndex() - 1; return tabPageAt(index >= 0 ? index : (count() - 1)); } -DolphinTabPage* DolphinTabWidget::tabPageAt(const int index) const +DolphinTabPage *DolphinTabWidget::tabPageAt(const int index) const { - return static_cast(widget(index)); + return static_cast(widget(index)); } -void DolphinTabWidget::saveProperties(KConfigGroup& group) const +void DolphinTabWidget::saveProperties(KConfigGroup &group) const { const int tabCount = count(); group.writeEntry("Tab Count", tabCount); group.writeEntry("Active Tab Index", currentIndex()); for (int i = 0; i < tabCount; ++i) { - const DolphinTabPage* tabPage = tabPageAt(i); + const DolphinTabPage *tabPage = tabPageAt(i); group.writeEntry("Tab Data " % QString::number(i), tabPage->saveState()); } } -void DolphinTabWidget::readProperties(const KConfigGroup& group) +void DolphinTabWidget::readProperties(const KConfigGroup &group) { const int tabCount = group.readEntry("Tab Count", 0); for (int i = 0; i < tabCount; ++i) { @@ -132,12 +127,12 @@ void DolphinTabWidget::openNewActivatedTab() oldNavigatorState = m_navigatorsWidget->secondaryUrlNavigator()->visualState(); } - const DolphinViewContainer* oldActiveViewContainer = currentTabPage()->activeViewContainer(); + const DolphinViewContainer *oldActiveViewContainer = currentTabPage()->activeViewContainer(); Q_ASSERT(oldActiveViewContainer); openNewActivatedTab(oldActiveViewContainer->url()); - DolphinViewContainer* newActiveViewContainer = currentTabPage()->activeViewContainer(); + DolphinViewContainer *newActiveViewContainer = currentTabPage()->activeViewContainer(); Q_ASSERT(newActiveViewContainer); // The URL navigator of the new tab should have the same editable state @@ -148,7 +143,7 @@ void DolphinTabWidget::openNewActivatedTab() newActiveViewContainer->view()->setFocus(); } -void DolphinTabWidget::openNewActivatedTab(const QUrl& primaryUrl, const QUrl& secondaryUrl) +void DolphinTabWidget::openNewActivatedTab(const QUrl &primaryUrl, const QUrl &secondaryUrl) { openNewTab(primaryUrl, secondaryUrl); if (GeneralSettings::openNewTabAfterLastTab()) { @@ -158,16 +153,14 @@ void DolphinTabWidget::openNewActivatedTab(const QUrl& primaryUrl, const QUrl& s } } -void DolphinTabWidget::openNewTab(const QUrl& primaryUrl, const QUrl& secondaryUrl, DolphinTabWidget::NewTabPosition position) +void DolphinTabWidget::openNewTab(const QUrl &primaryUrl, const QUrl &secondaryUrl, DolphinTabWidget::NewTabPosition position) { - QWidget* focusWidget = QApplication::focusWidget(); + QWidget *focusWidget = QApplication::focusWidget(); - DolphinTabPage* tabPage = new DolphinTabPage(primaryUrl, secondaryUrl, this); + DolphinTabPage *tabPage = new DolphinTabPage(primaryUrl, secondaryUrl, this); tabPage->setActive(false); - connect(tabPage, &DolphinTabPage::activeViewChanged, - this, &DolphinTabWidget::activeViewChanged); - connect(tabPage, &DolphinTabPage::activeViewUrlChanged, - this, &DolphinTabWidget::tabUrlChanged); + connect(tabPage, &DolphinTabPage::activeViewChanged, this, &DolphinTabWidget::activeViewChanged); + connect(tabPage, &DolphinTabPage::activeViewUrlChanged, this, &DolphinTabWidget::tabUrlChanged); connect(tabPage->activeViewContainer(), &DolphinViewContainer::captionChanged, this, [this, tabPage]() { const int tabIndex = indexOf(tabPage); Q_ASSERT(tabIndex >= 0); @@ -196,7 +189,7 @@ void DolphinTabWidget::openNewTab(const QUrl& primaryUrl, const QUrl& secondaryU } } -void DolphinTabWidget::openDirectories(const QList& dirs, bool splitView) +void DolphinTabWidget::openDirectories(const QList &dirs, bool splitView) { Q_ASSERT(dirs.size() > 0); @@ -204,7 +197,7 @@ void DolphinTabWidget::openDirectories(const QList& dirs, bool splitView) QList::const_iterator it = dirs.constBegin(); while (it != dirs.constEnd()) { - const QUrl& primaryUrl = *(it++); + const QUrl &primaryUrl = *(it++); const std::optional viewIndexAtDirectory = viewOpenAtDirectory(primaryUrl); // When the user asks for a URL that's already open, @@ -213,7 +206,7 @@ void DolphinTabWidget::openDirectories(const QList& dirs, bool splitView) somethingWasAlreadyOpen = true; activateViewContainerAt(viewIndexAtDirectory.value()); } else if (splitView && (it != dirs.constEnd())) { - const QUrl& secondaryUrl = *(it++); + const QUrl &secondaryUrl = *(it++); if (somethingWasAlreadyOpen) { openNewTab(primaryUrl, secondaryUrl); } else { @@ -229,14 +222,14 @@ void DolphinTabWidget::openDirectories(const QList& dirs, bool splitView) } } -void DolphinTabWidget::openFiles(const QList& files, bool splitView) +void DolphinTabWidget::openFiles(const QList &files, bool splitView) { Q_ASSERT(files.size() > 0); // Get all distinct directories from 'files'. QList dirsThatNeedToBeOpened; QList dirsThatWereAlreadyOpen; - for (const QUrl& file : files) { + for (const QUrl &file : files) { const QUrl dir(file.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash)); if (dirsThatNeedToBeOpened.contains(dir) || dirsThatWereAlreadyOpen.contains(dir)) { continue; @@ -267,7 +260,7 @@ void DolphinTabWidget::openFiles(const QList& files, bool splitView) // tabs, there is no need to split 'files' accordingly, as // the DolphinView will just ignore invalid selections. for (int i = 0; i < tabCount; ++i) { - DolphinTabPage* tabPage = tabPageAt(i); + DolphinTabPage *tabPage = tabPageAt(i); tabPage->markUrlsAsSelected(files); tabPage->markUrlAsCurrent(files.first()); if (i < oldTabCount) { @@ -293,7 +286,7 @@ void DolphinTabWidget::closeTab(const int index) return; } - DolphinTabPage* tabPage = tabPageAt(index); + DolphinTabPage *tabPage = tabPageAt(index); Q_EMIT rememberClosedTab(tabPage->activeViewContainer()->url(), tabPage->saveState()); removeTab(index); @@ -324,7 +317,7 @@ void DolphinTabWidget::activatePrevTab() setCurrentIndex(index >= 0 ? index : (count() - 1)); } -void DolphinTabWidget::restoreClosedTab(const QByteArray& state) +void DolphinTabWidget::restoreClosedTab(const QByteArray &state) { openNewActivatedTab(); currentTabPage()->restoreState(state); @@ -332,8 +325,8 @@ void DolphinTabWidget::restoreClosedTab(const QByteArray& state) void DolphinTabWidget::copyToInactiveSplitView() { - const DolphinTabPage* tabPage = tabPageAt(currentIndex()); - DolphinViewContainer* activeViewContainer = currentTabPage()->activeViewContainer(); + const DolphinTabPage *tabPage = tabPageAt(currentIndex()); + DolphinViewContainer *activeViewContainer = currentTabPage()->activeViewContainer(); if (!tabPage->splitViewEnabled() || activeViewContainer->view()->selectedItems().isEmpty()) { return; } @@ -349,8 +342,8 @@ void DolphinTabWidget::copyToInactiveSplitView() void DolphinTabWidget::moveToInactiveSplitView() { - const DolphinTabPage* tabPage = tabPageAt(currentIndex()); - DolphinViewContainer* activeViewContainer = currentTabPage()->activeViewContainer(); + const DolphinTabPage *tabPage = tabPageAt(currentIndex()); + DolphinViewContainer *activeViewContainer = currentTabPage()->activeViewContainer(); if (!tabPage->splitViewEnabled() || activeViewContainer->view()->selectedItems().isEmpty()) { return; } @@ -370,7 +363,7 @@ void DolphinTabWidget::detachTab(int index) QStringList args; - const DolphinTabPage* tabPage = tabPageAt(index); + const DolphinTabPage *tabPage = tabPageAt(index); args << tabPage->primaryViewContainer()->url().url(); if (tabPage->splitViewEnabled()) { args << tabPage->secondaryViewContainer()->url().url(); @@ -388,14 +381,14 @@ void DolphinTabWidget::detachTab(int index) void DolphinTabWidget::openNewActivatedTab(int index) { Q_ASSERT(index >= 0); - const DolphinTabPage* tabPage = tabPageAt(index); + const DolphinTabPage *tabPage = tabPageAt(index); openNewActivatedTab(tabPage->activeViewContainer()->url()); } -void DolphinTabWidget::tabDropEvent(int index, QDropEvent* event) +void DolphinTabWidget::tabDropEvent(int index, QDropEvent *event) { if (index >= 0) { - DolphinView* view = tabPageAt(index)->activeViewContainer()->view(); + DolphinView *view = tabPageAt(index)->activeViewContainer()->view(); view->dropUrls(view->url(), event, view); } else { const auto urls = event->mimeData()->urls(); @@ -411,9 +404,9 @@ void DolphinTabWidget::tabDropEvent(int index, QDropEvent* event) } } -void DolphinTabWidget::tabUrlChanged(const QUrl& url) +void DolphinTabWidget::tabUrlChanged(const QUrl &url) { - const int index = indexOf(qobject_cast(sender())); + const int index = indexOf(qobject_cast(sender())); if (index >= 0) { tabBar()->setTabText(index, tabName(tabPageAt(index))); tabBar()->setTabToolTip(index, url.toDisplayString(QUrl::PreferLocalFile)); @@ -446,7 +439,7 @@ void DolphinTabWidget::currentTabChanged(int index) if (tabPage->splitViewEnabled() && !m_navigatorsWidget->secondaryUrlNavigator()) { m_navigatorsWidget->createSecondaryUrlNavigator(); } - DolphinViewContainer* viewContainer = tabPage->activeViewContainer(); + DolphinViewContainer *viewContainer = tabPage->activeViewContainer(); Q_EMIT activeViewChanged(viewContainer); Q_EMIT currentUrlChanged(viewContainer->url()); tabPage->setActive(true); @@ -492,12 +485,12 @@ void DolphinTabWidget::tabRemoved(int index) Q_EMIT tabCountChanged(count()); } -QString DolphinTabWidget::tabName(DolphinTabPage* tabPage) const +QString DolphinTabWidget::tabName(DolphinTabPage *tabPage) const { if (!tabPage) { return QString(); } - + // clang-format off QString name; if (tabPage->splitViewEnabled()) { if (tabPage->primaryViewActive()) { @@ -512,6 +505,7 @@ QString DolphinTabWidget::tabName(DolphinTabPage* tabPage) const } else { name = tabPage->activeViewContainer()->caption(); } + // clang-format on // Make sure that a '&' inside the directory name is displayed correctly // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText() @@ -538,7 +532,7 @@ DolphinViewContainer *DolphinTabWidget::activateViewContainerAt(DolphinTabWidget return viewContainer; } -const std::optional DolphinTabWidget::viewOpenAtDirectory(const QUrl& directory) const +const std::optional DolphinTabWidget::viewOpenAtDirectory(const QUrl &directory) const { int i = currentIndex(); if (i < 0) { @@ -556,13 +550,12 @@ const std::optional DolphinTabWidget::viewOpe } i = (i + 1) % count(); - } - while (i != currentIndex()); + } while (i != currentIndex()); return std::nullopt; } -const std::optional DolphinTabWidget::viewShowingItem(const QUrl& item) const +const std::optional DolphinTabWidget::viewShowingItem(const QUrl &item) const { // The item might not be loaded yet even though it exists. So instead // we check if the folder containing the item is showing its contents. @@ -600,8 +593,7 @@ const std::optional DolphinTabWidget::viewSho } i = (i + 1) % count(); - } - while (i != currentIndex()); + } while (i != currentIndex()); return std::nullopt; } diff --git a/src/dolphintabwidget.h b/src/dolphintabwidget.h index 24d9e228b4..75c6e3471a 100644 --- a/src/dolphintabwidget.h +++ b/src/dolphintabwidget.h @@ -23,7 +23,6 @@ class DolphinTabWidget : public QTabWidget Q_OBJECT public: - /** * @param navigatorsWidget The navigatorsWidget which is always going to be connected * to the active tabPage. @@ -42,27 +41,27 @@ public: /** * @return Tab page at the current index (can be 0 if tabs count is smaller than 1) */ - DolphinTabPage* currentTabPage() const; + DolphinTabPage *currentTabPage() const; /** * @return the next tab page. If the current active tab is the last tab, * it returns the first tab. If there is only one tab, returns nullptr */ - DolphinTabPage* nextTabPage() const; + DolphinTabPage *nextTabPage() const; /** * @return the previous tab page. If the current active tab is the first tab, * it returns the last tab. If there is only one tab, returns nullptr */ - DolphinTabPage* prevTabPage() const; + DolphinTabPage *prevTabPage() const; /** * @return Tab page at the given \a index (can be 0 if the index is out-of-range) */ - DolphinTabPage* tabPageAt(const int index) const; + DolphinTabPage *tabPageAt(const int index) const; - void saveProperties(KConfigGroup& group) const; - void readProperties(const KConfigGroup& group); + void saveProperties(KConfigGroup &group) const; + void readProperties(const KConfigGroup &group); /** * Refreshes the views of the main window by recreating them according to @@ -74,13 +73,13 @@ public: * @return Whether any of the tab pages has @p url opened * in their primary or secondary view. */ - bool isUrlOpen(const QUrl& url) const; + bool isUrlOpen(const QUrl &url) const; /** * @return Whether the item with @p url can be found in any view only by switching * between already open tabs and scrolling in their primary or secondary view. */ - bool isItemVisibleInAnyView(const QUrl& urlOfItem) const; + bool isItemVisibleInAnyView(const QUrl &urlOfItem) const; Q_SIGNALS: /** @@ -88,7 +87,7 @@ Q_SIGNALS: * tab or by activating another view when split view is enabled in the current * tab. */ - void activeViewChanged(DolphinViewContainer* viewContainer); + void activeViewChanged(DolphinViewContainer *viewContainer); /** * Is emitted when the number of open tabs has changed (e.g. by opening or @@ -99,13 +98,13 @@ Q_SIGNALS: /** * Is emitted when a tab has been closed. */ - void rememberClosedTab(const QUrl& url, const QByteArray& state); + void rememberClosedTab(const QUrl &url, const QByteArray &state); /** * Is emitted when the url of the current tab has been changed. This signal * is also emitted when the active view has been changed. */ - void currentUrlChanged(const QUrl& url); + void currentUrlChanged(const QUrl &url); public Q_SLOTS: /** @@ -118,7 +117,7 @@ public Q_SLOTS: * Opens a new tab showing the URL \a primaryUrl and the optional URL * \a secondaryUrl and activates the tab. */ - void openNewActivatedTab(const QUrl& primaryUrl, const QUrl& secondaryUrl = QUrl()); + void openNewActivatedTab(const QUrl &primaryUrl, const QUrl &secondaryUrl = QUrl()); /** * Opens a new tab in the background showing the URL \a primaryUrl and the @@ -131,7 +130,7 @@ public Q_SLOTS: * If \a splitView is set, 2 directories are collected within one tab. * \pre \a dirs must contain at least one url. */ - void openDirectories(const QList& dirs, bool splitView); + void openDirectories(const QList &dirs, bool splitView); /** * Opens the directories which contain the files \p files and selects all files. @@ -176,7 +175,7 @@ public Q_SLOTS: * Is called when the user wants to reopen a previously closed tab from * the recent tabs menu. */ - void restoreClosedTab(const QByteArray& state); + void restoreClosedTab(const QByteArray &state); /** Copies all selected items to the inactive view. */ void copyToInactiveSplitView(); @@ -201,13 +200,13 @@ private Q_SLOTS: * Is connected to the KTabBar signal receivedDropEvent. * Allows dragging and dropping files onto tabs. */ - void tabDropEvent(int tab, QDropEvent* event); + void tabDropEvent(int tab, QDropEvent *event); /** * The active view url of a tab has been changed so update the text and the * icon of the corresponding tab. */ - void tabUrlChanged(const QUrl& url); + void tabUrlChanged(const QUrl &url); void currentTabChanged(int index); @@ -220,7 +219,7 @@ private: * @param tabPage The tab page to get the name of * @return The name of the tab page */ - QString tabName(DolphinTabPage* tabPage) const; + QString tabName(DolphinTabPage *tabPage) const; struct ViewIndex { const int tabIndex; @@ -247,7 +246,7 @@ private: * @return a small struct containing the tab index of the view and whether it is * in the primary view. A std::nullopt is returned if there is no view open for @p directory. */ - const std::optional viewOpenAtDirectory(const QUrl& directory) const; + const std::optional viewOpenAtDirectory(const QUrl &directory) const; /** * Get the position of the view within this widget that has @p item in the view. @@ -257,7 +256,7 @@ private: * @return a small struct containing the tab index of the view and whether it is * in the primary view. A std::nullopt is returned if there is no view open that has @p item visible anywhere. */ - const std::optional viewShowingItem(const QUrl& item) const; + const std::optional viewShowingItem(const QUrl &item) const; private: QPointer m_lastViewedTab; diff --git a/src/dolphinurlnavigator.cpp b/src/dolphinurlnavigator.cpp index d8d325bb43..ad0a86b774 100644 --- a/src/dolphinurlnavigator.cpp +++ b/src/dolphinurlnavigator.cpp @@ -12,43 +12,43 @@ #include "dolphinurlnavigatorscontroller.h" #include "global.h" -#include #include +#include #include #include #include -DolphinUrlNavigator::DolphinUrlNavigator(QWidget *parent) : - DolphinUrlNavigator(QUrl(), parent) -{} - -DolphinUrlNavigator::DolphinUrlNavigator(const QUrl &url, QWidget *parent) : - KUrlNavigator(DolphinPlacesModelSingleton::instance().placesModel(), url, parent) +DolphinUrlNavigator::DolphinUrlNavigator(QWidget *parent) + : DolphinUrlNavigator(QUrl(), parent) { - const GeneralSettings* settings = GeneralSettings::self(); +} + +DolphinUrlNavigator::DolphinUrlNavigator(const QUrl &url, QWidget *parent) + : KUrlNavigator(DolphinPlacesModelSingleton::instance().placesModel(), url, parent) +{ + const GeneralSettings *settings = GeneralSettings::self(); setUrlEditable(settings->editableUrl()); setShowFullPath(settings->showFullPath()); setHomeUrl(Dolphin::homeUrl()); setPlacesSelectorVisible(DolphinUrlNavigatorsController::placesSelectorVisible()); editor()->setCompletionMode(KCompletion::CompletionMode(settings->urlCompletionMode())); setWhatsThis(xi18nc("@info:whatsthis location bar", - "This describes the location of the files and folders " - "displayed below.The name of the currently viewed " - "folder can be read at the very right. To the left of it is the " - "name of the folder that contains it. The whole line is called " - "the path to the current location because " - "following these folders from left to right leads here." - "This interactive path " - "is more powerful than one would expect. To learn more " - "about the basic and advanced features of the location bar " - "click here. " - "This will open the dedicated page in the Handbook.")); + "This describes the location of the files and folders " + "displayed below.The name of the currently viewed " + "folder can be read at the very right. To the left of it is the " + "name of the folder that contains it. The whole line is called " + "the path to the current location because " + "following these folders from left to right leads here." + "This interactive path " + "is more powerful than one would expect. To learn more " + "about the basic and advanced features of the location bar " + "click here. " + "This will open the dedicated page in the Handbook.")); DolphinUrlNavigatorsController::registerDolphinUrlNavigator(this); - connect(this, &KUrlNavigator::returnPressed, - this, &DolphinUrlNavigator::slotReturnPressed); + connect(this, &KUrlNavigator::returnPressed, this, &DolphinUrlNavigator::slotReturnPressed); } DolphinUrlNavigator::~DolphinUrlNavigator() @@ -85,7 +85,7 @@ std::unique_ptr DolphinUrlNavigator::visualSta return visualState; } -void DolphinUrlNavigator::setVisualState(const VisualState& visualState) +void DolphinUrlNavigator::setVisualState(const VisualState &visualState) { setUrlEditable(visualState.isUrlEditable); if (!visualState.isUrlEditable) { diff --git a/src/dolphinurlnavigatorscontroller.cpp b/src/dolphinurlnavigatorscontroller.cpp index 59e1d63561..bdf6513f19 100644 --- a/src/dolphinurlnavigatorscontroller.cpp +++ b/src/dolphinurlnavigatorscontroller.cpp @@ -46,8 +46,7 @@ bool DolphinUrlNavigatorsController::placesSelectorVisible() void DolphinUrlNavigatorsController::registerDolphinUrlNavigator(DolphinUrlNavigator *dolphinUrlNavigator) { s_instances.push_front(dolphinUrlNavigator); - connect(dolphinUrlNavigator->editor(), &KUrlComboBox::completionModeChanged, - DolphinUrlNavigatorsController::setCompletionMode); + connect(dolphinUrlNavigator->editor(), &KUrlComboBox::completionModeChanged, DolphinUrlNavigatorsController::setCompletionMode); } void DolphinUrlNavigatorsController::unregisterDolphinUrlNavigator(DolphinUrlNavigator *dolphinUrlNavigator) diff --git a/src/dolphinviewcontainer.cpp b/src/dolphinviewcontainer.cpp index 10e8860186..b00d59225a 100644 --- a/src/dolphinviewcontainer.cpp +++ b/src/dolphinviewcontainer.cpp @@ -6,6 +6,7 @@ #include "dolphinviewcontainer.h" +#include "dolphin_detailsmodesettings.h" #include "dolphin_generalsettings.h" #include "dolphindebug.h" #include "dolphinplacesmodelsingleton.h" @@ -14,7 +15,6 @@ #include "search/dolphinsearchbox.h" #include "selectionmode/topbar.h" #include "statusbar/dolphinstatusbar.h" -#include "dolphin_detailsmodesettings.h" #include #if HAVE_KACTIVITIES @@ -38,38 +38,38 @@ #include #include #include +#include #include #include -#include // An overview of the widgets contained by this ViewContainer struct LayoutStructure { - int searchBox = 0; - int messageWidget = 1; - int selectionModeTopBar = 2; - int view = 3; - int selectionModeBottomBar = 4; - int filterBar = 5; - int statusBar = 6; + int searchBox = 0; + int messageWidget = 1; + int selectionModeTopBar = 2; + int view = 3; + int selectionModeBottomBar = 4; + int filterBar = 5; + int statusBar = 6; }; constexpr LayoutStructure positionFor; -DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) : - QWidget(parent), - m_topLayout(nullptr), - m_urlNavigator{new DolphinUrlNavigator(url)}, - m_urlNavigatorConnected{nullptr}, - m_searchBox(nullptr), - m_searchModeEnabled(false), - m_messageWidget(nullptr), - m_selectionModeTopBar{nullptr}, - m_view(nullptr), - m_filterBar(nullptr), - m_selectionModeBottomBar{nullptr}, - m_statusBar(nullptr), - m_statusBarTimer(nullptr), - m_statusBarTimestamp(), - m_autoGrabFocus(true) +DolphinViewContainer::DolphinViewContainer(const QUrl &url, QWidget *parent) + : QWidget(parent) + , m_topLayout(nullptr) + , m_urlNavigator{new DolphinUrlNavigator(url)} + , m_urlNavigatorConnected{nullptr} + , m_searchBox(nullptr) + , m_searchModeEnabled(false) + , m_messageWidget(nullptr) + , m_selectionModeTopBar{nullptr} + , m_view(nullptr) + , m_filterBar(nullptr) + , m_selectionModeBottomBar{nullptr} + , m_statusBar(nullptr) + , m_statusBarTimer(nullptr) + , m_statusBarTimestamp() + , m_autoGrabFocus(true) #if HAVE_KACTIVITIES , m_activityResourceInstance(nullptr) #endif @@ -87,17 +87,17 @@ DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) : connect(m_searchBox, &DolphinSearchBox::searchRequest, this, &DolphinViewContainer::startSearching); connect(m_searchBox, &DolphinSearchBox::focusViewRequest, this, &DolphinViewContainer::requestFocus); m_searchBox->setWhatsThis(xi18nc("@info:whatsthis findbar", - "This helps you find files and folders. Enter a " - "search term and specify search settings with the " - "buttons at the bottom:Filename/Content: " - "Does the item you are looking for contain the search terms " - "within its filename or its contents?The contents of images, " - "audio files and videos will not be searched." - "From Here/Everywhere: Do you want to search in this " - "folder and its sub-folders or everywhere?" - "More Options: Click this to search by media type, access " - "time or rating.More Search Tools: Install other " - "means to find an item.")); + "This helps you find files and folders. Enter a " + "search term and specify search settings with the " + "buttons at the bottom:Filename/Content: " + "Does the item you are looking for contain the search terms " + "within its filename or its contents?The contents of images, " + "audio files and videos will not be searched." + "From Here/Everywhere: Do you want to search in this " + "folder and its sub-folders or everywhere?" + "More Options: Click this to search by media type, access " + "time or rating.More Search Tools: Install other " + "means to find an item.")); m_messageWidget = new KMessageWidget(this); m_messageWidget->setCloseButtonVisible(true); @@ -105,7 +105,6 @@ DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) : #ifndef Q_OS_WIN if (getuid() == 0) { - // We must be logged in as the root user; show a big scary warning showMessage(i18n("Running Dolphin as root can be dangerous. Please be careful."), Warning); } @@ -115,95 +114,59 @@ DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) : m_filterBar = new FilterBar(this); m_filterBar->setVisible(GeneralSettings::filterBar()); - connect(m_filterBar, &FilterBar::filterChanged, - this, &DolphinViewContainer::setNameFilter); - connect(m_filterBar, &FilterBar::closeRequest, - this, &DolphinViewContainer::closeFilterBar); - connect(m_filterBar, &FilterBar::focusViewRequest, - this, &DolphinViewContainer::requestFocus); + connect(m_filterBar, &FilterBar::filterChanged, this, &DolphinViewContainer::setNameFilter); + connect(m_filterBar, &FilterBar::closeRequest, this, &DolphinViewContainer::closeFilterBar); + connect(m_filterBar, &FilterBar::focusViewRequest, this, &DolphinViewContainer::requestFocus); // Initialize the main view m_view = new DolphinView(url, this); - connect(m_view, &DolphinView::urlChanged, - m_filterBar, &FilterBar::clearIfUnlocked); - connect(m_view, &DolphinView::urlChanged, - m_messageWidget, &KMessageWidget::hide); + connect(m_view, &DolphinView::urlChanged, m_filterBar, &FilterBar::clearIfUnlocked); + connect(m_view, &DolphinView::urlChanged, m_messageWidget, &KMessageWidget::hide); // m_urlNavigator stays in sync with m_view's location changes and // keeps track of them so going back and forth in the history works. - connect(m_view, &DolphinView::urlChanged, - m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl); - connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlChanged, - this, &DolphinViewContainer::slotUrlNavigatorLocationChanged); - connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlAboutToBeChanged, - this, &DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged); - connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlSelectionRequested, - this, &DolphinViewContainer::slotUrlSelectionRequested); - connect(m_view, &DolphinView::writeStateChanged, - this, &DolphinViewContainer::writeStateChanged); - connect(m_view, &DolphinView::requestItemInfo, - this, &DolphinViewContainer::showItemInfo); - connect(m_view, &DolphinView::itemActivated, - this, &DolphinViewContainer::slotItemActivated); - connect(m_view, &DolphinView::itemsActivated, - this, &DolphinViewContainer::slotItemsActivated); - connect(m_view, &DolphinView::redirection, - this, &DolphinViewContainer::redirect); - connect(m_view, &DolphinView::directoryLoadingStarted, - this, &DolphinViewContainer::slotDirectoryLoadingStarted); - connect(m_view, &DolphinView::directoryLoadingCompleted, - this, &DolphinViewContainer::slotDirectoryLoadingCompleted); - connect(m_view, &DolphinView::directoryLoadingCanceled, - this, &DolphinViewContainer::slotDirectoryLoadingCanceled); - connect(m_view, &DolphinView::itemCountChanged, - this, &DolphinViewContainer::delayedStatusBarUpdate); - connect(m_view, &DolphinView::directoryLoadingProgress, - this, &DolphinViewContainer::updateDirectoryLoadingProgress); - connect(m_view, &DolphinView::directorySortingProgress, - this, &DolphinViewContainer::updateDirectorySortingProgress); - connect(m_view, &DolphinView::selectionChanged, - this, &DolphinViewContainer::delayedStatusBarUpdate); - connect(m_view, &DolphinView::errorMessage, - this, &DolphinViewContainer::showErrorMessage); - connect(m_view, &DolphinView::urlIsFileError, - this, &DolphinViewContainer::slotUrlIsFileError); - connect(m_view, &DolphinView::activated, - this, &DolphinViewContainer::activate); - connect(m_view, &DolphinView::hiddenFilesShownChanged, - this, &DolphinViewContainer::slotHiddenFilesShownChanged); - connect(m_view, &DolphinView::sortHiddenLastChanged, - this, &DolphinViewContainer::slotSortHiddenLastChanged); - connect(m_view, &DolphinView::currentDirectoryRemoved, - this, &DolphinViewContainer::slotCurrentDirectoryRemoved); + connect(m_view, &DolphinView::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl); + connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationChanged); + connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlAboutToBeChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged); + connect(m_urlNavigator.get(), &DolphinUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested); + connect(m_view, &DolphinView::writeStateChanged, this, &DolphinViewContainer::writeStateChanged); + connect(m_view, &DolphinView::requestItemInfo, this, &DolphinViewContainer::showItemInfo); + connect(m_view, &DolphinView::itemActivated, this, &DolphinViewContainer::slotItemActivated); + connect(m_view, &DolphinView::itemsActivated, this, &DolphinViewContainer::slotItemsActivated); + connect(m_view, &DolphinView::redirection, this, &DolphinViewContainer::redirect); + connect(m_view, &DolphinView::directoryLoadingStarted, this, &DolphinViewContainer::slotDirectoryLoadingStarted); + connect(m_view, &DolphinView::directoryLoadingCompleted, this, &DolphinViewContainer::slotDirectoryLoadingCompleted); + connect(m_view, &DolphinView::directoryLoadingCanceled, this, &DolphinViewContainer::slotDirectoryLoadingCanceled); + connect(m_view, &DolphinView::itemCountChanged, this, &DolphinViewContainer::delayedStatusBarUpdate); + connect(m_view, &DolphinView::directoryLoadingProgress, this, &DolphinViewContainer::updateDirectoryLoadingProgress); + connect(m_view, &DolphinView::directorySortingProgress, this, &DolphinViewContainer::updateDirectorySortingProgress); + connect(m_view, &DolphinView::selectionChanged, this, &DolphinViewContainer::delayedStatusBarUpdate); + connect(m_view, &DolphinView::errorMessage, this, &DolphinViewContainer::showErrorMessage); + connect(m_view, &DolphinView::urlIsFileError, this, &DolphinViewContainer::slotUrlIsFileError); + connect(m_view, &DolphinView::activated, this, &DolphinViewContainer::activate); + connect(m_view, &DolphinView::hiddenFilesShownChanged, this, &DolphinViewContainer::slotHiddenFilesShownChanged); + connect(m_view, &DolphinView::sortHiddenLastChanged, this, &DolphinViewContainer::slotSortHiddenLastChanged); + connect(m_view, &DolphinView::currentDirectoryRemoved, this, &DolphinViewContainer::slotCurrentDirectoryRemoved); // Initialize status bar m_statusBar = new DolphinStatusBar(this); m_statusBar->setUrl(m_view->url()); m_statusBar->setZoomLevel(m_view->zoomLevel()); - connect(m_view, &DolphinView::urlChanged, - m_statusBar, &DolphinStatusBar::setUrl); - connect(m_view, &DolphinView::zoomLevelChanged, - m_statusBar, &DolphinStatusBar::setZoomLevel); - connect(m_view, &DolphinView::infoMessage, - m_statusBar, &DolphinStatusBar::setText); - connect(m_view, &DolphinView::operationCompletedMessage, - m_statusBar, &DolphinStatusBar::setText); - connect(m_view, &DolphinView::statusBarTextChanged, - m_statusBar, &DolphinStatusBar::setDefaultText); - connect(m_view, &DolphinView::statusBarTextChanged, - m_statusBar, &DolphinStatusBar::resetToDefaultText); - connect(m_statusBar, &DolphinStatusBar::stopPressed, - this, &DolphinViewContainer::stopDirectoryLoading); - connect(m_statusBar, &DolphinStatusBar::zoomLevelChanged, - this, &DolphinViewContainer::slotStatusBarZoomLevelChanged); + connect(m_view, &DolphinView::urlChanged, m_statusBar, &DolphinStatusBar::setUrl); + connect(m_view, &DolphinView::zoomLevelChanged, m_statusBar, &DolphinStatusBar::setZoomLevel); + connect(m_view, &DolphinView::infoMessage, m_statusBar, &DolphinStatusBar::setText); + connect(m_view, &DolphinView::operationCompletedMessage, m_statusBar, &DolphinStatusBar::setText); + connect(m_view, &DolphinView::statusBarTextChanged, m_statusBar, &DolphinStatusBar::setDefaultText); + connect(m_view, &DolphinView::statusBarTextChanged, m_statusBar, &DolphinStatusBar::resetToDefaultText); + connect(m_statusBar, &DolphinStatusBar::stopPressed, this, &DolphinViewContainer::stopDirectoryLoading); + connect(m_statusBar, &DolphinStatusBar::zoomLevelChanged, this, &DolphinViewContainer::slotStatusBarZoomLevelChanged); m_statusBarTimer = new QTimer(this); m_statusBarTimer->setSingleShot(true); m_statusBarTimer->setInterval(300); connect(m_statusBarTimer, &QTimer::timeout, this, &DolphinViewContainer::updateStatusBar); - KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self(); - connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, - this, &DolphinViewContainer::delayedStatusBarUpdate); + KIO::FileUndoManager *undoManager = KIO::FileUndoManager::self(); + connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinViewContainer::delayedStatusBarUpdate); m_topLayout->addWidget(m_searchBox, positionFor.searchBox, 0); m_topLayout->addWidget(m_messageWidget, positionFor.messageWidget, 0); @@ -220,15 +183,11 @@ DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) : }); KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel(); - connect(placesModel, &KFilePlacesModel::dataChanged, - this, &DolphinViewContainer::slotPlacesModelChanged); - connect(placesModel, &KFilePlacesModel::rowsInserted, - this, &DolphinViewContainer::slotPlacesModelChanged); - connect(placesModel, &KFilePlacesModel::rowsRemoved, - this, &DolphinViewContainer::slotPlacesModelChanged); + connect(placesModel, &KFilePlacesModel::dataChanged, this, &DolphinViewContainer::slotPlacesModelChanged); + connect(placesModel, &KFilePlacesModel::rowsInserted, this, &DolphinViewContainer::slotPlacesModelChanged); + connect(placesModel, &KFilePlacesModel::rowsRemoved, this, &DolphinViewContainer::slotPlacesModelChanged); - connect(this, &DolphinViewContainer::searchModeEnabledChanged, - this, &DolphinViewContainer::captionChanged); + connect(this, &DolphinViewContainer::searchModeEnabledChanged, this, &DolphinViewContainer::captionChanged); // Initialize kactivities resource instance @@ -281,25 +240,25 @@ bool DolphinViewContainer::autoGrabFocus() const QString DolphinViewContainer::currentSearchText() const { - return m_searchBox->text(); + return m_searchBox->text(); } -const DolphinStatusBar* DolphinViewContainer::statusBar() const +const DolphinStatusBar *DolphinViewContainer::statusBar() const { return m_statusBar; } -DolphinStatusBar* DolphinViewContainer::statusBar() +DolphinStatusBar *DolphinViewContainer::statusBar() { return m_statusBar; } -const DolphinUrlNavigator* DolphinViewContainer::urlNavigator() const +const DolphinUrlNavigator *DolphinViewContainer::urlNavigator() const { return m_urlNavigatorConnected; } -DolphinUrlNavigator* DolphinViewContainer::urlNavigator() +DolphinUrlNavigator *DolphinViewContainer::urlNavigator() { return m_urlNavigatorConnected; } @@ -314,12 +273,12 @@ DolphinUrlNavigator *DolphinViewContainer::urlNavigatorInternalWithHistory() return m_urlNavigator.get(); } -const DolphinView* DolphinViewContainer::view() const +const DolphinView *DolphinViewContainer::view() const { return m_view; } -DolphinView* DolphinViewContainer::view() +DolphinView *DolphinViewContainer::view() { return m_view; } @@ -341,17 +300,13 @@ void DolphinViewContainer::connectUrlNavigator(DolphinUrlNavigator *urlNavigator urlNavigator->setActive(isActive()); // Url changes are still done via m_urlNavigator. - connect(urlNavigator, &DolphinUrlNavigator::urlChanged, - m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl); - connect(urlNavigator, &DolphinUrlNavigator::urlsDropped, - this, [=](const QUrl &destination, QDropEvent *event) { + connect(urlNavigator, &DolphinUrlNavigator::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl); + connect(urlNavigator, &DolphinUrlNavigator::urlsDropped, this, [=](const QUrl &destination, QDropEvent *event) { m_view->dropUrls(destination, event, urlNavigator->dropWidget()); }); // Aside from these, only visual things need to be connected. - connect(m_view, &DolphinView::urlChanged, - urlNavigator, &DolphinUrlNavigator::setLocationUrl); - connect(urlNavigator, &DolphinUrlNavigator::activated, - this, &DolphinViewContainer::activate); + connect(m_view, &DolphinView::urlChanged, urlNavigator, &DolphinUrlNavigator::setLocationUrl); + connect(urlNavigator, &DolphinUrlNavigator::activated, this, &DolphinViewContainer::activate); m_urlNavigatorConnected = urlNavigator; } @@ -362,14 +317,10 @@ void DolphinViewContainer::disconnectUrlNavigator() return; } - disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlChanged, - m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl); - disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlsDropped, - this, nullptr); - disconnect(m_view, &DolphinView::urlChanged, - m_urlNavigatorConnected, &DolphinUrlNavigator::setLocationUrl); - disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::activated, - this, &DolphinViewContainer::activate); + disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlChanged, m_urlNavigator.get(), &DolphinUrlNavigator::setLocationUrl); + disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::urlsDropped, this, nullptr); + disconnect(m_view, &DolphinView::urlChanged, m_urlNavigatorConnected, &DolphinUrlNavigator::setLocationUrl); + disconnect(m_urlNavigatorConnected, &DolphinUrlNavigator::activated, this, &DolphinViewContainer::activate); m_urlNavigatorVisualState = m_urlNavigatorConnected->visualState(); m_urlNavigatorConnected = nullptr; @@ -435,13 +386,13 @@ bool DolphinViewContainer::isSelectionModeEnabled() const const bool isEnabled = m_view->selectionMode(); Q_ASSERT((!isEnabled // We can't assert that the bars are invisible only because the selection mode is disabled because the hide animation might still be playing. - && (!m_selectionModeBottomBar || !m_selectionModeBottomBar->isEnabled() || - !m_selectionModeBottomBar->isVisible() || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::PasteContents)) - || ( isEnabled - && m_selectionModeTopBar && m_selectionModeTopBar->isVisible() - // The bottom bar is either visible or was hidden because it has nothing to show in GeneralContents mode e.g. because no items are selected. - && m_selectionModeBottomBar - && (m_selectionModeBottomBar->isVisible() || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::GeneralContents))); + && (!m_selectionModeBottomBar || !m_selectionModeBottomBar->isEnabled() || !m_selectionModeBottomBar->isVisible() + || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::PasteContents)) + || (isEnabled && m_selectionModeTopBar + && m_selectionModeTopBar->isVisible() + // The bottom bar is either visible or was hidden because it has nothing to show in GeneralContents mode e.g. because no items are selected. + && m_selectionModeBottomBar + && (m_selectionModeBottomBar->isVisible() || m_selectionModeBottomBar->contents() == SelectionMode::BottomBar::GeneralContents))); return isEnabled; } @@ -452,8 +403,7 @@ void DolphinViewContainer::slotSplitTabDisabled() } } - -void DolphinViewContainer::showMessage(const QString& msg, MessageType type) +void DolphinViewContainer::showMessage(const QString &msg, MessageType type) { if (msg.isEmpty()) { return; @@ -466,9 +416,15 @@ void DolphinViewContainer::showMessage(const QString& msg, MessageType type) m_messageWidget->setWordWrap(true); switch (type) { - case Information: m_messageWidget->setMessageType(KMessageWidget::Information); break; - case Warning: m_messageWidget->setMessageType(KMessageWidget::Warning); break; - case Error: m_messageWidget->setMessageType(KMessageWidget::Error); break; + case Information: + m_messageWidget->setMessageType(KMessageWidget::Information); + break; + case Warning: + m_messageWidget->setMessageType(KMessageWidget::Warning); + break; + case Error: + m_messageWidget->setMessageType(KMessageWidget::Error); + break; default: Q_ASSERT(false); break; @@ -507,7 +463,7 @@ void DolphinViewContainer::setSearchModeEnabled(bool enabled) m_searchBox->setVisible(enabled); if (enabled) { - const QUrl& locationUrl = m_urlNavigator->locationUrl(); + const QUrl &locationUrl = m_urlNavigator->locationUrl(); m_searchBox->fromSearchUrl(locationUrl); } @@ -581,7 +537,7 @@ QString DolphinViewContainer::captionWindowTitle() const QString DolphinViewContainer::caption() const { if (isSearchModeEnabled()) { - if (currentSearchText().isEmpty()){ + if (currentSearchText().isEmpty()) { return i18n("Search"); } else { return i18n("Search for %1", currentSearchText()); @@ -590,13 +546,13 @@ QString DolphinViewContainer::caption() const KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel(); const QString pattern = url().adjusted(QUrl::StripTrailingSlash).toString(QUrl::FullyEncoded).append("/?"); - const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, QRegularExpression::anchoredPattern(pattern), 1, Qt::MatchRegularExpression); + const auto &matchedPlaces = + placesModel->match(placesModel->index(0, 0), KFilePlacesModel::UrlRole, QRegularExpression::anchoredPattern(pattern), 1, Qt::MatchRegularExpression); if (!matchedPlaces.isEmpty()) { return placesModel->text(matchedPlaces.first()); } - if (!url().isLocalFile()) { QUrl adjustedUrl = url().adjusted(QUrl::StripTrailingSlash); QString caption; @@ -620,7 +576,7 @@ QString DolphinViewContainer::caption() const return fileName; } -void DolphinViewContainer::setUrl(const QUrl& newUrl) +void DolphinViewContainer::setUrl(const QUrl &newUrl) { if (newUrl != m_urlNavigator->locationUrl()) { m_urlNavigator->setLocationUrl(newUrl); @@ -724,14 +680,14 @@ void DolphinViewContainer::slotDirectoryLoadingCanceled() m_statusBar->setText(QString()); } -void DolphinViewContainer::slotUrlIsFileError(const QUrl& url) +void DolphinViewContainer::slotUrlIsFileError(const QUrl &url) { const KFileItem item(url); // Find out if the file can be opened in the view (for example, this is the // case if the file is an archive). The mime type must be known for that. item.determineMimeType(); - const QUrl& folderUrl = DolphinView::openItemAsFolderUrl(item, true); + const QUrl &folderUrl = DolphinView::openItemAsFolderUrl(item, true); if (!folderUrl.isEmpty()) { setUrl(folderUrl); } else { @@ -746,7 +702,7 @@ void DolphinViewContainer::slotItemActivated(const KFileItem &item) // results in an active view. m_view->setActive(true); - const QUrl& url = DolphinView::openItemAsFolderUrl(item, GeneralSettings::browseThroughArchives()); + const QUrl &url = DolphinView::openItemAsFolderUrl(item, GeneralSettings::browseThroughArchives()); if (!url.isEmpty()) { const auto modifiers = QGuiApplication::keyboardModifiers(); // keep in sync with KUrlNavigator::slotNavigatorButtonClicked @@ -773,7 +729,7 @@ void DolphinViewContainer::slotItemActivated(const KFileItem &item) job->start(); } -void DolphinViewContainer::slotItemsActivated(const KFileItemList& items) +void DolphinViewContainer::slotItemsActivated(const KFileItemList &items) { Q_ASSERT(items.count() >= 2); @@ -781,7 +737,7 @@ void DolphinViewContainer::slotItemsActivated(const KFileItemList& items) fileItemActions.runPreferredApplications(items); } -void DolphinViewContainer::showItemInfo(const KFileItem& item) +void DolphinViewContainer::showItemInfo(const KFileItem &item) { if (item.isNull()) { m_statusBar->resetToDefaultText(); @@ -802,7 +758,7 @@ void DolphinViewContainer::clearFilterBar() m_filterBar->clearIfUnlocked(); } -void DolphinViewContainer::setNameFilter(const QString& nameFilter) +void DolphinViewContainer::setNameFilter(const QString &nameFilter) { m_view->hideToolTip(ToolTipManager::HideBehavior::Instantly); m_view->setNameFilter(nameFilter); @@ -814,12 +770,12 @@ void DolphinViewContainer::activate() setActive(true); } -void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl&) +void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl &) { saveViewState(); } -void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl& url) +void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl &url) { if (m_urlNavigatorConnected) { m_urlNavigatorConnected->slotReturnPressed(); @@ -842,9 +798,7 @@ void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl& url) "Dolphin does not support web pages, the web browser has been launched"), Information); } else { - showMessage(i18nc("@info:status", - "Protocol not supported by Dolphin, default application has been launched"), - Information); + showMessage(i18nc("@info:status", "Protocol not supported by Dolphin, default application has been launched"), Information); } QDesktopServices::openUrl(url); @@ -855,7 +809,7 @@ void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl& url) } } -void DolphinViewContainer::slotUrlSelectionRequested(const QUrl& url) +void DolphinViewContainer::slotUrlSelectionRequested(const QUrl &url) { m_view->markUrlsAsSelected({url}); m_view->markUrlAsCurrent(url); // makes the item scroll into view @@ -863,17 +817,15 @@ void DolphinViewContainer::slotUrlSelectionRequested(const QUrl& url) void DolphinViewContainer::disableUrlNavigatorSelectionRequests() { - disconnect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, - this, &DolphinViewContainer::slotUrlSelectionRequested); + disconnect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested); } void DolphinViewContainer::enableUrlNavigatorSelectionRequests() { - connect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, - this, &DolphinViewContainer::slotUrlSelectionRequested); + connect(m_urlNavigator.get(), &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested); } -void DolphinViewContainer::redirect(const QUrl& oldUrl, const QUrl& newUrl) +void DolphinViewContainer::redirect(const QUrl &oldUrl, const QUrl &newUrl) { Q_UNUSED(oldUrl) const bool block = m_urlNavigator->signalsBlocked(); @@ -920,7 +872,7 @@ void DolphinViewContainer::slotStatusBarZoomLevelChanged(int zoomLevel) m_view->setZoomLevel(zoomLevel); } -void DolphinViewContainer::showErrorMessage(const QString& msg) +void DolphinViewContainer::showErrorMessage(const QString &msg) { showMessage(msg, Error); } @@ -966,7 +918,7 @@ void DolphinViewContainer::slotOpenUrlFinished(KJob *job) } } -bool DolphinViewContainer::isSearchUrl(const QUrl& url) const +bool DolphinViewContainer::isSearchUrl(const QUrl &url) const { return url.scheme().contains(QLatin1String("search")); } @@ -988,13 +940,12 @@ void DolphinViewContainer::tryRestoreViewState() } } -QString DolphinViewContainer::getNearestExistingAncestorOfPath(const QString& path) const +QString DolphinViewContainer::getNearestExistingAncestorOfPath(const QString &path) const { QDir dir(path); do { dir.setPath(QDir::cleanPath(dir.filePath(QStringLiteral("..")))); - } - while (!dir.exists() && !dir.isRoot()); + } while (!dir.exists() && !dir.isRoot()); return dir.exists() ? dir.path() : QString{}; } diff --git a/src/dolphinviewcontainer.h b/src/dolphinviewcontainer.h index dbaf18261a..7d5e87c327 100644 --- a/src/dolphinviewcontainer.h +++ b/src/dolphinviewcontainer.h @@ -21,8 +21,9 @@ #include #if HAVE_KACTIVITIES -namespace KActivities { - class ResourceInstance; +namespace KActivities +{ +class ResourceInstance; } #endif @@ -33,8 +34,9 @@ class QGridLayout; class QUrl; class DolphinSearchBox; class DolphinStatusBar; -namespace SelectionMode { - class TopBar; +namespace SelectionMode +{ +class TopBar; } /** @@ -54,14 +56,9 @@ class DolphinViewContainer : public QWidget Q_OBJECT public: - enum MessageType - { - Information, - Warning, - Error - }; + enum MessageType { Information, Warning, Error }; - DolphinViewContainer(const QUrl& url, QWidget* parent); + DolphinViewContainer(const QUrl &url, QWidget *parent); ~DolphinViewContainer() override; /** @@ -87,8 +84,8 @@ public: QString currentSearchText() const; - const DolphinStatusBar* statusBar() const; - DolphinStatusBar* statusBar(); + const DolphinStatusBar *statusBar() const; + DolphinStatusBar *statusBar(); /** * @return An UrlNavigator that is controlling this view @@ -122,8 +119,8 @@ public: */ DolphinUrlNavigator *urlNavigatorInternalWithHistory(); - const DolphinView* view() const; - DolphinView* view(); + const DolphinView *view() const; + DolphinView *view(); /** * @param urlNavigator The UrlNavigator that is supposed to control @@ -149,7 +146,9 @@ public: * @param actionCollection The collection of actions from which the actions on the bottom bar are retrieved. * @param bottomBarContents The contents the bar is supposed to show after this call. */ - void setSelectionModeEnabled(bool enabled, KActionCollection *actionCollection = nullptr, SelectionMode::BottomBar::Contents bottomBarContents = SelectionMode::BottomBar::Contents::GeneralContents); + void setSelectionModeEnabled(bool enabled, + KActionCollection *actionCollection = nullptr, + SelectionMode::BottomBar::Contents bottomBarContents = SelectionMode::BottomBar::Contents::GeneralContents); /** @see setSelectionModeEnabled() */ bool isSelectionModeEnabled() const; @@ -157,7 +156,7 @@ public: * Shows the message \msg with the given type non-modal above * the view-content. */ - void showMessage(const QString& msg, MessageType type); + void showMessage(const QString &msg, MessageType type); /** * Refreshes the view container to get synchronized with the (updated) Dolphin settings. @@ -167,7 +166,6 @@ public: /** Returns true, if the filter bar is visible. */ bool isFilterBarVisible() const; - /** Returns true if the search mode is enabled. */ bool isSearchModeEnabled() const; @@ -214,7 +212,7 @@ public Q_SLOTS: * are emitted. * @see DolphinViewContainer::urlNavigator() */ - void setUrl(const QUrl& url); + void setUrl(const QUrl &url); /** * Popups the filter bar above the status bar if \a visible is true. @@ -312,7 +310,7 @@ private Q_SLOTS: * Is called if the URL set by DolphinView::setUrl() represents * a file and not a directory. Takes care to activate the file. */ - void slotUrlIsFileError(const QUrl& url); + void slotUrlIsFileError(const QUrl &url); /** * Handles clicking on an item. If the item is a directory, the @@ -325,13 +323,13 @@ private Q_SLOTS: * Handles activation of multiple files. The files get started by * the corresponding applications. */ - void slotItemsActivated(const KFileItemList& items); + void slotItemsActivated(const KFileItemList &items); /** * Shows the information for the item \a item inside the statusbar. If the * item is null, the default statusbar information is shown. */ - void showItemInfo(const KFileItem& item); + void showItemInfo(const KFileItem &item); void closeFilterBar(); @@ -339,7 +337,7 @@ private Q_SLOTS: * Filters the currently shown items by \a nameFilter. All items * which contain the given filter string will be shown. */ - void setNameFilter(const QString& nameFilter); + void setNameFilter(const QString &nameFilter); /** * Marks the view container as active @@ -351,25 +349,25 @@ private Q_SLOTS: * Is invoked if the signal urlAboutToBeChanged() from the URL navigator * is emitted. Tries to save the view-state. */ - void slotUrlNavigatorLocationAboutToBeChanged(const QUrl& url); + void slotUrlNavigatorLocationAboutToBeChanged(const QUrl &url); /** * Restores the current view to show \a url and assures * that the root URL of the view is respected. */ - void slotUrlNavigatorLocationChanged(const QUrl& url); + void slotUrlNavigatorLocationChanged(const QUrl &url); /** * @see KUrlNavigator::urlSelectionRequested */ - void slotUrlSelectionRequested(const QUrl& url); + void slotUrlSelectionRequested(const QUrl &url); /** * Is invoked when a redirection is done and changes the * URL of the URL navigator to \a newUrl without triggering * a reloading of the directory. */ - void redirect(const QUrl& oldUrl, const QUrl& newUrl); + void redirect(const QUrl &oldUrl, const QUrl &newUrl); /** Requests the focus for the view \a m_view. */ void requestFocus(); @@ -391,7 +389,7 @@ private Q_SLOTS: /** * Slot that calls showMessage(msg, Error). */ - void showErrorMessage(const QString& msg); + void showErrorMessage(const QString &msg); /** * Is invoked when a KFilePlacesModel has been changed @@ -403,13 +401,13 @@ private Q_SLOTS: void slotSortHiddenLastChanged(bool hiddenLast); void slotCurrentDirectoryRemoved(); - void slotOpenUrlFinished(KJob* job); + void slotOpenUrlFinished(KJob *job); private: /** * @return True if the URL protocol is a search URL (e. g. baloosearch:// or filenamesearch://). */ - bool isSearchUrl(const QUrl& url) const; + bool isSearchUrl(const QUrl &url) const; /** * Saves the state of the current view: contents position, @@ -426,7 +424,7 @@ private: /** * @return Path of nearest existing ancestor directory. */ - QString getNearestExistingAncestorOfPath(const QString& path) const; + QString getNearestExistingAncestorOfPath(const QString &path) const; private: QGridLayout *m_topLayout; @@ -445,24 +443,24 @@ private: */ QPointer m_urlNavigatorConnected; - DolphinSearchBox* m_searchBox; + DolphinSearchBox *m_searchBox; bool m_searchModeEnabled; - KMessageWidget* m_messageWidget; + KMessageWidget *m_messageWidget; /// A bar shown at the top of the view to signify that selection mode is currently active. SelectionMode::TopBar *m_selectionModeTopBar; - DolphinView* m_view; + DolphinView *m_view; - FilterBar* m_filterBar; + FilterBar *m_filterBar; /// A bar shown at the bottom of the view whose contents depend on what the user is currently doing. SelectionMode::BottomBar *m_selectionModeBottomBar; - DolphinStatusBar* m_statusBar; - QTimer* m_statusBarTimer; // Triggers a delayed update - QElapsedTimer m_statusBarTimestamp; // Time in ms since last update + DolphinStatusBar *m_statusBar; + QTimer *m_statusBarTimer; // Triggers a delayed update + QElapsedTimer m_statusBarTimestamp; // Time in ms since last update bool m_autoGrabFocus; /** * The visual state to be applied to the next UrlNavigator that gets @@ -472,7 +470,7 @@ private: #if HAVE_KACTIVITIES private: - KActivities::ResourceInstance * m_activityResourceInstance; + KActivities::ResourceInstance *m_activityResourceInstance; #endif }; diff --git a/src/filterbar/filterbar.cpp b/src/filterbar/filterbar.cpp index c1fb344b1e..76e23d4202 100644 --- a/src/filterbar/filterbar.cpp +++ b/src/filterbar/filterbar.cpp @@ -15,8 +15,8 @@ #include #include -FilterBar::FilterBar(QWidget* parent) : - QWidget(parent) +FilterBar::FilterBar(QWidget *parent) + : QWidget(parent) { // Create button to lock text when changing folders m_lockButton = new QToolButton(this); @@ -26,14 +26,12 @@ FilterBar::FilterBar(QWidget* parent) : m_lockButton->setToolTip(i18nc("@info:tooltip", "Keep Filter When Changing Folders")); connect(m_lockButton, &QToolButton::toggled, this, &FilterBar::slotToggleLockButton); - // Create filter editor m_filterInput = new QLineEdit(this); m_filterInput->setLayoutDirection(Qt::LeftToRight); m_filterInput->setClearButtonEnabled(true); m_filterInput->setPlaceholderText(i18n("Filter...")); - connect(m_filterInput, &QLineEdit::textChanged, - this, &FilterBar::filterChanged); + connect(m_filterInput, &QLineEdit::textChanged, this, &FilterBar::filterChanged); setFocusProxy(m_filterInput); // Create close button @@ -44,7 +42,7 @@ FilterBar::FilterBar(QWidget* parent) : connect(closeButton, &QToolButton::clicked, this, &FilterBar::closeRequest); // Apply layout - QHBoxLayout* hLayout = new QHBoxLayout(this); + QHBoxLayout *hLayout = new QHBoxLayout(this); hLayout->setContentsMargins(0, 0, 0, 0); hLayout->addWidget(m_lockButton); hLayout->addWidget(m_filterInput); @@ -91,14 +89,14 @@ void FilterBar::slotToggleLockButton(bool checked) } } -void FilterBar::showEvent(QShowEvent* event) +void FilterBar::showEvent(QShowEvent *event) { if (!event->spontaneous()) { m_filterInput->setFocus(); } } -void FilterBar::keyReleaseEvent(QKeyEvent* event) +void FilterBar::keyReleaseEvent(QKeyEvent *event) { QWidget::keyReleaseEvent(event); @@ -120,4 +118,3 @@ void FilterBar::keyReleaseEvent(QKeyEvent* event) break; } } - diff --git a/src/filterbar/filterbar.h b/src/filterbar/filterbar.h index 73b1c566ec..8a0b814311 100644 --- a/src/filterbar/filterbar.h +++ b/src/filterbar/filterbar.h @@ -24,7 +24,7 @@ class FilterBar : public QWidget Q_OBJECT public: - explicit FilterBar(QWidget* parent = nullptr); + explicit FilterBar(QWidget *parent = nullptr); ~FilterBar() override; /** Called by view container to hide this **/ @@ -48,7 +48,7 @@ Q_SIGNALS: * Signal that reports the name filter has been * changed to \a nameFilter. */ - void filterChanged(const QString& nameFilter); + void filterChanged(const QString &nameFilter); /** * Emitted as soon as the filterbar should get closed. @@ -61,12 +61,12 @@ Q_SIGNALS: void focusViewRequest(); protected: - void showEvent(QShowEvent* event) override; - void keyReleaseEvent(QKeyEvent* event) override; + void showEvent(QShowEvent *event) override; + void keyReleaseEvent(QKeyEvent *event) override; private: - QLineEdit* m_filterInput; - QToolButton* m_lockButton; + QLineEdit *m_filterInput; + QToolButton *m_lockButton; }; #endif diff --git a/src/global.cpp b/src/global.cpp index d5fbec6bc4..554eb41fad 100644 --- a/src/global.cpp +++ b/src/global.cpp @@ -19,11 +19,11 @@ #include -QList Dolphin::validateUris(const QStringList& uriList) +QList Dolphin::validateUris(const QStringList &uriList) { const QString currentDir = QDir::currentPath(); QList urls; - for (const QString& str : uriList) { + for (const QString &str : uriList) { const QUrl url = QUrl::fromUserInput(str, currentDir, QUrl::AssumeLocalFile); if (url.isValid()) { urls.append(url); @@ -57,7 +57,11 @@ void Dolphin::openNewWindow(const QList &urls, QWidget *window, const Open job->start(); } -bool Dolphin::attachToExistingInstance(const QList& inputUrls, bool openFiles, bool splitView, const QString& preferredService, const QString &activationToken) +bool Dolphin::attachToExistingInstance(const QList &inputUrls, + bool openFiles, + bool splitView, + const QString &preferredService, + const QString &activationToken) { bool attached = false; @@ -71,7 +75,7 @@ bool Dolphin::attachToExistingInstance(const QList& inputUrls, bool openFi } int activeWindowIndex = -1; - for (const auto& interface: qAsConst(dolphinInterfaces)) { + for (const auto &interface : qAsConst(dolphinInterfaces)) { ++activeWindowIndex; auto isActiveWindowReply = interface.first->isActiveWindow(); @@ -83,7 +87,7 @@ bool Dolphin::attachToExistingInstance(const QList& inputUrls, bool openFi // check to see if any instances already have any of the given URLs or their parents open QList newWindowURLs; - for (const QUrl& url : inputUrls) { + for (const QUrl &url : inputUrls) { bool urlFound = false; const QString urlString = url.toString(); @@ -101,8 +105,7 @@ bool Dolphin::attachToExistingInstance(const QList& inputUrls, bool openFi } i = (i + 1) % dolphinInterfaces.size(); - } - while (i != activeWindowIndex); + } while (i != activeWindowIndex); if (!urlFound) { if (GeneralSettings::openExternallyCalledFolderInNewTab()) { @@ -113,13 +116,11 @@ bool Dolphin::attachToExistingInstance(const QList& inputUrls, bool openFi } } - for (const auto& interface: qAsConst(dolphinInterfaces)) { + for (const auto &interface : qAsConst(dolphinInterfaces)) { if (interface.second.isEmpty()) { continue; } - auto reply = openFiles ? - interface.first->openFiles(interface.second, splitView) : - interface.first->openDirectories(interface.second, splitView); + auto reply = openFiles ? interface.first->openFiles(interface.second, splitView) : interface.first->openDirectories(interface.second, splitView); reply.waitForFinished(); if (!reply.isError()) { interface.first->activateWindow(activationToken); @@ -137,14 +138,12 @@ bool Dolphin::attachToExistingInstance(const QList& inputUrls, bool openFi return attached; } -QVector, QStringList>> Dolphin::dolphinGuiInstances(const QString& preferredService) +QVector, QStringList>> Dolphin::dolphinGuiInstances(const QString &preferredService) { QVector, QStringList>> dolphinInterfaces; if (!preferredService.isEmpty()) { QSharedPointer preferredInterface( - new OrgKdeDolphinMainWindowInterface(preferredService, - QStringLiteral("/dolphin/Dolphin_1"), - QDBusConnection::sessionBus())); + new OrgKdeDolphinMainWindowInterface(preferredService, QStringLiteral("/dolphin/Dolphin_1"), QDBusConnection::sessionBus())); if (preferredInterface->isValid() && !preferredInterface->lastError().isValid()) { dolphinInterfaces.append(qMakePair(preferredInterface, QStringList())); } @@ -157,13 +156,11 @@ QVector, QStringList>> Do const QString pattern = QStringLiteral("org.kde.dolphin-"); // Don't match the pid without leading "-" const QString myPid = QLatin1Char('-') + QString::number(QCoreApplication::applicationPid()); - for (const QString& service : dbusServices) { + for (const QString &service : dbusServices) { if (service.startsWith(pattern) && !service.endsWith(myPid)) { // Check if instance can handle our URLs QSharedPointer interface( - new OrgKdeDolphinMainWindowInterface(service, - QStringLiteral("/dolphin/Dolphin_1"), - QDBusConnection::sessionBus())); + new OrgKdeDolphinMainWindowInterface(service, QStringLiteral("/dolphin/Dolphin_1"), QDBusConnection::sessionBus())); if (interface->isValid() && !interface->lastError().isValid()) { dolphinInterfaces.append(qMakePair(interface, QStringList())); } @@ -189,17 +186,14 @@ double GlobalConfig::animationDurationFactor() updateAnimationDurationFactor(kdeGlobalsConfig, {"AnimationDurationFactor"}); KConfigWatcher::Ptr configWatcher = KConfigWatcher::create(KSharedConfig::openConfig()); - connect(configWatcher.data(), &KConfigWatcher::configChanged, - &GlobalConfig::updateAnimationDurationFactor); + connect(configWatcher.data(), &KConfigWatcher::configChanged, &GlobalConfig::updateAnimationDurationFactor); return s_animationDurationFactor; } void GlobalConfig::updateAnimationDurationFactor(const KConfigGroup &group, const QByteArrayList &names) { - if (group.name() == QLatin1String("KDE") && - names.contains(QByteArrayLiteral("AnimationDurationFactor"))) { - s_animationDurationFactor = std::max(0.0, - group.readEntry("AnimationDurationFactor", 1.0)); + if (group.name() == QLatin1String("KDE") && names.contains(QByteArrayLiteral("AnimationDurationFactor"))) { + s_animationDurationFactor = std::max(0.0, group.readEntry("AnimationDurationFactor", 1.0)); } } diff --git a/src/global.h b/src/global.h index 80ec03fd02..dd07f9170f 100644 --- a/src/global.h +++ b/src/global.h @@ -14,51 +14,46 @@ class KConfigGroup; class OrgKdeDolphinMainWindowInterface; -namespace Dolphin { - QList validateUris(const QStringList& uriList); +namespace Dolphin +{ +QList validateUris(const QStringList &uriList); - /** - * Returns the home url which is defined in General Settings - */ - QUrl homeUrl(); +/** + * Returns the home url which is defined in General Settings + */ +QUrl homeUrl(); - enum class OpenNewWindowFlag { - None = 0, - Select = 1<<1 - }; - Q_DECLARE_FLAGS(OpenNewWindowFlags, OpenNewWindowFlag) +enum class OpenNewWindowFlag { None = 0, Select = 1 << 1 }; +Q_DECLARE_FLAGS(OpenNewWindowFlags, OpenNewWindowFlag) - /** - * Opens a new Dolphin window - */ - void openNewWindow(const QList &urls = {}, QWidget *window = nullptr, const OpenNewWindowFlags &flags = OpenNewWindowFlag::None); +/** + * Opens a new Dolphin window + */ +void openNewWindow(const QList &urls = {}, QWidget *window = nullptr, const OpenNewWindowFlags &flags = OpenNewWindowFlag::None); - /** - * Attaches URLs to an existing Dolphin instance if possible. - * If @p preferredService is a valid dbus service, it will be tried first. - * @p preferredService needs to support the org.kde.dolphin.MainWindow dbus interface with the /dolphin/Dolphin_1 path. - * Returns true if the URLs were successfully attached. - */ - bool attachToExistingInstance(const QList& inputUrls, bool openFiles, bool splitView, const QString& preferredService, const QString &activationToken); +/** + * Attaches URLs to an existing Dolphin instance if possible. + * If @p preferredService is a valid dbus service, it will be tried first. + * @p preferredService needs to support the org.kde.dolphin.MainWindow dbus interface with the /dolphin/Dolphin_1 path. + * Returns true if the URLs were successfully attached. + */ +bool attachToExistingInstance(const QList &inputUrls, bool openFiles, bool splitView, const QString &preferredService, const QString &activationToken); - /** - * Returns a QVector with all GUI-capable Dolphin instances - */ - QVector, QStringList>> dolphinGuiInstances(const QString& preferredService); +/** + * Returns a QVector with all GUI-capable Dolphin instances + */ +QVector, QStringList>> dolphinGuiInstances(const QString &preferredService); - QPair sortOrderForUrl(QUrl &url); +QPair sortOrderForUrl(QUrl &url); - /** - * TODO: Move this somewhere global to all KDE apps, not just Dolphin - */ - const int VERTICAL_SPACER_HEIGHT = 12; - const int LAYOUT_SPACING_SMALL = 2; +/** + * TODO: Move this somewhere global to all KDE apps, not just Dolphin + */ +const int VERTICAL_SPACER_HEIGHT = 12; +const int LAYOUT_SPACING_SMALL = 2; } -enum Animated { - WithAnimation, - WithoutAnimation -}; +enum Animated { WithAnimation, WithoutAnimation }; class GlobalConfig : public QObject { diff --git a/src/kitemviews/kfileitemlisttostring.cpp b/src/kitemviews/kfileitemlisttostring.cpp index 0004c7e7f1..d10680adca 100644 --- a/src/kitemviews/kfileitemlisttostring.cpp +++ b/src/kitemviews/kfileitemlisttostring.cpp @@ -19,27 +19,35 @@ QString fileItemListToString(KFileItemList items, int maximumTextWidth, const QF QString text; switch (items.count()) { case 1: - text = i18nc("Textual representation of a file. %1 is the name of the file/folder.", - "\"%1\"", items.first().name()); + text = i18nc("Textual representation of a file. %1 is the name of the file/folder.", "\"%1\"", items.first().name()); break; case 2: - text = i18nc("Textual representation of two files. %1 and %2 are names of files/folders.", - "\"%1\" and \"%2\"", items.first().name(), items.last().name()); + text = + i18nc("Textual representation of two files. %1 and %2 are names of files/folders.", "\"%1\" and \"%2\"", items.first().name(), items.last().name()); break; case 3: text = i18nc("Textual representation of three files. %1, %2 and %3 are names of files/folders.", - "\"%1\", \"%2\" and \"%3\"", - items.first().name(), items.at(1).name(), items.last().name()); + "\"%1\", \"%2\" and \"%3\"", + items.first().name(), + items.at(1).name(), + items.last().name()); break; case 4: text = i18nc("Textual representation of four files. %1, %2, %3 and %4 are names of files/folders.", - "\"%1\", \"%2\", \"%3\" and \"%4\"", - items.first().name(), items.at(1).name(), items.at(2).name(), items.last().name()); + "\"%1\", \"%2\", \"%3\" and \"%4\"", + items.first().name(), + items.at(1).name(), + items.at(2).name(), + items.last().name()); break; case 5: text = i18nc("Textual representation of five files. %1, %2, %3, %4 and %5 are names of files/folders.", - "\"%1\", \"%2\", \"%3\", \"%4\" and \"%5\"", - items.first().name(), items.at(1).name(), items.at(2).name(), items.at(3).name(), items.last().name()); + "\"%1\", \"%2\", \"%3\", \"%4\" and \"%5\"", + items.first().name(), + items.at(1).name(), + items.at(2).name(), + items.at(3).name(), + items.last().name()); break; default: text = QString(); @@ -54,14 +62,15 @@ QString fileItemListToString(KFileItemList items, int maximumTextWidth, const QF const KFileItemListProperties properties(items); if (itemsState == Selected) { if (properties.isFile()) { - text = i18ncp("Textual representation of selected files. %1 is the number of files.", - "One Selected File", "%1 Selected Files", items.count()); + text = i18ncp("Textual representation of selected files. %1 is the number of files.", "One Selected File", "%1 Selected Files", items.count()); } else if (properties.isDirectory()) { - text = i18ncp("Textual representation of selected folders. %1 is the number of folders.", - "One Selected Folder", "%1 Selected Folders", items.count()); + text = + i18ncp("Textual representation of selected folders. %1 is the number of folders.", "One Selected Folder", "%1 Selected Folders", items.count()); } else { text = i18ncp("Textual representation of selected fileitems. %1 is the number of files/folders.", - "One Selected Item", "%1 Selected Items", items.count()); + "One Selected Item", + "%1 Selected Items", + items.count()); } if (fontMetrics.horizontalAdvance(text) <= maximumTextWidth) { @@ -70,13 +79,10 @@ QString fileItemListToString(KFileItemList items, int maximumTextWidth, const QF } if (properties.isFile()) { - return i18ncp("Textual representation of files. %1 is the number of files.", - "One File", "%1 Files", items.count()); + return i18ncp("Textual representation of files. %1 is the number of files.", "One File", "%1 Files", items.count()); } else if (properties.isDirectory()) { - return i18ncp("Textual representation of folders. %1 is the number of folders.", - "One Folder", "%1 Folders", items.count()); + return i18ncp("Textual representation of folders. %1 is the number of folders.", "One Folder", "%1 Folders", items.count()); } else { - return i18ncp("Textual representation of fileitems. %1 is the number of files/folders.", - "One Item", "%1 Items", items.count()); + return i18ncp("Textual representation of fileitems. %1 is the number of files/folders.", "One Item", "%1 Items", items.count()); } } diff --git a/src/kitemviews/kfileitemlisttostring.h b/src/kitemviews/kfileitemlisttostring.h index ad8c82b218..f1c2902b8a 100644 --- a/src/kitemviews/kfileitemlisttostring.h +++ b/src/kitemviews/kfileitemlisttostring.h @@ -12,10 +12,7 @@ class KFileItemList; class QFontMetrics; class QString; -enum ItemsState { - None, - Selected -}; +enum ItemsState { None, Selected }; /** * @brief Generates a textual representation of the given list of KFileItems. diff --git a/src/kitemviews/kfileitemlistview.cpp b/src/kitemviews/kfileitemlistview.cpp index 26bc014653..e2a27a5ea0 100644 --- a/src/kitemviews/kfileitemlistview.cpp +++ b/src/kitemviews/kfileitemlistview.cpp @@ -15,32 +15,33 @@ #include #include -#include -#include #include #include +#include +#include // #define KFILEITEMLISTVIEW_DEBUG -namespace { - // If the visible index range changes, KFileItemModelRolesUpdater is not - // informed immediately, but with a short delay. This ensures that scrolling - // always feels smooth and is not interrupted by icon loading (which can be - // quite expensive if a disk access is required to determine the final icon). - const int ShortInterval = 50; +namespace +{ +// If the visible index range changes, KFileItemModelRolesUpdater is not +// informed immediately, but with a short delay. This ensures that scrolling +// always feels smooth and is not interrupted by icon loading (which can be +// quite expensive if a disk access is required to determine the final icon). +const int ShortInterval = 50; - // If the icon size changes, a longer delay is used. This prevents that - // the expensive re-generation of all previews is triggered repeatedly when - // changing the zoom level. - const int LongInterval = 300; +// If the icon size changes, a longer delay is used. This prevents that +// the expensive re-generation of all previews is triggered repeatedly when +// changing the zoom level. +const int LongInterval = 300; } -KFileItemListView::KFileItemListView(QGraphicsWidget* parent) : - KStandardItemListView(parent), - m_modelRolesUpdater(nullptr), - m_updateVisibleIndexRangeTimer(nullptr), - m_updateIconSizeTimer(nullptr), - m_scanDirectories(true) +KFileItemListView::KFileItemListView(QGraphicsWidget *parent) + : KStandardItemListView(parent) + , m_modelRolesUpdater(nullptr) + , m_updateVisibleIndexRangeTimer(nullptr) + , m_updateIconSizeTimer(nullptr) + , m_scanDirectories(true) { setAcceptDrops(true); @@ -94,7 +95,7 @@ bool KFileItemListView::enlargeSmallPreviews() const return m_modelRolesUpdater ? m_modelRolesUpdater->enlargeSmallPreviews() : false; } -void KFileItemListView::setEnabledPlugins(const QStringList& list) +void KFileItemListView::setEnabledPlugins(const QStringList &list) { if (m_modelRolesUpdater) { m_modelRolesUpdater->setEnabledPlugins(list); @@ -131,7 +132,7 @@ bool KFileItemListView::scanDirectories() return m_scanDirectories; } -QPixmap KFileItemListView::createDragPixmap(const KItemSet& indexes) const +QPixmap KFileItemListView::createDragPixmap(const KItemSet &indexes) const { if (!model()) { return QPixmap(); @@ -213,27 +214,27 @@ QPixmap KFileItemListView::createDragPixmap(const KItemSet& indexes) const return dragPixmap; } -void KFileItemListView::setHoverSequenceState(const QUrl& itemUrl, int seqIdx) +void KFileItemListView::setHoverSequenceState(const QUrl &itemUrl, int seqIdx) { if (m_modelRolesUpdater) { m_modelRolesUpdater->setHoverSequenceState(itemUrl, seqIdx); } } -KItemListWidgetCreatorBase* KFileItemListView::defaultWidgetCreator() const +KItemListWidgetCreatorBase *KFileItemListView::defaultWidgetCreator() const { return new KItemListWidgetCreator(); } -void KFileItemListView::initializeItemListWidget(KItemListWidget* item) +void KFileItemListView::initializeItemListWidget(KItemListWidget *item) { KStandardItemListView::initializeItemListWidget(item); // Make sure that the item has an icon. QHash data = item->data(); if (!data.contains("iconName") && data["iconPixmap"].value().isNull()) { - Q_ASSERT(qobject_cast(model())); - KFileItemModel* fileItemModel = static_cast(model()); + Q_ASSERT(qobject_cast(model())); + KFileItemModel *fileItemModel = static_cast(model()); const KFileItem fileItem = fileItemModel->fileItem(item->index()); QString iconName = fileItem.iconName(); @@ -257,16 +258,16 @@ void KFileItemListView::onItemLayoutChanged(ItemLayout current, ItemLayout previ triggerVisibleIndexRangeUpdate(); } -void KFileItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous) +void KFileItemListView::onModelChanged(KItemModelBase *current, KItemModelBase *previous) { - Q_ASSERT(qobject_cast(current)); + Q_ASSERT(qobject_cast(current)); KStandardItemListView::onModelChanged(current, previous); delete m_modelRolesUpdater; m_modelRolesUpdater = nullptr; if (current) { - m_modelRolesUpdater = new KFileItemModelRolesUpdater(static_cast(current), this); + m_modelRolesUpdater = new KFileItemModelRolesUpdater(static_cast(current), this); m_modelRolesUpdater->setIconSize(availableIconSize()); m_modelRolesUpdater->setScanDirectories(scanDirectories()); @@ -280,7 +281,7 @@ void KFileItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt:: triggerVisibleIndexRangeUpdate(); } -void KFileItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous) +void KFileItemListView::onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -293,13 +294,13 @@ void KFileItemListView::onScrollOffsetChanged(qreal current, qreal previous) triggerVisibleIndexRangeUpdate(); } -void KFileItemListView::onVisibleRolesChanged(const QList& current, const QList& previous) +void KFileItemListView::onVisibleRolesChanged(const QList ¤t, const QList &previous) { KStandardItemListView::onVisibleRolesChanged(current, previous); applyRolesToModel(); } -void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) +void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) { KStandardItemListView::onStyleOptionChanged(current, previous); triggerIconSizeUpdate(); @@ -328,25 +329,24 @@ void KFileItemListView::onTransactionEnd() // Only unpause the model-roles-updater if no timer is active. If one // timer is still active the model-roles-updater will be unpaused later as // soon as the timer has been exceeded. - const bool timerActive = m_updateVisibleIndexRangeTimer->isActive() || - m_updateIconSizeTimer->isActive(); + const bool timerActive = m_updateVisibleIndexRangeTimer->isActive() || m_updateIconSizeTimer->isActive(); if (!timerActive) { m_modelRolesUpdater->setPaused(false); } } -void KFileItemListView::resizeEvent(QGraphicsSceneResizeEvent* event) +void KFileItemListView::resizeEvent(QGraphicsSceneResizeEvent *event) { KStandardItemListView::resizeEvent(event); triggerVisibleIndexRangeUpdate(); } -void KFileItemListView::slotItemsRemoved(const KItemRangeList& itemRanges) +void KFileItemListView::slotItemsRemoved(const KItemRangeList &itemRanges) { KStandardItemListView::slotItemsRemoved(itemRanges); } -void KFileItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous) +void KFileItemListView::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous) { const QByteArray sortRole = model()->sortRole(); if (!visibleRoles().contains(sortRole)) { @@ -420,8 +420,8 @@ void KFileItemListView::applyRolesToModel() return; } - Q_ASSERT(qobject_cast(model())); - KFileItemModel* fileItemModel = static_cast(model()); + Q_ASSERT(qobject_cast(model())); + KFileItemModel *fileItemModel = static_cast(model()); // KFileItemModel does not distinct between "visible" and "invisible" roles. // Add all roles that are mandatory for having a working KFileItemListView: @@ -448,7 +448,7 @@ void KFileItemListView::applyRolesToModel() QSize KFileItemListView::availableIconSize() const { - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); const int iconSize = option.iconSize; if (itemLayout() == IconsLayout) { const int maxIconWidth = itemSize().width() - 2 * option.padding; @@ -457,4 +457,3 @@ QSize KFileItemListView::availableIconSize() const return QSize(iconSize, iconSize); } - diff --git a/src/kitemviews/kfileitemlistview.h b/src/kitemviews/kfileitemlistview.h index 9c7b4fc6f5..63bcf9e753 100644 --- a/src/kitemviews/kfileitemlistview.h +++ b/src/kitemviews/kfileitemlistview.h @@ -29,7 +29,7 @@ class DOLPHIN_EXPORT KFileItemListView : public KStandardItemListView Q_OBJECT public: - explicit KFileItemListView(QGraphicsWidget* parent = nullptr); + explicit KFileItemListView(QGraphicsWidget *parent = nullptr); ~KFileItemListView() override; void setPreviewsShown(bool show); @@ -52,7 +52,7 @@ public: * * @see enabledPlugins */ - void setEnabledPlugins(const QStringList& list); + void setEnabledPlugins(const QStringList &list); /** * Returns the list of enabled thumbnail plugins. @@ -78,7 +78,7 @@ public: void setScanDirectories(bool enabled); bool scanDirectories(); - QPixmap createDragPixmap(const KItemSet& indexes) const override; + QPixmap createDragPixmap(const KItemSet &indexes) const override; /** * Notifies the view of a change in the hover state on an item. @@ -88,27 +88,27 @@ public: * this method will be called repeatedly with increasing values * for this parameter. */ - void setHoverSequenceState(const QUrl& itemUrl, int seqIdx); + void setHoverSequenceState(const QUrl &itemUrl, int seqIdx); protected: - KItemListWidgetCreatorBase* defaultWidgetCreator() const override; - void initializeItemListWidget(KItemListWidget* item) override; + KItemListWidgetCreatorBase *defaultWidgetCreator() const override; + void initializeItemListWidget(KItemListWidget *item) override; virtual void onPreviewsShownChanged(bool shown); void onItemLayoutChanged(ItemLayout current, ItemLayout previous) override; - void onModelChanged(KItemModelBase* current, KItemModelBase* previous) override; + void onModelChanged(KItemModelBase *current, KItemModelBase *previous) override; void onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous) override; - void onItemSizeChanged(const QSizeF& current, const QSizeF& previous) override; + void onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous) override; void onScrollOffsetChanged(qreal current, qreal previous) override; - void onVisibleRolesChanged(const QList& current, const QList& previous) override; - void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) override; + void onVisibleRolesChanged(const QList ¤t, const QList &previous) override; + void onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) override; void onSupportsItemExpandingChanged(bool supportsExpanding) override; void onTransactionBegin() override; void onTransactionEnd() override; - void resizeEvent(QGraphicsSceneResizeEvent* event) override; + void resizeEvent(QGraphicsSceneResizeEvent *event) override; protected Q_SLOTS: - void slotItemsRemoved(const KItemRangeList& itemRanges) override; - void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous) override; + void slotItemsRemoved(const KItemRangeList &itemRanges) override; + void slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous) override; private Q_SLOTS: void triggerVisibleIndexRangeUpdate(); @@ -134,14 +134,12 @@ private: QSize availableIconSize() const; private: - KFileItemModelRolesUpdater* m_modelRolesUpdater; - QTimer* m_updateVisibleIndexRangeTimer; - QTimer* m_updateIconSizeTimer; + KFileItemModelRolesUpdater *m_modelRolesUpdater; + QTimer *m_updateVisibleIndexRangeTimer; + QTimer *m_updateIconSizeTimer; bool m_scanDirectories; friend class KFileItemListViewTest; // For unit testing }; #endif - - diff --git a/src/kitemviews/kfileitemlistwidget.cpp b/src/kitemviews/kfileitemlistwidget.cpp index a62b75824c..8002af5972 100644 --- a/src/kitemviews/kfileitemlistwidget.cpp +++ b/src/kitemviews/kfileitemlistwidget.cpp @@ -18,8 +18,8 @@ #include #include -KFileItemListWidgetInformant::KFileItemListWidgetInformant() : - KStandardItemListWidgetInformant() +KFileItemListWidgetInformant::KFileItemListWidgetInformant() + : KStandardItemListWidgetInformant() { } @@ -27,26 +27,25 @@ KFileItemListWidgetInformant::~KFileItemListWidgetInformant() { } -QString KFileItemListWidgetInformant::itemText(int index, const KItemListView* view) const +QString KFileItemListWidgetInformant::itemText(int index, const KItemListView *view) const { - Q_ASSERT(qobject_cast(view->model())); - KFileItemModel* fileItemModel = static_cast(view->model()); + Q_ASSERT(qobject_cast(view->model())); + KFileItemModel *fileItemModel = static_cast(view->model()); const KFileItem item = fileItemModel->fileItem(index); return item.text(); } -bool KFileItemListWidgetInformant::itemIsLink(int index, const KItemListView* view) const +bool KFileItemListWidgetInformant::itemIsLink(int index, const KItemListView *view) const { - Q_ASSERT(qobject_cast(view->model())); - KFileItemModel* fileItemModel = static_cast(view->model()); + Q_ASSERT(qobject_cast(view->model())); + KFileItemModel *fileItemModel = static_cast(view->model()); const KFileItem item = fileItemModel->fileItem(index); return item.isLink(); } -QString KFileItemListWidgetInformant::roleText(const QByteArray& role, - const QHash& values) const +QString KFileItemListWidgetInformant::roleText(const QByteArray &role, const QHash &values) const { QString text; const QVariant roleValue = values.value(role); @@ -56,7 +55,7 @@ QString KFileItemListWidgetInformant::roleText(const QByteArray& role, // Implementation note: In case if more roles require a custom handling // use a hash + switch for a linear runtime. - auto formatDate = [formatter, local](const QDateTime& time) { + auto formatDate = [formatter, local](const QDateTime &time) { if (DetailsModeSettings::useShortRelativeDates()) { return formatter.formatRelativeDateTime(time, QLocale::ShortFormat); } else { @@ -83,12 +82,12 @@ QString KFileItemListWidgetInformant::roleText(const QByteArray& role, text = formatter.formatByteSize(size); } } else if (role == "modificationtime" || role == "creationtime" || role == "accesstime") { - bool ok; - const long long time = roleValue.toLongLong(&ok); - if (ok && time != -1) { - const QDateTime dateTime = QDateTime::fromSecsSinceEpoch(time); - text = formatDate(dateTime); - } + bool ok; + const long long time = roleValue.toLongLong(&ok); + if (ok && time != -1) { + const QDateTime dateTime = QDateTime::fromSecsSinceEpoch(time); + text = formatDate(dateTime); + } } else if (role == "deletiontime" || role == "imageDateTime") { const QDateTime dateTime = roleValue.toDateTime(); if (dateTime.isValid()) { @@ -106,7 +105,7 @@ QString KFileItemListWidgetInformant::roleText(const QByteArray& role, return text; } -QFont KFileItemListWidgetInformant::customizedFontForLinks(const QFont& baseFont) const +QFont KFileItemListWidgetInformant::customizedFontForLinks(const QFont &baseFont) const { // The customized font should be italic if the file is a symbolic link. QFont font(baseFont); @@ -114,8 +113,8 @@ QFont KFileItemListWidgetInformant::customizedFontForLinks(const QFont& baseFont return font; } -KFileItemListWidget::KFileItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) : - KStandardItemListWidget(informant, parent) +KFileItemListWidget::KFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent) + : KStandardItemListWidget(informant, parent) { } @@ -123,12 +122,12 @@ KFileItemListWidget::~KFileItemListWidget() { } -KItemListWidgetInformant* KFileItemListWidget::createInformant() +KItemListWidgetInformant *KFileItemListWidget::createInformant() { return new KFileItemListWidgetInformant(); } -bool KFileItemListWidget::isRoleRightAligned(const QByteArray& role) const +bool KFileItemListWidget::isRoleRightAligned(const QByteArray &role) const { return role == "size"; } @@ -138,7 +137,7 @@ bool KFileItemListWidget::isHidden() const return data().value("isHidden").toBool(); } -QFont KFileItemListWidget::customizedFont(const QFont& baseFont) const +QFont KFileItemListWidget::customizedFont(const QFont &baseFont) const { // The customized font should be italic if the file is a symbolic link. QFont font(baseFont); @@ -146,14 +145,14 @@ QFont KFileItemListWidget::customizedFont(const QFont& baseFont) const return font; } -int KFileItemListWidget::selectionLength(const QString& text) const +int KFileItemListWidget::selectionLength(const QString &text) const { // Select the text without MIME-type extension int selectionLength = text.length(); // If item is a directory, use the whole text length for // selection (ignore all points) - if(data().value("isDir").toBool()) { + if (data().value("isDir").toBool()) { return selectionLength; } @@ -179,7 +178,7 @@ int KFileItemListWidget::selectionLength(const QString& text) const void KFileItemListWidget::hoverSequenceStarted() { - KFileItemListView* view = listView(); + KFileItemListView *view = listView(); if (!view) { return; @@ -192,7 +191,7 @@ void KFileItemListWidget::hoverSequenceStarted() void KFileItemListWidget::hoverSequenceIndexChanged(int sequenceIndex) { - KFileItemListView* view = listView(); + KFileItemListView *view = listView(); if (!view) { return; @@ -209,7 +208,7 @@ void KFileItemListWidget::hoverSequenceIndexChanged(int sequenceIndex) void KFileItemListWidget::hoverSequenceEnded() { - KFileItemListView* view = listView(); + KFileItemListView *view = listView(); if (!view) { return; @@ -218,8 +217,7 @@ void KFileItemListWidget::hoverSequenceEnded() view->setHoverSequenceState(QUrl(), 0); } -KFileItemListView* KFileItemListWidget::listView() +KFileItemListView *KFileItemListWidget::listView() { - return dynamic_cast(parentItem()); + return dynamic_cast(parentItem()); } - diff --git a/src/kitemviews/kfileitemlistwidget.h b/src/kitemviews/kfileitemlistwidget.h index 094f6105f9..27fcf7f29d 100644 --- a/src/kitemviews/kfileitemlistwidget.h +++ b/src/kitemviews/kfileitemlistwidget.h @@ -12,7 +12,6 @@ class KFileItemListView; - class DOLPHIN_EXPORT KFileItemListWidgetInformant : public KStandardItemListWidgetInformant { public: @@ -20,10 +19,10 @@ public: ~KFileItemListWidgetInformant() override; protected: - QString itemText(int index, const KItemListView* view) const override; - bool itemIsLink(int index, const KItemListView* view) const override; - QString roleText(const QByteArray& role, const QHash& values) const override; - QFont customizedFontForLinks(const QFont& baseFont) const override; + QString itemText(int index, const KItemListView *view) const override; + bool itemIsLink(int index, const KItemListView *view) const override; + QString roleText(const QByteArray &role, const QHash &values) const override; + QFont customizedFontForLinks(const QFont &baseFont) const override; }; class DOLPHIN_EXPORT KFileItemListWidget : public KStandardItemListWidget @@ -31,29 +30,27 @@ class DOLPHIN_EXPORT KFileItemListWidget : public KStandardItemListWidget Q_OBJECT public: - KFileItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent); + KFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent); ~KFileItemListWidget() override; - static KItemListWidgetInformant* createInformant(); + static KItemListWidgetInformant *createInformant(); protected: virtual void hoverSequenceStarted() override; virtual void hoverSequenceIndexChanged(int sequenceIndex) override; virtual void hoverSequenceEnded() override; - bool isRoleRightAligned(const QByteArray& role) const override; + bool isRoleRightAligned(const QByteArray &role) const override; bool isHidden() const override; - QFont customizedFont(const QFont& baseFont) const override; + QFont customizedFont(const QFont &baseFont) const override; /** * @return Selection length without MIME-type extension */ - int selectionLength(const QString& text) const override; + int selectionLength(const QString &text) const override; private: - KFileItemListView* listView(); + KFileItemListView *listView(); }; #endif - - diff --git a/src/kitemviews/kfileitemmodel.cpp b/src/kitemviews/kfileitemmodel.cpp index 5e6f9af01b..14de9697ba 100644 --- a/src/kitemviews/kfileitemmodel.cpp +++ b/src/kitemviews/kfileitemmodel.cpp @@ -8,24 +8,24 @@ #include "kfileitemmodel.h" -#include "dolphin_generalsettings.h" #include "dolphin_detailsmodesettings.h" +#include "dolphin_generalsettings.h" #include "dolphindebug.h" #include "private/kfileitemmodelsortalgorithm.h" #include #include -#include #include #include +#include #include +#include #include #include +#include #include #include -#include -#include #include #include @@ -33,25 +33,25 @@ Q_GLOBAL_STATIC(QRecursiveMutex, s_collatorMutex) // #define KFILEITEMMODEL_DEBUG -KFileItemModel::KFileItemModel(QObject* parent) : - KItemModelBase("text", parent), - m_dirLister(nullptr), - m_sortDirsFirst(true), - m_sortHiddenLast(false), - m_sortRole(NameRole), - m_sortingProgressPercent(-1), - m_roles(), - m_itemData(), - m_items(), - m_filter(), - m_filteredItems(), - m_requestRole(), - m_maximumUpdateIntervalTimer(nullptr), - m_resortAllItemsTimer(nullptr), - m_pendingItemsToInsert(), - m_groups(), - m_expandedDirs(), - m_urlsToExpand() +KFileItemModel::KFileItemModel(QObject *parent) + : KItemModelBase("text", parent) + , m_dirLister(nullptr) + , m_sortDirsFirst(true) + , m_sortHiddenLast(false) + , m_sortRole(NameRole) + , m_sortingProgressPercent(-1) + , m_roles() + , m_itemData() + , m_items() + , m_filter() + , m_filteredItems() + , m_requestRole() + , m_maximumUpdateIntervalTimer(nullptr) + , m_resortAllItemsTimer(nullptr) + , m_pendingItemsToInsert() + , m_groups() + , m_expandedDirs() + , m_urlsToExpand() { m_collator.setNumericMode(true); @@ -61,7 +61,7 @@ KFileItemModel::KFileItemModel(QObject* parent) : m_dirLister->setAutoErrorHandlingEnabled(false); m_dirLister->setDelayedMimeTypes(true); - const QWidget* parentWidget = qobject_cast(parent); + const QWidget *parentWidget = qobject_cast(parent); if (parentWidget) { m_dirLister->setMainWindow(parentWidget->window()); } @@ -149,7 +149,7 @@ int KFileItemModel::count() const QHash KFileItemModel::data(int index) const { if (index >= 0 && index < count()) { - ItemData* data = m_itemData.at(index); + ItemData *data = m_itemData.at(index); if (data->values.isEmpty()) { data->values = retrieveData(data->item, data->parent); } else if (data->values.count() <= 2 && data->values.value("isExpanded").toBool()) { @@ -171,7 +171,7 @@ QHash KFileItemModel::data(int index) const return QHash(); } -bool KFileItemModel::setData(int index, const QHash& values) +bool KFileItemModel::setData(int index, const QHash &values) { if (index < 0 || index >= count()) { return false; @@ -268,20 +268,20 @@ bool KFileItemModel::showDirectoriesOnly() const return m_dirLister->dirOnlyMode(); } -QMimeData* KFileItemModel::createMimeData(const KItemSet& indexes) const +QMimeData *KFileItemModel::createMimeData(const KItemSet &indexes) const { - QMimeData* data = new QMimeData(); + QMimeData *data = new QMimeData(); // The following code has been taken from KDirModel::mimeData() // (kdelibs/kio/kio/kdirmodel.cpp) // SPDX-FileCopyrightText: 2006 David Faure QList urls; QList mostLocalUrls; - const ItemData* lastAddedItem = nullptr; + const ItemData *lastAddedItem = nullptr; for (int index : indexes) { - const ItemData* itemData = m_itemData.at(index); - const ItemData* parent = itemData->parent; + const ItemData *itemData = m_itemData.at(index); + const ItemData *parent = itemData->parent; while (parent && parent != lastAddedItem) { parent = parent->parent; @@ -293,7 +293,7 @@ QMimeData* KFileItemModel::createMimeData(const KItemSet& indexes) const } lastAddedItem = itemData; - const KFileItem& item = itemData->item; + const KFileItem &item = itemData->item; if (!item.isNull()) { urls << item.url(); @@ -306,7 +306,7 @@ QMimeData* KFileItemModel::createMimeData(const KItemSet& indexes) const return data; } -int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromIndex) const +int KFileItemModel::indexForKeyboardSearch(const QString &text, int startFromIndex) const { startFromIndex = qMax(0, startFromIndex); for (int i = startFromIndex; i < count(); ++i) { @@ -328,12 +328,12 @@ bool KFileItemModel::supportsDropping(int index) const return !item.isNull() && (item.isDir() || item.isDesktopFile()); } -QString KFileItemModel::roleDescription(const QByteArray& role) const +QString KFileItemModel::roleDescription(const QByteArray &role) const { static QHash description; if (description.isEmpty()) { int count = 0; - const RoleInfoMap* map = rolesInfoMap(count); + const RoleInfoMap *map = rolesInfoMap(count); for (int i = 0; i < count; ++i) { if (map[i].roleTranslation.isEmpty()) { continue; @@ -345,7 +345,7 @@ QString KFileItemModel::roleDescription(const QByteArray& role) const return description.value(role); } -QList > KFileItemModel::groups() const +QList> KFileItemModel::groups() const { if (!m_itemData.isEmpty() && m_groups.isEmpty()) { #ifdef KFILEITEMMODEL_DEBUG @@ -353,8 +353,12 @@ QList > KFileItemModel::groups() const timer.start(); #endif switch (typeForRole(sortRole())) { - case NameRole: m_groups = nameRoleGroups(); break; - case SizeRole: m_groups = sizeRoleGroups(); break; + case NameRole: + m_groups = nameRoleGroups(); + break; + case SizeRole: + m_groups = sizeRoleGroups(); + break; case ModificationTimeRole: m_groups = timeRoleGroups([](const ItemData *item) { return item->item.time(KFileItem::ModificationTime); @@ -375,9 +379,15 @@ QList > KFileItemModel::groups() const return item->values.value("deletiontime").toDateTime(); }); break; - case PermissionsRole: m_groups = permissionRoleGroups(); break; - case RatingRole: m_groups = ratingRoleGroups(); break; - default: m_groups = genericStringRoleGroups(sortRole()); break; + case PermissionsRole: + m_groups = permissionRoleGroups(); + break; + case RatingRole: + m_groups = ratingRoleGroups(); + break; + default: + m_groups = genericStringRoleGroups(sortRole()); + break; } #ifdef KFILEITEMMODEL_DEBUG @@ -406,12 +416,12 @@ KFileItem KFileItemModel::fileItem(const QUrl &url) const return KFileItem(); } -int KFileItemModel::index(const KFileItem& item) const +int KFileItemModel::index(const KFileItem &item) const { return index(item.url()); } -int KFileItemModel::index(const QUrl& url) const +int KFileItemModel::index(const QUrl &url) const { const QUrl urlToFind = url.adjusted(QUrl::StripTrailingSlash); @@ -461,13 +471,13 @@ int KFileItemModel::index(const QUrl& url) const } const auto uniqueKeys = indexesForUrl.uniqueKeys(); - for (const QUrl& url : uniqueKeys) { + for (const QUrl &url : uniqueKeys) { if (indexesForUrl.count(url) > 1) { qCWarning(DolphinDebug) << "Multiple items found with the URL" << url; auto it = indexesForUrl.find(url); while (it != indexesForUrl.end() && it.key() == url) { - const ItemData* data = m_itemData.at(it.value()); + const ItemData *data = m_itemData.at(it.value()); qCWarning(DolphinDebug) << "index" << it.value() << ":" << data->item; if (data->parent) { qCWarning(DolphinDebug) << "parent" << data->parent->item; @@ -492,7 +502,7 @@ void KFileItemModel::clear() slotClear(); } -void KFileItemModel::setRoles(const QSet& roles) +void KFileItemModel::setRoles(const QSet &roles) { if (m_roles == roles) { return; @@ -516,7 +526,7 @@ void KFileItemModel::setRoles(const QSet& roles) QSetIterator it(roles); while (it.hasNext()) { - const QByteArray& role = it.next(); + const QByteArray &role = it.next(); m_requestRole[typeForRole(role)] = true; } @@ -532,8 +542,8 @@ void KFileItemModel::setRoles(const QSet& roles) // Clear the 'values' of all filtered items. They will be re-populated with the // correct roles the next time 'values' will be accessed via data(int). - QHash::iterator filteredIt = m_filteredItems.begin(); - const QHash::iterator filteredEnd = m_filteredItems.end(); + QHash::iterator filteredIt = m_filteredItems.begin(); + const QHash::iterator filteredEnd = m_filteredItems.end(); while (filteredIt != filteredEnd) { (*filteredIt)->values.clear(); ++filteredIt; @@ -565,7 +575,7 @@ bool KFileItemModel::setExpanded(int index, bool expanded) m_dirLister->openUrl(url, KDirLister::Keep); const QVariantList previouslyExpandedChildren = m_itemData.at(index)->values.value("previouslyExpandedChildren").value(); - for (const QVariant& var : previouslyExpandedChildren) { + for (const QVariant &var : previouslyExpandedChildren) { m_urlsToExpand.insert(var.toUrl()); } } else { @@ -595,12 +605,12 @@ bool KFileItemModel::setExpanded(int index, bool expanded) int childIndex = firstChildIndex; while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) { - ItemData* itemData = m_itemData.at(childIndex); + ItemData *itemData = m_itemData.at(childIndex); if (itemData->values.value("isExpanded").toBool()) { const QUrl targetUrl = itemData->item.targetUrl(); const QUrl url = itemData->item.url(); m_expandedDirs.remove(targetUrl); - m_dirLister->stop(url); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11 + m_dirLister->stop(url); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11 #if KIO_VERSION >= QT_VERSION_CHECK(5, 92, 0) m_dirLister->forgetDirs(url); #endif @@ -662,7 +672,6 @@ void KFileItemModel::restoreExpandedDirectories(const QSet &urls) void KFileItemModel::expandParentDirectories(const QUrl &url) { - // Assure that each sub-path of the URL that should be // expanded is added to m_urlsToExpand. KDirLister // does not care whether the parent-URL has already been @@ -696,7 +705,7 @@ void KFileItemModel::expandParentDirectories(const QUrl &url) } } -void KFileItemModel::setNameFilter(const QString& nameFilter) +void KFileItemModel::setNameFilter(const QString &nameFilter) { if (m_filter.pattern() != nameFilter) { dispatchPendingItemsToInsert(); @@ -710,7 +719,7 @@ QString KFileItemModel::nameFilter() const return m_filter.pattern(); } -void KFileItemModel::setMimeTypeFilters(const QStringList& filters) +void KFileItemModel::setMimeTypeFilters(const QStringList &filters) { if (m_filter.mimeTypes() != filters) { dispatchPendingItemsToInsert(); @@ -740,8 +749,7 @@ void KFileItemModel::applyFilters() for (int index = m_itemData.count() - 1; index >= 0; --index) { ItemData *itemData = m_itemData.at(index); - if (m_filter.matches(itemData->item) - || (itemShownBelow && itemShownBelow->parent == itemData)) { + if (m_filter.matches(itemData->item) || (itemShownBelow && itemShownBelow->parent == itemData)) { // We could've entered here for two reasons: // 1. This item passes the filter itself // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below @@ -808,7 +816,7 @@ void KFileItemModel::applyFilters() insertItems(newVisibleItems); } -void KFileItemModel::removeFilteredChildren(const KItemRangeList& itemRanges) +void KFileItemModel::removeFilteredChildren(const KItemRangeList &itemRanges) { if (m_filteredItems.isEmpty() || !m_requestRole[ExpandedParentsCountRole]) { // There are either no filtered items, or it is not possible to expand @@ -816,14 +824,14 @@ void KFileItemModel::removeFilteredChildren(const KItemRangeList& itemRanges) return; } - QSet parents; - for (const KItemRange& range : itemRanges) { + QSet parents; + for (const KItemRange &range : itemRanges) { for (int index = range.index; index < range.index + range.count; ++index) { parents.insert(m_itemData.at(index)); } } - QHash::iterator it = m_filteredItems.begin(); + QHash::iterator it = m_filteredItems.begin(); while (it != m_filteredItems.end()) { if (parents.contains(it.value()->parent)) { delete it.value(); @@ -839,7 +847,7 @@ QList KFileItemModel::rolesInformation() static QList rolesInfo; if (rolesInfo.isEmpty()) { int count = 0; - const RoleInfoMap* map = rolesInfoMap(count); + const RoleInfoMap *map = rolesInfoMap(count); for (int i = 0; i < count; ++i) { if (map[i].roleType != NoRole) { RoleInfo info; @@ -869,7 +877,7 @@ void KFileItemModel::onGroupedSortingChanged(bool current) m_groups.clear(); } -void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems) +void KFileItemModel::onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems) { Q_UNUSED(previous) m_sortRole = typeForRole(current); @@ -937,7 +945,7 @@ void KFileItemModel::resortAllItems() // been moved because of the resorting. QList oldUrls; oldUrls.reserve(itemCount); - for (const ItemData* itemData : qAsConst(m_itemData)) { + for (const ItemData *itemData : qAsConst(m_itemData)) { oldUrls.append(itemData->item.url()); } @@ -952,8 +960,7 @@ void KFileItemModel::resortAllItems() // Determine the first index that has been moved. int firstMovedIndex = 0; - while (firstMovedIndex < itemCount - && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) { + while (firstMovedIndex < itemCount && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) { ++firstMovedIndex; } @@ -962,8 +969,7 @@ void KFileItemModel::resortAllItems() m_groups.clear(); int lastMovedIndex = itemCount - 1; - while (lastMovedIndex > firstMovedIndex - && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) { + while (lastMovedIndex > firstMovedIndex && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) { --lastMovedIndex; } @@ -983,7 +989,7 @@ void KFileItemModel::resortAllItems() Q_EMIT itemsMoved(KItemRange(firstMovedIndex, movedItemsCount), movedToIndexes); } else if (groupedSorting()) { // The groups might have changed even if the order of the items has not. - const QList > oldGroups = m_groups; + const QList> oldGroups = m_groups; m_groups.clear(); if (groups() != oldGroups) { Q_EMIT groupsChanged(); @@ -1007,7 +1013,7 @@ void KFileItemModel::slotCompleted() // -> we expand the first visible URL we find in m_restoredExpandedUrls. // Iterate over a const copy because items are deleted and inserted within the loop const auto urlsToExpand = m_urlsToExpand; - for(const QUrl &url : urlsToExpand) { + for (const QUrl &url : urlsToExpand) { const int indexForUrl = index(url); if (indexForUrl >= 0) { m_urlsToExpand.remove(url); @@ -1035,7 +1041,7 @@ void KFileItemModel::slotCanceled() Q_EMIT directoryLoadingCanceled(); } -void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList& items) +void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList &items) { Q_ASSERT(!items.isEmpty()); @@ -1068,7 +1074,7 @@ void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemLis } } - const QList itemDataList = createItemDataList(parentUrl, items); + const QList itemDataList = createItemDataList(parentUrl, items); if (!m_filter.hasSetFilters()) { m_pendingItemsToInsert.append(itemDataList); @@ -1078,7 +1084,7 @@ void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemLis // The name or type filter is active. Hide filtered items // before inserting them into the model and remember // the filtered items in m_filteredItems. - for (ItemData* itemData : itemDataList) { + for (ItemData *itemData : itemDataList) { if (m_filter.matches(itemData->item)) { m_pendingItemsToInsert.append(itemData); if (itemData->parent) { @@ -1142,7 +1148,7 @@ int KFileItemModel::filterChildlessParents(KItemRangeList &removedItemRanges, co return filteredParentsCount; } -void KFileItemModel::slotItemsDeleted(const KFileItemList& items) +void KFileItemModel::slotItemsDeleted(const KFileItemList &items) { dispatchPendingItemsToInsert(); @@ -1152,7 +1158,7 @@ void KFileItemModel::slotItemsDeleted(const KFileItemList& items) const auto currentDir = directory(); - for (const KFileItem& item : items) { + for (const KFileItem &item : items) { if (item.url() == currentDir) { Q_EMIT currentDirectoryRemoved(); return; @@ -1163,7 +1169,7 @@ void KFileItemModel::slotItemsDeleted(const KFileItemList& items) indexesToRemove.append(indexForItem); } else { // Probably the item has been filtered. - QHash::iterator it = m_filteredItems.find(item); + QHash::iterator it = m_filteredItems.find(item); if (it != m_filteredItems.end()) { delete it.value(); m_filteredItems.erase(it); @@ -1213,7 +1219,7 @@ void KFileItemModel::slotItemsDeleted(const KFileItemList& items) Q_EMIT fileItemsChanged(dirsChanged); } -void KFileItemModel::slotRefreshItems(const QList >& items) +void KFileItemModel::slotRefreshItems(const QList> &items) { Q_ASSERT(!items.isEmpty()); #ifdef KFILEITEMMODEL_DEBUG @@ -1233,14 +1239,14 @@ void KFileItemModel::slotRefreshItems(const QList >& // Contains currently hidden items that should // get visible and hence removed from m_filteredItems - QList newVisibleItems; + QList newVisibleItems; - QListIterator > it(items); + QListIterator> it(items); while (it.hasNext()) { - const QPair& itemPair = it.next(); - const KFileItem& oldItem = itemPair.first; - const KFileItem& newItem = itemPair.second; + const QPair &itemPair = it.next(); + const KFileItem &oldItem = itemPair.first; + const KFileItem &newItem = itemPair.second; const int indexForItem = index(oldItem); const bool newItemMatchesFilter = m_filter.matches(newItem); if (indexForItem >= 0) { @@ -1248,11 +1254,11 @@ void KFileItemModel::slotRefreshItems(const QList >& // Keep old values as long as possible if they could not retrieved synchronously yet. // The update of the values will be done asynchronously by KFileItemModelRolesUpdater. - ItemData * const itemData = m_itemData.at(indexForItem); + ItemData *const itemData = m_itemData.at(indexForItem); QHashIterator it(retrieveData(newItem, itemData->parent)); while (it.hasNext()) { it.next(); - const QByteArray& role = it.key(); + const QByteArray &role = it.key(); if (itemData->values.value(role) != it.value()) { itemData->values.insert(role, it.value()); changedRoles.insert(role); @@ -1276,7 +1282,7 @@ void KFileItemModel::slotRefreshItems(const QList >& } } else { // Check if 'oldItem' is one of the filtered items. - QHash::iterator it = m_filteredItems.find(oldItem); + QHash::iterator it = m_filteredItems.find(oldItem); if (it != m_filteredItems.end()) { ItemData *const itemData = it.value(); itemData->item = newItem; @@ -1413,7 +1419,7 @@ void KFileItemModel::dispatchPendingItemsToInsert() } } -void KFileItemModel::insertItems(QList& newItems) +void KFileItemModel::insertItems(QList &newItems) { if (newItems.isEmpty()) { return; @@ -1436,8 +1442,7 @@ void KFileItemModel::insertItems(QList& newItems) if (m_sortRole == NameRole) { parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount()); } else if (isRoleValueNatural(m_sortRole)) { - auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b) - { + auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) { const QByteArray role = roleForType(m_sortRole); return a->values.value(role).toString() < b->values.value(role).toString(); }; @@ -1476,7 +1481,7 @@ void KFileItemModel::insertItems(QList& newItems) int rangeCount = 0; while (sourceIndexNewItems >= 0) { - ItemData* newItem = newItems.at(sourceIndexNewItems); + ItemData *newItem = newItems.at(sourceIndexNewItems); if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) { // Move an existing item to its new position. If any new items // are behind it, push the item range to itemRanges. @@ -1516,7 +1521,7 @@ void KFileItemModel::insertItems(QList& newItems) #endif } -void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior) +void KFileItemModel::removeItems(const KItemRangeList &itemRanges, RemoveItemsBehavior behavior) { if (itemRanges.isEmpty()) { return; @@ -1526,7 +1531,7 @@ void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBe // Step 1: Remove the items from m_itemData, and free the ItemData. int removedItemsCount = 0; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { removedItemsCount += range.count; for (int index = range.index; index < range.index + range.count; ++index) { @@ -1565,7 +1570,7 @@ void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBe Q_EMIT itemsRemoved(itemRanges); } -QList KFileItemModel::createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const +QList KFileItemModel::createItemDataList(const QUrl &parentUrl, const KFileItemList &items) const { if (m_sortRole == TypeRole) { // Try to resolve the MIME-types synchronously to prevent a reordering of @@ -1578,11 +1583,11 @@ QList KFileItemModel::createItemDataList(const QUrl& const int parentIndex = index(parentUrl); ItemData *parentItem = parentIndex < 0 ? m_filteredItems.value(KFileItem(parentUrl), nullptr) : m_itemData.at(parentIndex); - QList itemDataList; + QList itemDataList; itemDataList.reserve(items.count()); - for (const KFileItem& item : items) { - ItemData* itemData = new ItemData(); + for (const KFileItem &item : items) { + ItemData *itemData = new ItemData(); itemData->item = item; itemData->parent = parentItem; itemDataList.append(itemData); @@ -1591,7 +1596,7 @@ QList KFileItemModel::createItemDataList(const QUrl& return itemDataList; } -void KFileItemModel::prepareItemsForSorting(QList& itemDataList) +void KFileItemModel::prepareItemsForSorting(QList &itemDataList) { switch (m_sortRole) { case ExtensionRole: @@ -1603,7 +1608,7 @@ void KFileItemModel::prepareItemsForSorting(QList& itemDataList) case DeletionTimeRole: // These roles can be determined with retrieveData, and they have to be stored // in the QHash "values" for the sorting. - for (ItemData* itemData : qAsConst(itemDataList)) { + for (ItemData *itemData : qAsConst(itemDataList)) { if (itemData->values.isEmpty()) { itemData->values = retrieveData(itemData->item, itemData->parent); } @@ -1612,7 +1617,7 @@ void KFileItemModel::prepareItemsForSorting(QList& itemDataList) case TypeRole: // At least store the data including the file type for items with known MIME type. - for (ItemData* itemData : qAsConst(itemDataList)) { + for (ItemData *itemData : qAsConst(itemDataList)) { if (itemData->values.isEmpty()) { const KFileItem item = itemData->item; if (item.isDir() || item.isMimeTypeKnown()) { @@ -1632,11 +1637,11 @@ void KFileItemModel::prepareItemsForSorting(QList& itemDataList) } } -int KFileItemModel::expandedParentsCount(const ItemData* data) +int KFileItemModel::expandedParentsCount(const ItemData *data) { // The hash 'values' is only guaranteed to contain the key "expandedParentsCount" // if the corresponding item is expanded, and it is not a top-level item. - const ItemData* parent = data->parent; + const ItemData *parent = data->parent; if (parent) { if (parent->parent) { Q_ASSERT(parent->values.contains("expandedParentsCount")); @@ -1655,7 +1660,7 @@ void KFileItemModel::removeExpandedItems() const int maxIndex = m_itemData.count() - 1; for (int i = 0; i <= maxIndex; ++i) { - const ItemData* itemData = m_itemData.at(i); + const ItemData *itemData = m_itemData.at(i); if (itemData->parent) { indexesToRemove.append(i); } @@ -1665,8 +1670,8 @@ void KFileItemModel::removeExpandedItems() m_expandedDirs.clear(); // Also remove all filtered items which have a parent. - QHash::iterator it = m_filteredItems.begin(); - const QHash::iterator end = m_filteredItems.end(); + QHash::iterator it = m_filteredItems.begin(); + const QHash::iterator end = m_filteredItems.end(); while (it != end) { if (it.value()->parent) { @@ -1678,14 +1683,14 @@ void KFileItemModel::removeExpandedItems() } } -void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet& changedRoles) +void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet &changedRoles) { Q_EMIT itemsChanged(itemRanges, changedRoles); // Trigger a resorting if necessary. Note that this can happen even if the sort // role has not changed at all because the file name can be used as a fallback. if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))) { - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { bool needsResorting = false; const int first = range.index; @@ -1695,11 +1700,9 @@ void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList& i // (a) The first item in the range is "lessThan" its predecessor, // (b) the successor of the last item is "lessThan" the last item, or // (c) the internal order of the items in the range is incorrect. - if (first > 0 - && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) { + if (first > 0 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) { needsResorting = true; - } else if (last < count() - 1 - && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) { + } else if (last < count() - 1 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) { needsResorting = true; } else { for (int index = first; index < last; ++index) { @@ -1737,14 +1740,14 @@ void KFileItemModel::resetRoles() } } -KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const +KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray &role) const { static QHash roles; if (roles.isEmpty()) { // Insert user visible roles that can be accessed with // KFileItemModel::roleInformation() int count = 0; - const RoleInfoMap* map = rolesInfoMap(count); + const RoleInfoMap *map = rolesInfoMap(count); for (int i = 0; i < count; ++i) { roles.insert(map[i].role, map[i].roleType); } @@ -1771,7 +1774,7 @@ QByteArray KFileItemModel::roleForType(RoleType roleType) const // Insert user visible roles that can be accessed with // KFileItemModel::roleInformation() int count = 0; - const RoleInfoMap* map = rolesInfoMap(count); + const RoleInfoMap *map = rolesInfoMap(count); for (int i = 0; i < count; ++i) { roles.insert(map[i].roleType, map[i].role); } @@ -1791,7 +1794,7 @@ QByteArray KFileItemModel::roleForType(RoleType roleType) const return roles.value(roleType); } -QHash KFileItemModel::retrieveData(const KFileItem& item, const ItemData* parent) const +QHash KFileItemModel::retrieveData(const KFileItem &item, const ItemData *parent) const { // It is important to insert only roles that are fast to retrieve. E.g. // KFileItem::iconName() can be very expensive if the MIME-type is unknown @@ -1930,7 +1933,7 @@ QHash KFileItemModel::retrieveData(const KFileItem& item, return data; } -bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const +bool KFileItemModel::lessThan(const ItemData *a, const ItemData *b, const QCollator &collator) const { int result = 0; @@ -1991,11 +1994,9 @@ bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b, const QColla return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0; } -void KFileItemModel::sort(const QList::iterator &begin, - const QList::iterator &end) const +void KFileItemModel::sort(const QList::iterator &begin, const QList::iterator &end) const { - auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b) - { + auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) { return lessThan(a, b, m_collator); }; @@ -2012,15 +2013,15 @@ void KFileItemModel::sort(const QList::iterator &begi } } -int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const +int KFileItemModel::sortRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const { // This function must never return 0, because that would break stable // sorting, which leads to all kinds of bugs. // See: https://bugs.kde.org/show_bug.cgi?id=433247 // If two items have equal sort values, let the fallbacks at the bottom of // the function handle it. - const KFileItem& itemA = a->item; - const KFileItem& itemB = b->item; + const KFileItem &itemA = a->item; + const KFileItem &itemB = b->item; int result = 0; @@ -2128,7 +2129,7 @@ int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const break; } - case DimensionsRole: { + case DimensionsRole: { const QByteArray role = roleForType(m_sortRole); const QSize dimensionsA = a->values.value(role).toSize(); const QSize dimensionsB = b->values.value(role).toSize(); @@ -2156,7 +2157,6 @@ int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const } break; } - } if (result != 0) { @@ -2182,7 +2182,7 @@ int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive); } -int KFileItemModel::stringCompare(const QString& a, const QString& b, const QCollator& collator) const +int KFileItemModel::stringCompare(const QString &a, const QString &b, const QCollator &collator) const { QMutexLocker collatorLock(s_collatorMutex()); @@ -2201,12 +2201,12 @@ int KFileItemModel::stringCompare(const QString& a, const QString& b, const QCol return QString::compare(a, b, Qt::CaseSensitive); } -QList > KFileItemModel::nameRoleGroups() const +QList> KFileItemModel::nameRoleGroups() const { Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; - QList > groups; + QList> groups; QString groupValue; QChar firstChar; @@ -2226,7 +2226,6 @@ QList > KFileItemModel::nameRoleGroups() const if (firstChar != newFirstChar) { QString newGroupValue; if (newFirstChar.isLetter()) { - if (m_collator.compare(newFirstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(newFirstChar, QChar(QLatin1Char('Z'))) <= 0) { // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group. @@ -2275,12 +2274,12 @@ QList > KFileItemModel::nameRoleGroups() const return groups; } -QList > KFileItemModel::sizeRoleGroups() const +QList> KFileItemModel::sizeRoleGroups() const { Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; - QList > groups; + QList> groups; QString groupValue; for (int i = 0; i <= maxIndex; ++i) { @@ -2288,7 +2287,7 @@ QList > KFileItemModel::sizeRoleGroups() const continue; } - const KFileItem& item = m_itemData.at(i)->item; + const KFileItem &item = m_itemData.at(i)->item; KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U; QString newGroupValue; if (!item.isNull() && item.isDir()) { @@ -2318,12 +2317,12 @@ QList > KFileItemModel::sizeRoleGroups() const return groups; } -QList > KFileItemModel::timeRoleGroups(const std::function &fileTimeCb) const +QList> KFileItemModel::timeRoleGroups(const std::function &fileTimeCb) const { Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; - QList > groups; + QList> groups; const QDate currentDate = QDate::currentDate(); @@ -2345,19 +2344,23 @@ QList > KFileItemModel::timeRoleGroups(const std::function< const int daysDistance = fileDate.daysTo(currentDate); QString newGroupValue; - if (currentDate.year() == fileDate.year() && - currentDate.month() == fileDate.month()) { - + if (currentDate.year() == fileDate.year() && currentDate.month() == fileDate.month()) { switch (daysDistance / 7) { case 0: switch (daysDistance) { - case 0: newGroupValue = i18nc("@title:group Date", "Today"); break; - case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break; + case 0: + newGroupValue = i18nc("@title:group Date", "Today"); + break; + case 1: + newGroupValue = i18nc("@title:group Date", "Yesterday"); + break; default: - newGroupValue = fileTime.toString( - i18nc("@title:group Date: The week day name: dddd", "dddd")); - newGroupValue = i18nc("Can be used to script translation of \"dddd\"" - "with context @title:group Date", "%1", newGroupValue); + newGroupValue = fileTime.toString(i18nc("@title:group Date: The week day name: dddd", "dddd")); + newGroupValue = i18nc( + "Can be used to script translation of \"dddd\"" + "with context @title:group Date", + "%1", + newGroupValue); } break; case 1: @@ -2378,100 +2381,135 @@ QList > KFileItemModel::timeRoleGroups(const std::function< } } else { const QDate lastMonthDate = currentDate.addMonths(-1); - if (lastMonthDate.year() == fileDate.year() && - lastMonthDate.month() == fileDate.month()) { - + if (lastMonthDate.year() == fileDate.year() && lastMonthDate.month() == fileDate.month()) { if (daysDistance == 1) { - const KLocalizedString format = ki18nc("@title:group Date: " - "MMMM is full month name in current locale, and yyyy is " - "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Yesterday' (MMMM, yyyy)"); + const KLocalizedString format = ki18nc( + "@title:group Date: " + "MMMM is full month name in current locale, and yyyy is " + "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a " + "part of the text that should not be formatted as a date", + "'Yesterday' (MMMM, yyyy)"); const QString translatedFormat = format.toString(); if (translatedFormat.count(QLatin1Char('\'')) == 2) { newGroupValue = fileTime.toString(translatedFormat); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = i18nc( + "Can be used to script translation of " "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } else { - qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; - const QString untranslatedFormat = format.toString({ QLatin1String("en_US") }); + qCWarning(DolphinDebug).nospace() + << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; + const QString untranslatedFormat = format.toString({QLatin1String("en_US")}); newGroupValue = fileTime.toString(untranslatedFormat); } } else if (daysDistance <= 7) { - newGroupValue = fileTime.toString(i18nc("@title:group Date: " - "The week day name: dddd, MMMM is full month name " - "in current locale, and yyyy is full year number.", - "dddd (MMMM, yyyy)")); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = + fileTime.toString(i18nc("@title:group Date: " + "The week day name: dddd, MMMM is full month name " + "in current locale, and yyyy is full year number.", + "dddd (MMMM, yyyy)")); + newGroupValue = i18nc( + "Can be used to script translation of " "\"dddd (MMMM, yyyy)\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } else if (daysDistance <= 7 * 2) { - const KLocalizedString format = ki18nc("@title:group Date: " - "MMMM is full month name in current locale, and yyyy is " - "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'One Week Ago' (MMMM, yyyy)"); + const KLocalizedString format = ki18nc( + "@title:group Date: " + "MMMM is full month name in current locale, and yyyy is " + "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a " + "part of the text that should not be formatted as a date", + "'One Week Ago' (MMMM, yyyy)"); const QString translatedFormat = format.toString(); if (translatedFormat.count(QLatin1Char('\'')) == 2) { newGroupValue = fileTime.toString(translatedFormat); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = i18nc( + "Can be used to script translation of " "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } else { - qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; - const QString untranslatedFormat = format.toString({ QLatin1String("en_US") }); + qCWarning(DolphinDebug).nospace() + << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; + const QString untranslatedFormat = format.toString({QLatin1String("en_US")}); newGroupValue = fileTime.toString(untranslatedFormat); } } else if (daysDistance <= 7 * 3) { - const KLocalizedString format = ki18nc("@title:group Date: " - "MMMM is full month name in current locale, and yyyy is " - "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Two Weeks Ago' (MMMM, yyyy)"); + const KLocalizedString format = ki18nc( + "@title:group Date: " + "MMMM is full month name in current locale, and yyyy is " + "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a " + "part of the text that should not be formatted as a date", + "'Two Weeks Ago' (MMMM, yyyy)"); const QString translatedFormat = format.toString(); if (translatedFormat.count(QLatin1Char('\'')) == 2) { newGroupValue = fileTime.toString(translatedFormat); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = i18nc( + "Can be used to script translation of " "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } else { - qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; - const QString untranslatedFormat = format.toString({ QLatin1String("en_US") }); + qCWarning(DolphinDebug).nospace() + << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; + const QString untranslatedFormat = format.toString({QLatin1String("en_US")}); newGroupValue = fileTime.toString(untranslatedFormat); } } else if (daysDistance <= 7 * 4) { - const KLocalizedString format = ki18nc("@title:group Date: " - "MMMM is full month name in current locale, and yyyy is " - "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Three Weeks Ago' (MMMM, yyyy)"); + const KLocalizedString format = ki18nc( + "@title:group Date: " + "MMMM is full month name in current locale, and yyyy is " + "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a " + "part of the text that should not be formatted as a date", + "'Three Weeks Ago' (MMMM, yyyy)"); const QString translatedFormat = format.toString(); if (translatedFormat.count(QLatin1Char('\'')) == 2) { newGroupValue = fileTime.toString(translatedFormat); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = i18nc( + "Can be used to script translation of " "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } else { - qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; - const QString untranslatedFormat = format.toString({ QLatin1String("en_US") }); + qCWarning(DolphinDebug).nospace() + << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; + const QString untranslatedFormat = format.toString({QLatin1String("en_US")}); newGroupValue = fileTime.toString(untranslatedFormat); } } else { - const KLocalizedString format = ki18nc("@title:group Date: " - "MMMM is full month name in current locale, and yyyy is " - "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Earlier on' MMMM, yyyy"); + const KLocalizedString format = ki18nc( + "@title:group Date: " + "MMMM is full month name in current locale, and yyyy is " + "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a " + "part of the text that should not be formatted as a date", + "'Earlier on' MMMM, yyyy"); const QString translatedFormat = format.toString(); if (translatedFormat.count(QLatin1Char('\'')) == 2) { newGroupValue = fileTime.toString(translatedFormat); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = i18nc( + "Can be used to script translation of " "\"'Earlier on' MMMM, yyyy\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } else { - qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; - const QString untranslatedFormat = format.toString({ QLatin1String("en_US") }); + qCWarning(DolphinDebug).nospace() + << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org"; + const QString untranslatedFormat = format.toString({QLatin1String("en_US")}); newGroupValue = fileTime.toString(untranslatedFormat); } } } else { - newGroupValue = fileTime.toString(i18nc("@title:group " - "The month and year: MMMM is full month name in current locale, " - "and yyyy is full year number", "MMMM, yyyy")); - newGroupValue = i18nc("Can be used to script translation of " + newGroupValue = + fileTime.toString(i18nc("@title:group " + "The month and year: MMMM is full month name in current locale, " + "and yyyy is full year number", + "MMMM, yyyy")); + newGroupValue = i18nc( + "Can be used to script translation of " "\"MMMM, yyyy\" with context @title:group Date", - "%1", newGroupValue); + "%1", + newGroupValue); } } @@ -2484,12 +2522,12 @@ QList > KFileItemModel::timeRoleGroups(const std::function< return groups; } -QList > KFileItemModel::permissionRoleGroups() const +QList> KFileItemModel::permissionRoleGroups() const { Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; - QList > groups; + QList> groups; QString permissionsString; QString groupValue; @@ -2498,7 +2536,7 @@ QList > KFileItemModel::permissionRoleGroups() const continue; } - const ItemData* itemData = m_itemData.at(i); + const ItemData *itemData = m_itemData.at(i); const QString newPermissionsString = itemData->values.value("permissions").toString(); if (newPermissionsString == permissionsString) { continue; @@ -2556,12 +2594,12 @@ QList > KFileItemModel::permissionRoleGroups() const return groups; } -QList > KFileItemModel::ratingRoleGroups() const +QList> KFileItemModel::ratingRoleGroups() const { Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; - QList > groups; + QList> groups; int groupValue = -1; for (int i = 0; i <= maxIndex; ++i) { @@ -2578,12 +2616,12 @@ QList > KFileItemModel::ratingRoleGroups() const return groups; } -QList > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const +QList> KFileItemModel::genericStringRoleGroups(const QByteArray &role) const { Q_ASSERT(!m_itemData.isEmpty()); const int maxIndex = count() - 1; - QList > groups; + QList> groups; bool isFirstGroupValue = true; QString groupValue; @@ -2630,7 +2668,7 @@ void KFileItemModel::emitSortProgress(int resolvedCount) } } -const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count) +const KFileItemModel::RoleInfoMap *KFileItemModel::rolesInfoMap(int &count) { static const RoleInfoMap rolesInfoMap[] = { // | role | roleType | role translation | group translation | requires Baloo | requires indexer @@ -2678,11 +2716,11 @@ const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count) return rolesInfoMap; } -void KFileItemModel::determineMimeTypes(const KFileItemList& items, int timeout) +void KFileItemModel::determineMimeTypes(const KFileItemList &items, int timeout) { QElapsedTimer timer; timer.start(); - for (const KFileItem& item : items) { + for (const KFileItem &item : items) { // Only determine mime types for files here. For directories, // KFileItem::determineMimeType() reads the .directory file inside to // load the icon, but this is not necessary at all if we just need the @@ -2700,7 +2738,7 @@ void KFileItemModel::determineMimeTypes(const KFileItemList& items, int timeout) } } -QByteArray KFileItemModel::sharedValue(const QByteArray& value) +QByteArray KFileItemModel::sharedValue(const QByteArray &value) { static QSet pool; const QSet::const_iterator it = pool.constFind(value); @@ -2737,14 +2775,13 @@ bool KFileItemModel::isConsistent() const // Check if the items are sorted correctly. if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) { - qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:" - << fileItem(i - 1) << fileItem(i); + qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:" << fileItem(i - 1) << fileItem(i); return false; } // Check if all parent-child relationships are consistent. - const ItemData* data = m_itemData.at(i); - const ItemData* parent = data->parent; + const ItemData *data = m_itemData.at(i); + const ItemData *parent = data->parent; if (parent) { if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) { qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item; @@ -2753,7 +2790,8 @@ bool KFileItemModel::isConsistent() const const int parentIndex = index(parent->item); if (parentIndex >= i) { - qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child" << data->item; + qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child" + << data->item; return false; } } diff --git a/src/kitemviews/kfileitemmodel.h b/src/kitemviews/kfileitemmodel.h index 368ab76d88..7c4b8ec8f6 100644 --- a/src/kitemviews/kfileitemmodel.h +++ b/src/kitemviews/kfileitemmodel.h @@ -25,8 +25,9 @@ class KDirLister; class QTimer; -namespace KIO { - class Job; +namespace KIO +{ +class Job; } /** @@ -44,7 +45,7 @@ class DOLPHIN_EXPORT KFileItemModel : public KItemModelBase Q_OBJECT public: - explicit KFileItemModel(QObject* parent = nullptr); + explicit KFileItemModel(QObject *parent = nullptr); ~KFileItemModel() override; /** @@ -53,13 +54,13 @@ public: * indicate the current state of the loading process. The items * of the directory are added after the loading has been completed. */ - void loadDirectory(const QUrl& url); + void loadDirectory(const QUrl &url); /** * Throws away all currently loaded items and refreshes the directory * by reloading all items again. */ - void refreshDirectory(const QUrl& url); + void refreshDirectory(const QUrl &url); /** * @return Parent directory of the items that are shown. In case @@ -77,7 +78,7 @@ public: int count() const override; QHash data(int index) const override; - bool setData(int index, const QHash& values) override; + bool setData(int index, const QHash &values) override; /** * Sets a separate sorting with directories first (true) or a mixed @@ -102,15 +103,15 @@ public: void setShowDirectoriesOnly(bool enabled); bool showDirectoriesOnly() const; - QMimeData* createMimeData(const KItemSet& indexes) const override; + QMimeData *createMimeData(const KItemSet &indexes) const override; - int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const override; + int indexForKeyboardSearch(const QString &text, int startFromIndex = 0) const override; bool supportsDropping(int index) const override; - QString roleDescription(const QByteArray& role) const override; + QString roleDescription(const QByteArray &role) const override; - QList > groups() const override; + QList> groups() const override; /** * @return The file-item for the index \a index. If the index is in a valid @@ -124,14 +125,14 @@ public: * URL is found KFileItem::isNull() will be true for the returned * file-item. The runtime complexity of this call is O(1). */ - KFileItem fileItem(const QUrl& url) const; + KFileItem fileItem(const QUrl &url) const; /** * @return The index for the file-item \a item. -1 is returned if no file-item * is found or if the file-item is null. The amortized runtime * complexity of this call is O(1). */ - int index(const KFileItem& item) const; + int index(const KFileItem &item) const; /** * @return The index for the URL \a url. -1 is returned if no file-item @@ -153,7 +154,7 @@ public: /** * Sets the roles that should be shown for each item. */ - void setRoles(const QSet& roles); + void setRoles(const QSet &roles); QSet roles() const; bool setExpanded(int index, bool expanded) override; @@ -168,21 +169,21 @@ public: * After calling loadDirectory() or refreshDirectory() the marked sub-directories * will be expanded step-by-step. */ - void restoreExpandedDirectories(const QSet& urls); + void restoreExpandedDirectories(const QSet &urls); /** * Expands all parent-directories of the item \a url. */ - void expandParentDirectories(const QUrl& url); + void expandParentDirectories(const QUrl &url); - void setNameFilter(const QString& nameFilter); + void setNameFilter(const QString &nameFilter); QString nameFilter() const; - void setMimeTypeFilters(const QStringList& filters); + void setMimeTypeFilters(const QStringList &filters); QStringList mimeTypeFilters() const; - struct RoleInfo - { QByteArray role; + struct RoleInfo { + QByteArray role; QString translation; QString group; bool requiresBaloo; @@ -237,25 +238,25 @@ Q_SIGNALS: * Is emitted if an information message (e.g. "Connecting to host...") * should be shown. */ - void infoMessage(const QString& message); + void infoMessage(const QString &message); /** * Is emitted if an error message (e.g. "Unknown location") * should be shown. */ - void errorMessage(const QString& message); + void errorMessage(const QString &message); /** * Is emitted if a redirection from the current URL \a oldUrl * to the new URL \a newUrl has been done. */ - void directoryRedirection(const QUrl& oldUrl, const QUrl& newUrl); + void directoryRedirection(const QUrl &oldUrl, const QUrl &newUrl); /** * Is emitted when the URL passed by KFileItemModel::setUrl() represents a file. * In this case no signal errorMessage() will be emitted. */ - void urlIsFileError(const QUrl& url); + void urlIsFileError(const QUrl &url); /** * It is emitted for files when they change and @@ -270,7 +271,7 @@ Q_SIGNALS: protected: void onGroupedSortingChanged(bool current) override; - void onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems = true) override; + void onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems = true) override; void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous) override; private Q_SLOTS: @@ -282,9 +283,9 @@ private Q_SLOTS: void slotCompleted(); void slotCanceled(); - void slotItemsAdded(const QUrl& directoryUrl, const KFileItemList& items); - void slotItemsDeleted(const KFileItemList& items); - void slotRefreshItems(const QList >& items); + void slotItemsAdded(const QUrl &directoryUrl, const KFileItemList &items); + void slotItemsDeleted(const KFileItemList &items); + void slotRefreshItems(const QList> &items); void slotClear(); void slotSortingChoiceChanged(); void slotListerError(KIO::Job *job); @@ -294,33 +295,66 @@ private Q_SLOTS: private: enum RoleType { // User visible roles: - NoRole, NameRole, SizeRole, ModificationTimeRole, CreationTimeRole, AccessTimeRole, PermissionsRole, OwnerRole, - GroupRole, TypeRole, ExtensionRole, DestinationRole, PathRole, DeletionTimeRole, + NoRole, + NameRole, + SizeRole, + ModificationTimeRole, + CreationTimeRole, + AccessTimeRole, + PermissionsRole, + OwnerRole, + GroupRole, + TypeRole, + ExtensionRole, + DestinationRole, + PathRole, + DeletionTimeRole, // User visible roles available with Baloo: - CommentRole, TagsRole, RatingRole, DimensionsRole, WidthRole, HeightRole, ImageDateTimeRole, OrientationRole, - PublisherRole, PageCountRole, WordCountRole, TitleRole, AuthorRole, LineCountRole, ArtistRole, GenreRole, AlbumRole, DurationRole, TrackRole, ReleaseYearRole, - BitrateRole, OriginUrlRole, AspectRatioRole, FrameRateRole, + CommentRole, + TagsRole, + RatingRole, + DimensionsRole, + WidthRole, + HeightRole, + ImageDateTimeRole, + OrientationRole, + PublisherRole, + PageCountRole, + WordCountRole, + TitleRole, + AuthorRole, + LineCountRole, + ArtistRole, + GenreRole, + AlbumRole, + DurationRole, + TrackRole, + ReleaseYearRole, + BitrateRole, + OriginUrlRole, + AspectRatioRole, + FrameRateRole, // Non-visible roles: - IsDirRole, IsLinkRole, IsHiddenRole, IsExpandedRole, IsExpandableRole, ExpandedParentsCountRole, + IsDirRole, + IsLinkRole, + IsHiddenRole, + IsExpandedRole, + IsExpandableRole, + ExpandedParentsCountRole, // Mandatory last entry: RolesCount }; - struct ItemData - { + struct ItemData { KFileItem item; QHash values; - ItemData* parent; + ItemData *parent; }; - enum RemoveItemsBehavior { - KeepItemData, - DeleteItemData, - DeleteItemDataIfUnfiltered - }; + enum RemoveItemsBehavior { KeepItemData, DeleteItemData, DeleteItemDataIfUnfiltered }; - void insertItems(QList& items); - void removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior); + void insertItems(QList &items); + void removeItems(const KItemRangeList &itemRanges, RemoveItemsBehavior behavior); /** * Helper method for insertItems() and removeItems(): Creates @@ -328,16 +362,16 @@ private: * Note that the ItemData instances are created dynamically and * must be deleted by the caller. */ - QList createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const; + QList createItemDataList(const QUrl &parentUrl, const KFileItemList &items) const; /** * Prepares the items for sorting. Normally, the hash 'values' in ItemData is filled * lazily to save time and memory, but for some sort roles, it is expected that the * sort role data is stored in 'values'. */ - void prepareItemsForSorting(QList& itemDataList); + void prepareItemsForSorting(QList &itemDataList); - static int expandedParentsCount(const ItemData* data); + static int expandedParentsCount(const ItemData *data); void removeExpandedItems(); @@ -346,7 +380,7 @@ private: * the itemsChanged() signal, checks if the sort order is still correct, * and starts m_resortAllItemsTimer if that is not the case. */ - void emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet& changedRoles); + void emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet &changedRoles); /** * Resets all values from m_requestRole to false. @@ -357,7 +391,7 @@ private: * @return Role-type for the given role. * Runtime complexity is O(1). */ - RoleType typeForRole(const QByteArray& role) const; + RoleType typeForRole(const QByteArray &role) const; /** * @return Role-byte-array for the given role-type. @@ -365,7 +399,7 @@ private: */ QByteArray roleForType(RoleType roleType) const; - QHash retrieveData(const KFileItem& item, const ItemData* parent) const; + QHash retrieveData(const KFileItem &item, const ItemData *parent) const; /** * @return True if role values benefit from natural or case insensitive sorting. @@ -376,35 +410,35 @@ private: * @return True if \a a has a KFileItem whose text is 'less than' the one * of \a b according to QString::operator<(const QString&). */ - static bool nameLessThan(const ItemData* a, const ItemData* b); + static bool nameLessThan(const ItemData *a, const ItemData *b); /** * @return True if the item-data \a a should be ordered before the item-data * \b. The item-data may have different parent-items. */ - bool lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const; + bool lessThan(const ItemData *a, const ItemData *b, const QCollator &collator) const; /** * Sorts the items between \a begin and \a end using the comparison * function lessThan(). */ - void sort(const QList::iterator &begin, const QList::iterator &end) const; + void sort(const QList::iterator &begin, const QList::iterator &end) const; /** * Helper method for lessThan() and expandedParentsCountCompare(): Compares * the passed item-data using m_sortRole as criteria. Both items must * have the same parent item, otherwise the comparison will be wrong. */ - int sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const; + int sortRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const; - int stringCompare(const QString& a, const QString& b, const QCollator& collator) const; + int stringCompare(const QString &a, const QString &b, const QCollator &collator) const; - QList > nameRoleGroups() const; - QList > sizeRoleGroups() const; - QList > timeRoleGroups(const std::function &fileTimeCb) const; - QList > permissionRoleGroups() const; - QList > ratingRoleGroups() const; - QList > genericStringRoleGroups(const QByteArray& typeForRole) const; + QList> nameRoleGroups() const; + QList> sizeRoleGroups() const; + QList> timeRoleGroups(const std::function &fileTimeCb) const; + QList> permissionRoleGroups() const; + QList> ratingRoleGroups() const; + QList> genericStringRoleGroups(const QByteArray &typeForRole) const; /** * Helper method for all xxxRoleGroups() methods to check whether the @@ -431,7 +465,7 @@ private: * Removes filtered items whose expanded parents have been deleted * or collapsed via setExpanded(parentIndex, false). */ - void removeFilteredChildren(const KItemRangeList& parents); + void removeFilteredChildren(const KItemRangeList &parents); /** * Loads the selected choice of sorting method from Dolphin General Settings @@ -442,9 +476,8 @@ private: * Maps the QByteArray-roles to RoleTypes and provides translation- and * group-contexts. */ - struct RoleInfoMap - { - const char* const role; + struct RoleInfoMap { + const char *const role; const RoleType roleType; const KLazyLocalizedString roleTranslation; const KLazyLocalizedString groupTranslation; @@ -455,19 +488,19 @@ private: /** * @return Map of user visible roles that are accessible by KFileItemModel::rolesInformation(). */ - static const RoleInfoMap* rolesInfoMap(int& count); + static const RoleInfoMap *rolesInfoMap(int &count); /** * Determines the MIME-types of all items that can be done within * the given timeout. */ - static void determineMimeTypes(const KFileItemList& items, int timeout); + static void determineMimeTypes(const KFileItemList &items, int timeout); /** * @return Returns a copy of \a value that is implicitly shared * with other users to save memory. */ - static QByteArray sharedValue(const QByteArray& value); + static QByteArray sharedValue(const QByteArray &value); /** * Checks if the model's internal data structures are consistent. @@ -495,7 +528,7 @@ private: int m_sortingProgressPercent; // Value of directorySortingProgress() signal QSet m_roles; - QList m_itemData; + QList m_itemData; // m_items is a cache for the method index(const QUrl&). If it contains N // entries, it is guaranteed that these correspond to the first N items in @@ -504,16 +537,16 @@ private: mutable QHash m_items; KFileItemModelFilter m_filter; - QHash m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter() + QHash m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter() bool m_requestRole[RolesCount]; - QTimer* m_maximumUpdateIntervalTimer; - QTimer* m_resortAllItemsTimer; - QList m_pendingItemsToInsert; + QTimer *m_maximumUpdateIntervalTimer; + QTimer *m_resortAllItemsTimer; + QList m_pendingItemsToInsert; // Cache for KFileItemModel::groups() - mutable QList > m_groups; + mutable QList> m_groups; // Stores the URLs (key: target url, value: url) of the expanded directories. QHash m_expandedDirs; @@ -522,31 +555,21 @@ private: // and done step after step in slotCompleted(). QSet m_urlsToExpand; - friend class KFileItemModelRolesUpdater; // Accesses emitSortProgress() method - friend class KFileItemModelTest; // For unit testing - friend class KFileItemModelBenchmark; // For unit testing - friend class KFileItemListViewTest; // For unit testing - friend class DolphinPart; // Accesses m_dirLister + friend class KFileItemModelRolesUpdater; // Accesses emitSortProgress() method + friend class KFileItemModelTest; // For unit testing + friend class KFileItemModelBenchmark; // For unit testing + friend class KFileItemListViewTest; // For unit testing + friend class DolphinPart; // Accesses m_dirLister }; inline bool KFileItemModel::isRoleValueNatural(RoleType roleType) { - return (roleType == TypeRole || - roleType == ExtensionRole || - roleType == TagsRole || - roleType == CommentRole || - roleType == TitleRole || - roleType == ArtistRole || - roleType == GenreRole || - roleType == AlbumRole || - roleType == PathRole || - roleType == DestinationRole || - roleType == OriginUrlRole || - roleType == OwnerRole || - roleType == GroupRole); + return (roleType == TypeRole || roleType == ExtensionRole || roleType == TagsRole || roleType == CommentRole || roleType == TitleRole + || roleType == ArtistRole || roleType == GenreRole || roleType == AlbumRole || roleType == PathRole || roleType == DestinationRole + || roleType == OriginUrlRole || roleType == OwnerRole || roleType == GroupRole); } -inline bool KFileItemModel::nameLessThan(const ItemData* a, const ItemData* b) +inline bool KFileItemModel::nameLessThan(const ItemData *a, const ItemData *b) { return a->item.text() < b->item.text(); } @@ -561,5 +584,3 @@ inline bool KFileItemModel::isChildItem(int index) const } #endif - - diff --git a/src/kitemviews/kfileitemmodelrolesupdater.cpp b/src/kitemviews/kfileitemmodelrolesupdater.cpp index 568f43a4bf..cf660cb9fb 100644 --- a/src/kitemviews/kfileitemmodelrolesupdater.cpp +++ b/src/kitemviews/kfileitemmodelrolesupdater.cpp @@ -38,55 +38,56 @@ using namespace std::chrono_literals; // #define KFILEITEMMODELROLESUPDATER_DEBUG -namespace { - // Maximum time in ms that the KFileItemModelRolesUpdater - // may perform a blocking operation - const int MaxBlockTimeout = 200; +namespace +{ +// Maximum time in ms that the KFileItemModelRolesUpdater +// may perform a blocking operation +const int MaxBlockTimeout = 200; - // If the number of items is smaller than ResolveAllItemsLimit, - // the roles of all items will be resolved. - const int ResolveAllItemsLimit = 500; +// If the number of items is smaller than ResolveAllItemsLimit, +// the roles of all items will be resolved. +const int ResolveAllItemsLimit = 500; - // Not only the visible area, but up to ReadAheadPages before and after - // this area will be resolved. - const int ReadAheadPages = 5; +// Not only the visible area, but up to ReadAheadPages before and after +// this area will be resolved. +const int ReadAheadPages = 5; } -KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QObject* parent) : - QObject(parent), - m_state(Idle), - m_previewChangedDuringPausing(false), - m_iconSizeChangedDuringPausing(false), - m_rolesChangedDuringPausing(false), - m_previewShown(false), - m_enlargeSmallPreviews(true), - m_clearPreviews(false), - m_finishedItems(), - m_model(model), - m_iconSize(), - m_firstVisibleIndex(0), - m_lastVisibleIndex(-1), - m_maximumVisibleItems(50), - m_roles(), - m_resolvableRoles(), - m_enabledPlugins(), - m_localFileSizePreviewLimit(0), - m_scanDirectories(true), - m_pendingSortRoleItems(), - m_pendingIndexes(), - m_pendingPreviewItems(), - m_previewJob(), - m_hoverSequenceItem(), - m_hoverSequenceIndex(0), - m_hoverSequencePreviewJob(nullptr), - m_hoverSequenceNumSuccessiveFailures(0), - m_recentlyChangedItemsTimer(nullptr), - m_recentlyChangedItems(), - m_changedItems(), - m_directoryContentsCounter(nullptr) - #if HAVE_BALOO - , m_balooFileMonitor(nullptr) - #endif +KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel *model, QObject *parent) + : QObject(parent) + , m_state(Idle) + , m_previewChangedDuringPausing(false) + , m_iconSizeChangedDuringPausing(false) + , m_rolesChangedDuringPausing(false) + , m_previewShown(false) + , m_enlargeSmallPreviews(true) + , m_clearPreviews(false) + , m_finishedItems() + , m_model(model) + , m_iconSize() + , m_firstVisibleIndex(0) + , m_lastVisibleIndex(-1) + , m_maximumVisibleItems(50) + , m_roles() + , m_resolvableRoles() + , m_enabledPlugins() + , m_localFileSizePreviewLimit(0) + , m_scanDirectories(true) + , m_pendingSortRoleItems() + , m_pendingIndexes() + , m_pendingPreviewItems() + , m_previewJob() + , m_hoverSequenceItem() + , m_hoverSequenceIndex(0) + , m_hoverSequencePreviewJob(nullptr) + , m_hoverSequenceNumSuccessiveFailures(0) + , m_recentlyChangedItemsTimer(nullptr) + , m_recentlyChangedItems() + , m_changedItems() + , m_directoryContentsCounter(nullptr) +#if HAVE_BALOO + , m_balooFileMonitor(nullptr) +#endif { Q_ASSERT(model); @@ -94,16 +95,11 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO m_enabledPlugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins()); m_localFileSizePreviewLimit = static_cast(globalConfig.readEntry("MaximumSize", 0)); - connect(m_model, &KFileItemModel::itemsInserted, - this, &KFileItemModelRolesUpdater::slotItemsInserted); - connect(m_model, &KFileItemModel::itemsRemoved, - this, &KFileItemModelRolesUpdater::slotItemsRemoved); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); - connect(m_model, &KFileItemModel::itemsMoved, - this, &KFileItemModelRolesUpdater::slotItemsMoved); - connect(m_model, &KFileItemModel::sortRoleChanged, - this, &KFileItemModelRolesUpdater::slotSortRoleChanged); + connect(m_model, &KFileItemModel::itemsInserted, this, &KFileItemModelRolesUpdater::slotItemsInserted); + connect(m_model, &KFileItemModel::itemsRemoved, this, &KFileItemModelRolesUpdater::slotItemsRemoved); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsMoved, this, &KFileItemModelRolesUpdater::slotItemsMoved); + connect(m_model, &KFileItemModel::sortRoleChanged, this, &KFileItemModelRolesUpdater::slotSortRoleChanged); // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous // resolving of the roles. Postpone the resolving until no update has been done for 100 ms. @@ -120,8 +116,7 @@ KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QO #endif m_directoryContentsCounter = new KDirectoryContentsCounter(m_model, this); - connect(m_directoryContentsCounter, &KDirectoryContentsCounter::result, - this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived); + connect(m_directoryContentsCounter, &KDirectoryContentsCounter::result, this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived); const auto plugins = KPluginMetaData::findPlugins(QStringLiteral("kf" QT_STRINGIFY(QT_VERSION_MAJOR)) + QStringLiteral("/overlayicon")); for (const KPluginMetaData &data : plugins) { @@ -142,7 +137,7 @@ KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater() killPreviewJob(); } -void KFileItemModelRolesUpdater::setIconSize(const QSize& size) +void KFileItemModelRolesUpdater::setIconSize(const QSize &size) { if (size != m_iconSize) { m_iconSize = size; @@ -221,7 +216,7 @@ bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const return m_enlargeSmallPreviews; } -void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList& list) +void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList &list) { if (m_enabledPlugins != list) { m_enabledPlugins = list; @@ -241,8 +236,7 @@ void KFileItemModelRolesUpdater::setPaused(bool paused) m_state = Paused; killPreviewJob(); } else { - const bool updatePreviews = (m_iconSizeChangedDuringPausing && m_previewShown) || - m_previewChangedDuringPausing; + const bool updatePreviews = (m_iconSizeChangedDuringPausing && m_previewShown) || m_previewChangedDuringPausing; const bool resolveAll = updatePreviews || m_rolesChangedDuringPausing; if (resolveAll) { m_finishedItems.clear(); @@ -263,7 +257,7 @@ void KFileItemModelRolesUpdater::setPaused(bool paused) } } -void KFileItemModelRolesUpdater::setRoles(const QSet& roles) +void KFileItemModelRolesUpdater::setRoles(const QSet &roles) { if (m_roles != roles) { m_roles = roles; @@ -273,11 +267,11 @@ void KFileItemModelRolesUpdater::setRoles(const QSet& roles) // with the help of Baloo. If this is the case, a (quite expensive) // resolving will be done in KFileItemModelRolesUpdater::rolesData() and // the role gets watched for changes. - const KBalooRolesProvider& rolesProvider = KBalooRolesProvider::instance(); + const KBalooRolesProvider &rolesProvider = KBalooRolesProvider::instance(); bool hasBalooRole = false; QSetIterator it(roles); while (it.hasNext()) { - const QByteArray& role = it.next(); + const QByteArray &role = it.next(); if (rolesProvider.roles().contains(role)) { hasBalooRole = true; break; @@ -286,8 +280,7 @@ void KFileItemModelRolesUpdater::setRoles(const QSet& roles) if (hasBalooRole && m_balooConfig.fileIndexingEnabled() && !m_balooFileMonitor) { m_balooFileMonitor = new Baloo::FileMonitor(this); - connect(m_balooFileMonitor, &Baloo::FileMonitor::fileMetaDataChanged, - this, &KFileItemModelRolesUpdater::applyChangedBalooRoles); + connect(m_balooFileMonitor, &Baloo::FileMonitor::fileMetaDataChanged, this, &KFileItemModelRolesUpdater::applyChangedBalooRoles); } else if (!hasBalooRole && m_balooFileMonitor) { delete m_balooFileMonitor; m_balooFileMonitor = nullptr; @@ -337,7 +330,7 @@ bool KFileItemModelRolesUpdater::scanDirectories() const return m_scanDirectories; } -void KFileItemModelRolesUpdater::setHoverSequenceState(const QUrl& itemUrl, int seqIdx) +void KFileItemModelRolesUpdater::setHoverSequenceState(const QUrl &itemUrl, int seqIdx) { const KFileItem item = m_model->fileItem(itemUrl); @@ -357,7 +350,7 @@ void KFileItemModelRolesUpdater::setHoverSequenceState(const QUrl& itemUrl, int loadNextHoverSequencePreview(); } -void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRanges) +void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList &itemRanges) { QElapsedTimer timer; timer.start(); @@ -365,7 +358,7 @@ void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRan // Determine the sort role synchronously for as many items as possible. if (m_resolvableRoles.contains(m_model->sortRole())) { int insertedCount = 0; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { const int lastIndex = insertedCount + range.index + range.count - 1; for (int i = insertedCount + range.index; i <= lastIndex; ++i) { if (timer.elapsed() < MaxBlockTimeout) { @@ -392,7 +385,7 @@ void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRan startUpdating(); } -void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRanges) +void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList &itemRanges) { Q_UNUSED(itemRanges) @@ -406,7 +399,7 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang } else { QStringList newFileList; const QStringList oldFileList = m_balooFileMonitor->files(); - for (const QString& file : oldFileList) { + for (const QString &file : oldFileList) { if (m_model->index(QUrl::fromLocalFile(file)) >= 0) { newFileList.append(file); } @@ -442,7 +435,7 @@ void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRang } // Removed items won't have hover previews loaded anymore. - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { int index = itemRange.index; for (int count = itemRange.count; count > 0; --count) { const KFileItem item = m_model->fileItem(index); @@ -465,8 +458,7 @@ void KFileItemModelRolesUpdater::slotItemsMoved(KItemRange itemRange, const QLis startUpdating(); } -void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRanges, - const QSet& roles) +void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList &itemRanges, const QSet &roles) { Q_UNUSED(roles) @@ -475,9 +467,9 @@ void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRang // to prevent expensive repeated updates if files are updated frequently. const bool itemsChangedRecently = m_recentlyChangedItemsTimer->isActive(); - QSet& targetSet = itemsChangedRecently ? m_recentlyChangedItems : m_changedItems; + QSet &targetSet = itemsChangedRecently ? m_recentlyChangedItems : m_changedItems; - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { int index = itemRange.index; for (int count = itemRange.count; count > 0; --count) { const KFileItem item = m_model->fileItem(index); @@ -493,8 +485,7 @@ void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRang } } -void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current, - const QByteArray& previous) +void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -531,7 +522,7 @@ void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current, } } -void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPixmap& pixmap) +void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem &item, const QPixmap &pixmap) { if (m_state != PreviewJobRunning) { return; @@ -555,7 +546,7 @@ void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPi // assumes that an overlay will be drawn and has some additional // setup time. if (!scaledPixmap.isNull()) { - for (const QString& overlay : overlays) { + for (const QString &overlay : overlays) { if (!overlay.isEmpty()) { // There is at least one overlay, draw all overlays above m_pixmap // and cancel the check @@ -567,16 +558,14 @@ void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPi data.insert("iconPixmap", scaledPixmap); - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); m_model->setData(index, data); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); m_finishedItems.insert(item); } -void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item) +void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem &item) { if (m_state != PreviewJobRunning) { return; @@ -589,11 +578,9 @@ void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item) QHash data; data.insert("iconPixmap", QPixmap()); - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); m_model->setData(index, data); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); applyResolvedRoles(index, ResolveAll); m_finishedItems.insert(item); @@ -619,7 +606,7 @@ void KFileItemModelRolesUpdater::slotPreviewJobFinished() } } -void KFileItemModelRolesUpdater::slotHoverSequenceGotPreview(const KFileItem& item, const QPixmap& pixmap) +void KFileItemModelRolesUpdater::slotHoverSequenceGotPreview(const KFileItem &item, const QPixmap &pixmap) { const int index = m_model->index(item); if (index < 0) { @@ -653,8 +640,7 @@ void KFileItemModelRolesUpdater::slotHoverSequenceGotPreview(const KFileItem& it m_model->setData(index, data); - const auto loadedIt = std::find(m_hoverSequenceLoadedItems.begin(), - m_hoverSequenceLoadedItems.end(), item); + const auto loadedIt = std::find(m_hoverSequenceLoadedItems.begin(), m_hoverSequenceLoadedItems.end(), item); if (loadedIt == m_hoverSequenceLoadedItems.end()) { m_hoverSequenceLoadedItems.push_back(item); trimHoverSequenceLoadedItems(); @@ -664,7 +650,7 @@ void KFileItemModelRolesUpdater::slotHoverSequenceGotPreview(const KFileItem& it m_hoverSequenceNumSuccessiveFailures = 0; } -void KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed(const KFileItem& item) +void KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed(const KFileItem &item) { const int index = m_model->index(item); if (index < 0) { @@ -676,11 +662,8 @@ void KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed(const KFileItem& QHash data = m_model->data(index); QVector pixmaps = data["hoverSequencePixmaps"].value>(); - qCDebug(DolphinDebug).nospace() - << "Failed to generate hover sequence preview #" << pixmaps.size() - << " for file " << item.url().toString() - << " (attempt " << (m_hoverSequenceNumSuccessiveFailures+1) - << "/" << (numRetries+1) << ")"; + qCDebug(DolphinDebug).nospace() << "Failed to generate hover sequence preview #" << pixmaps.size() << " for file " << item.url().toString() << " (attempt " + << (m_hoverSequenceNumSuccessiveFailures + 1) << "/" << (numRetries + 1) << ")"; if (m_hoverSequenceNumSuccessiveFailures >= numRetries) { // Give up and simply duplicate the previous sequence image (if any) @@ -755,11 +738,9 @@ void KFileItemModelRolesUpdater::resolveNextSortRole() m_state = Idle; // Prevent that we try to update the items twice. - disconnect(m_model, &KFileItemModel::itemsMoved, - this, &KFileItemModelRolesUpdater::slotItemsMoved); + disconnect(m_model, &KFileItemModel::itemsMoved, this, &KFileItemModelRolesUpdater::slotItemsMoved); applySortProgressToModel(); - connect(m_model, &KFileItemModel::itemsMoved, - this, &KFileItemModelRolesUpdater::slotItemsMoved); + connect(m_model, &KFileItemModel::itemsMoved, this, &KFileItemModelRolesUpdater::slotItemsMoved); startUpdating(); } } @@ -796,18 +777,13 @@ void KFileItemModelRolesUpdater::resolveNextPendingRoles() data.insert("iconPixmap", QPixmap()); data.insert("hoverSequencePixmaps", QVariant::fromValue(QVector())); - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); for (int index = 0; index <= m_model->count(); ++index) { - if (m_model->data(index).contains("iconPixmap") || - m_model->data(index).contains("hoverSequencePixmaps")) - { + if (m_model->data(index).contains("iconPixmap") || m_model->data(index).contains("hoverSequencePixmaps")) { m_model->setData(index, data); } } - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); - + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); } m_clearPreviews = false; } @@ -825,7 +801,7 @@ void KFileItemModelRolesUpdater::resolveRecentlyChangedItems() updateChangedItems(); } -void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString& file) +void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString &file) { #if HAVE_BALOO const KFileItem item = m_model->fileItem(QUrl::fromLocalFile(file)); @@ -847,11 +823,11 @@ void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem & Baloo::File file(item.localPath()); file.load(); - const KBalooRolesProvider& rolesProvider = KBalooRolesProvider::instance(); + const KBalooRolesProvider &rolesProvider = KBalooRolesProvider::instance(); QHash data; const auto roles = rolesProvider.roles(); - for (const QByteArray& role : roles) { + for (const QByteArray &role : roles) { // Overwrite all the role values with an empty QVariant, because the roles // provider doesn't overwrite it when the property value list is empty. // See bug 322348 @@ -864,12 +840,10 @@ void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem & data.insert(it.key(), it.value()); } - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); const int index = m_model->index(item); m_model->setData(index, data); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); #else #ifndef Q_CC_MSVC Q_UNUSED(item) @@ -877,7 +851,7 @@ void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem & #endif } -void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString& path, int count, long size) +void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString &path, int count, long size) { const bool getSizeRole = m_roles.contains("size"); const bool getIsExpandableRole = m_roles.contains("isExpandable"); @@ -895,11 +869,9 @@ void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QStrin data.insert("isExpandable", count > 0); } - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); m_model->setData(index, data); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); } } } @@ -995,8 +967,7 @@ void KFileItemModelRolesUpdater::startPreviewJob() // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must // do a downscaling anyhow because of the frame, so in this case only the provided // cache sizes are requested. - const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128) - ? QSize(256, 256) : QSize(128, 128); + const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128) ? QSize(256, 256) : QSize(128, 128); // KIO::filePreview() will request the MIME-type of all passed items, which (in the // worst case) might block the application for several seconds. To prevent such @@ -1026,38 +997,32 @@ void KFileItemModelRolesUpdater::startPreviewJob() } while (!m_pendingPreviewItems.isEmpty() && timer.elapsed() < MaxBlockTimeout); } - KIO::PreviewJob* job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins); + KIO::PreviewJob *job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins); job->setIgnoreMaximumSize(itemSubSet.first().isLocalFile() && !itemSubSet.first().isSlow() && m_localFileSizePreviewLimit <= 0); if (job->uiDelegate()) { KJobWidgets::setWindow(job, qApp->activeWindow()); } - connect(job, &KIO::PreviewJob::gotPreview, - this, &KFileItemModelRolesUpdater::slotGotPreview); - connect(job, &KIO::PreviewJob::failed, - this, &KFileItemModelRolesUpdater::slotPreviewFailed); - connect(job, &KIO::PreviewJob::finished, - this, &KFileItemModelRolesUpdater::slotPreviewJobFinished); + connect(job, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotGotPreview); + connect(job, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotPreviewFailed); + connect(job, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished); m_previewJob = job; } -QPixmap KFileItemModelRolesUpdater::transformPreviewPixmap(const QPixmap& pixmap) +QPixmap KFileItemModelRolesUpdater::transformPreviewPixmap(const QPixmap &pixmap) { QPixmap scaledPixmap = pixmap; - if (!pixmap.hasAlpha() && !pixmap.isNull() - && m_iconSize.width() > KIconLoader::SizeSmallMedium - && m_iconSize.height() > KIconLoader::SizeSmallMedium) { + if (!pixmap.hasAlpha() && !pixmap.isNull() && m_iconSize.width() > KIconLoader::SizeSmallMedium && m_iconSize.height() > KIconLoader::SizeSmallMedium) { if (m_enlargeSmallPreviews) { KPixmapModifier::applyFrame(scaledPixmap, m_iconSize); } else { // Assure that small previews don't get enlarged. Instead they // should be shown centered within the frame. const QSize contentSize = KPixmapModifier::sizeInsideFrame(m_iconSize); - const bool enlargingRequired = scaledPixmap.width() < contentSize.width() && - scaledPixmap.height() < contentSize.height(); + const bool enlargingRequired = scaledPixmap.width() < contentSize.width() && scaledPixmap.height() < contentSize.height(); if (enlargingRequired) { QSize frameSize = scaledPixmap.size() / scaledPixmap.devicePixelRatio(); frameSize.scale(m_iconSize, Qt::KeepAspectRatio); @@ -1068,7 +1033,7 @@ QPixmap KFileItemModelRolesUpdater::transformPreviewPixmap(const QPixmap& pixmap KPixmapModifier::applyFrame(largeFrame, frameSize); QPainter painter(&largeFrame); - painter.drawPixmap((largeFrame.width() - scaledPixmap.width() / scaledPixmap.devicePixelRatio()) / 2, + painter.drawPixmap((largeFrame.width() - scaledPixmap.width() / scaledPixmap.devicePixelRatio()) / 2, (largeFrame.height() - scaledPixmap.height() / scaledPixmap.devicePixelRatio()) / 2, scaledPixmap); scaledPixmap = largeFrame; @@ -1098,7 +1063,7 @@ void KFileItemModelRolesUpdater::loadNextHoverSequencePreview() } // We generate the next few sequence indices in advance (buffering) - const int maxSeqIdx = m_hoverSequenceIndex+5; + const int maxSeqIdx = m_hoverSequenceIndex + 5; QHash data = m_model->data(index); @@ -1131,10 +1096,9 @@ void KFileItemModelRolesUpdater::loadNextHoverSequencePreview() // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must // do a downscaling anyhow because of the frame, so in this case only the provided // cache sizes are requested. - const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128) - ? QSize(256, 256) : QSize(128, 128); + const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128) ? QSize(256, 256) : QSize(128, 128); - KIO::PreviewJob* job = new KIO::PreviewJob({m_hoverSequenceItem}, cacheSize, &m_enabledPlugins); + KIO::PreviewJob *job = new KIO::PreviewJob({m_hoverSequenceItem}, cacheSize, &m_enabledPlugins); job->setSequenceIndex(loadSeqIdx); job->setIgnoreMaximumSize(m_hoverSequenceItem.isLocalFile() && !m_hoverSequenceItem.isSlow() && m_localFileSizePreviewLimit <= 0); @@ -1142,12 +1106,9 @@ void KFileItemModelRolesUpdater::loadNextHoverSequencePreview() KJobWidgets::setWindow(job, qApp->activeWindow()); } - connect(job, &KIO::PreviewJob::gotPreview, - this, &KFileItemModelRolesUpdater::slotHoverSequenceGotPreview); - connect(job, &KIO::PreviewJob::failed, - this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed); - connect(job, &KIO::PreviewJob::finished, - this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished); + connect(job, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotHoverSequenceGotPreview); + connect(job, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed); + connect(job, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished); m_hoverSequencePreviewJob = job; } @@ -1155,12 +1116,9 @@ void KFileItemModelRolesUpdater::loadNextHoverSequencePreview() void KFileItemModelRolesUpdater::killHoverSequencePreviewJob() { if (m_hoverSequencePreviewJob) { - disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::gotPreview, - this, &KFileItemModelRolesUpdater::slotHoverSequenceGotPreview); - disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::failed, - this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed); - disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::finished, - this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished); + disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotHoverSequenceGotPreview); + disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed); + disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished); m_hoverSequencePreviewJob->kill(); m_hoverSequencePreviewJob = nullptr; } @@ -1199,7 +1157,7 @@ void KFileItemModelRolesUpdater::updateChangedItems() auto changedItemsIt = m_changedItems.begin(); while (changedItemsIt != m_changedItems.end()) { - const auto& item = *changedItemsIt; + const auto &item = *changedItemsIt; const int index = m_model->index(item); if (index < 0) { @@ -1261,11 +1219,9 @@ void KFileItemModelRolesUpdater::applySortRole(int index) data = rolesData(item); } - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); m_model->setData(index, data); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); } void KFileItemModelRolesUpdater::applySortProgressToModel() @@ -1308,18 +1264,16 @@ bool KFileItemModelRolesUpdater::applyResolvedRoles(int index, ResolveHint hint) data.insert("hoverSequencePixmaps", QVariant::fromValue(QVector())); } - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); m_model->setData(index, data); - connect(m_model, &KFileItemModel::itemsChanged, - this, &KFileItemModelRolesUpdater::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged); return true; } return false; } -QHash KFileItemModelRolesUpdater::rolesData(const KFileItem& item) +QHash KFileItemModelRolesUpdater::rolesData(const KFileItem &item) { QHash data; @@ -1364,14 +1318,14 @@ QHash KFileItemModelRolesUpdater::rolesData(const KFileIte return data; } -void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl& url, const QStringList &) +void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl &url, const QStringList &) { const KFileItem item = m_model->fileItem(url); if (item.isNull()) { return; } const int index = m_model->index(item); - QHash data = m_model->data(index); + QHash data = m_model->data(index); QStringList overlays = item.overlays(); for (KOverlayIconPlugin *it : qAsConst(m_overlayIconsPlugin)) { overlays.append(it->getOverlays(url)); @@ -1393,12 +1347,9 @@ void KFileItemModelRolesUpdater::updateAllPreviews() void KFileItemModelRolesUpdater::killPreviewJob() { if (m_previewJob) { - disconnect(m_previewJob, &KIO::PreviewJob::gotPreview, - this, &KFileItemModelRolesUpdater::slotGotPreview); - disconnect(m_previewJob, &KIO::PreviewJob::failed, - this, &KFileItemModelRolesUpdater::slotPreviewFailed); - disconnect(m_previewJob, &KIO::PreviewJob::finished, - this, &KFileItemModelRolesUpdater::slotPreviewJobFinished); + disconnect(m_previewJob, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotGotPreview); + disconnect(m_previewJob, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotPreviewFailed); + disconnect(m_previewJob, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished); m_previewJob->kill(); m_previewJob = nullptr; m_pendingPreviewItems.clear(); @@ -1410,9 +1361,7 @@ QList KFileItemModelRolesUpdater::indexesToResolve() const const int count = m_model->count(); QList result; - result.reserve(qMin(count, (m_lastVisibleIndex - m_firstVisibleIndex + 1) + - ResolveAllItemsLimit + - (2 * m_maximumVisibleItems))); + result.reserve(qMin(count, (m_lastVisibleIndex - m_firstVisibleIndex + 1) + ResolveAllItemsLimit + (2 * m_maximumVisibleItems))); // Add visible items. // Resolve files first, their previews are quicker. @@ -1492,4 +1441,3 @@ void KFileItemModelRolesUpdater::trimHoverSequenceLoadedItems() } } } - diff --git a/src/kitemviews/kfileitemmodelrolesupdater.h b/src/kitemviews/kfileitemmodelrolesupdater.h index b0177b9f8e..90f29c5c0a 100644 --- a/src/kitemviews/kfileitemmodelrolesupdater.h +++ b/src/kitemviews/kfileitemmodelrolesupdater.h @@ -12,8 +12,8 @@ #include -#include #include "config-dolphin.h" +#include #include #include @@ -26,16 +26,17 @@ class QPixmap; class QTimer; class KOverlayIconPlugin; -namespace KIO { - class PreviewJob; +namespace KIO +{ +class PreviewJob; } #if HAVE_BALOO - namespace Baloo - { - class FileMonitor; - } - #include +namespace Baloo +{ +class FileMonitor; +} +#include #endif /** @@ -82,10 +83,10 @@ class DOLPHIN_EXPORT KFileItemModelRolesUpdater : public QObject Q_OBJECT public: - explicit KFileItemModelRolesUpdater(KFileItemModel* model, QObject* parent = nullptr); + explicit KFileItemModelRolesUpdater(KFileItemModel *model, QObject *parent = nullptr); ~KFileItemModelRolesUpdater() override; - void setIconSize(const QSize& size); + void setIconSize(const QSize &size); QSize iconSize() const; /** @@ -123,7 +124,7 @@ public: /** * Sets the roles that should be resolved asynchronously. */ - void setRoles(const QSet& roles); + void setRoles(const QSet &roles); QSet roles() const; /** @@ -135,7 +136,7 @@ public: * * @see enabledPlugins */ - void setEnabledPlugins(const QStringList& list); + void setEnabledPlugins(const QStringList &list); /** * Returns the list of enabled thumbnail plugins. @@ -172,16 +173,14 @@ public: * this method will be called repeatedly with increasing values * for this parameter. */ - void setHoverSequenceState(const QUrl& itemUrl, int seqIdx); + void setHoverSequenceState(const QUrl &itemUrl, int seqIdx); private Q_SLOTS: - void slotItemsInserted(const KItemRangeList& itemRanges); - void slotItemsRemoved(const KItemRangeList& itemRanges); + void slotItemsInserted(const KItemRangeList &itemRanges); + void slotItemsRemoved(const KItemRangeList &itemRanges); void slotItemsMoved(KItemRange itemRange, const QList &movedToIndexes); - void slotItemsChanged(const KItemRangeList& itemRanges, - const QSet& roles); - void slotSortRoleChanged(const QByteArray& current, - const QByteArray& previous); + void slotItemsChanged(const KItemRangeList &itemRanges, const QSet &roles); + void slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous); /** * Is invoked after a preview has been received successfully. @@ -190,7 +189,7 @@ private Q_SLOTS: * * @see startPreviewJob() */ - void slotGotPreview(const KFileItem& item, const QPixmap& pixmap); + void slotGotPreview(const KFileItem &item, const QPixmap &pixmap); /** * Is invoked after generating a preview has failed. @@ -199,7 +198,7 @@ private Q_SLOTS: * * @see startPreviewJob() */ - void slotPreviewFailed(const KFileItem& item); + void slotPreviewFailed(const KFileItem &item); /** * Is invoked when the preview job has been finished. Starts a new preview @@ -215,12 +214,12 @@ private Q_SLOTS: /** * Is invoked after a hover sequence preview has been received successfully. */ - void slotHoverSequenceGotPreview(const KFileItem& item, const QPixmap& pixmap); + void slotHoverSequenceGotPreview(const KFileItem &item, const QPixmap &pixmap); /** * Is invoked after generating a hover sequence preview has failed. */ - void slotHoverSequencePreviewFailed(const KFileItem& item); + void slotHoverSequencePreviewFailed(const KFileItem &item); /** * Is invoked when a hover sequence preview job is finished. May start another @@ -235,7 +234,7 @@ private Q_SLOTS: /** * Is invoked when one of the KOverlayIconPlugin emit the signal that an overlay has changed */ - void slotOverlaysChanged(const QUrl& url, const QStringList&); + void slotOverlaysChanged(const QUrl &url, const QStringList &); /** * Resolves the sort role of the next item in m_pendingSortRole, applies it @@ -258,10 +257,10 @@ private Q_SLOTS: */ void resolveRecentlyChangedItems(); - void applyChangedBalooRoles(const QString& file); - void applyChangedBalooRolesForItem(const KFileItem& file); + void applyChangedBalooRoles(const QString &file); + void applyChangedBalooRolesForItem(const KFileItem &file); - void slotDirectoryContentsCountReceived(const QString& path, int count, long size); + void slotDirectoryContentsCountReceived(const QString &path, int count, long size); private: /** @@ -293,7 +292,7 @@ private: * @param pixmap A raw preview image from a PreviewJob. * @return The scaled and decorated preview image. */ - QPixmap transformPreviewPixmap(const QPixmap& pixmap); + QPixmap transformPreviewPixmap(const QPixmap &pixmap); /** * Starts a PreviewJob for loading the next hover sequence image. @@ -318,12 +317,9 @@ private: void applySortProgressToModel(); - enum ResolveHint { - ResolveFast, - ResolveAll - }; + enum ResolveHint { ResolveFast, ResolveAll }; bool applyResolvedRoles(int index, ResolveHint hint); - QHash rolesData(const KFileItem& item); + QHash rolesData(const KFileItem &item); /** * Must be invoked if a property has been changed that affects @@ -338,13 +334,7 @@ private: void trimHoverSequenceLoadedItems(); private: - enum State { - Idle, - Paused, - ResolvingSortRole, - ResolvingAllRoles, - PreviewJobRunning - }; + enum State { Idle, Paused, ResolvingSortRole, ResolvingAllRoles, PreviewJobRunning }; State m_state; @@ -369,7 +359,7 @@ private: // previews and other expensive roles are determined again. QSet m_finishedItems; - KFileItemModel* m_model; + KFileItemModel *m_model; QSize m_iconSize; int m_firstVisibleIndex; int m_lastVisibleIndex; @@ -391,13 +381,13 @@ private: // A new preview job will be started from them once the first one finishes. KFileItemList m_pendingPreviewItems; - KIO::PreviewJob* m_previewJob; + KIO::PreviewJob *m_previewJob; // Info about the item that the user currently hovers, and the current sequence // index for thumb generation. KFileItem m_hoverSequenceItem; int m_hoverSequenceIndex; - KIO::PreviewJob* m_hoverSequencePreviewJob; + KIO::PreviewJob *m_hoverSequencePreviewJob; int m_hoverSequenceNumSuccessiveFailures; std::list m_hoverSequenceLoadedItems; @@ -406,18 +396,18 @@ private: // a high CPU-load by generating e.g. previews for each notification, the update // will be postponed until no file change has been done within a longer period // of time. - QTimer* m_recentlyChangedItemsTimer; + QTimer *m_recentlyChangedItemsTimer; QSet m_recentlyChangedItems; // Items which have not been changed repeatedly recently. QSet m_changedItems; - KDirectoryContentsCounter* m_directoryContentsCounter; + KDirectoryContentsCounter *m_directoryContentsCounter; - QList m_overlayIconsPlugin; + QList m_overlayIconsPlugin; #if HAVE_BALOO - Baloo::FileMonitor* m_balooFileMonitor; + Baloo::FileMonitor *m_balooFileMonitor; Baloo::IndexerConfig m_balooConfig; #endif }; diff --git a/src/kitemviews/kitemlistcontainer.cpp b/src/kitemviews/kitemlistcontainer.cpp index 10b9f1415c..1d62c96204 100644 --- a/src/kitemviews/kitemlistcontainer.cpp +++ b/src/kitemviews/kitemlistcontainer.cpp @@ -30,13 +30,14 @@ class KItemListContainerViewport : public QGraphicsView Q_OBJECT public: - KItemListContainerViewport(QGraphicsScene* scene, QWidget* parent); + KItemListContainerViewport(QGraphicsScene *scene, QWidget *parent); + protected: - void wheelEvent(QWheelEvent* event) override; + void wheelEvent(QWheelEvent *event) override; }; -KItemListContainerViewport::KItemListContainerViewport(QGraphicsScene* scene, QWidget* parent) : - QGraphicsView(scene, parent) +KItemListContainerViewport::KItemListContainerViewport(QGraphicsScene *scene, QWidget *parent) + : QGraphicsView(scene, parent) { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -44,24 +45,24 @@ KItemListContainerViewport::KItemListContainerViewport(QGraphicsScene* scene, QW setFrameShape(QFrame::NoFrame); } -void KItemListContainerViewport::wheelEvent(QWheelEvent* event) +void KItemListContainerViewport::wheelEvent(QWheelEvent *event) { // Assure that the wheel-event gets forwarded to the parent // and not handled at all by QGraphicsView. event->ignore(); } -KItemListContainer::KItemListContainer(KItemListController* controller, QWidget* parent) : - QAbstractScrollArea(parent), - m_controller(controller), - m_horizontalSmoothScroller(nullptr), - m_verticalSmoothScroller(nullptr), - m_scroller(nullptr) +KItemListContainer::KItemListContainer(KItemListController *controller, QWidget *parent) + : QAbstractScrollArea(parent) + , m_controller(controller) + , m_horizontalSmoothScroller(nullptr) + , m_verticalSmoothScroller(nullptr) + , m_scroller(nullptr) { Q_ASSERT(controller); controller->setParent(this); - QGraphicsView* graphicsView = new KItemListContainerViewport(new QGraphicsScene(this), this); + QGraphicsView *graphicsView = new KItemListContainerViewport(new QGraphicsScene(this), this); setViewport(graphicsView); m_horizontalSmoothScroller = new KItemListSmoothScroller(horizontalScrollBar(), this); @@ -74,17 +75,13 @@ KItemListContainer::KItemListContainer(KItemListController* controller, QWidget* slotViewChanged(controller->view(), nullptr); } - connect(controller, &KItemListController::modelChanged, - this, &KItemListContainer::slotModelChanged); - connect(controller, &KItemListController::viewChanged, - this, &KItemListContainer::slotViewChanged); + connect(controller, &KItemListController::modelChanged, this, &KItemListContainer::slotModelChanged); + connect(controller, &KItemListController::viewChanged, this, &KItemListContainer::slotViewChanged); m_scroller = QScroller::scroller(viewport()); m_scroller->grabGesture(viewport()); - connect(controller, &KItemListController::scrollerStop, - this, &KItemListContainer::stopScroller); - connect(m_scroller, &QScroller::stateChanged, - controller, &KItemListController::slotStateChanged); + connect(controller, &KItemListController::scrollerStop, this, &KItemListContainer::stopScroller); + connect(m_scroller, &QScroller::stateChanged, controller, &KItemListController::slotStateChanged); } KItemListContainer::~KItemListContainer() @@ -95,14 +92,14 @@ KItemListContainer::~KItemListContainer() m_controller = nullptr; } -KItemListController* KItemListContainer::controller() const +KItemListController *KItemListContainer::controller() const { return m_controller; } void KItemListContainer::setEnabledFrame(bool enable) { - QGraphicsView* graphicsView = qobject_cast(viewport()); + QGraphicsView *graphicsView = qobject_cast(viewport()); if (enable) { setFrameShape(QFrame::StyledPanel); graphicsView->setPalette(palette()); @@ -113,7 +110,7 @@ void KItemListContainer::setEnabledFrame(bool enable) // to the text color, so that enough contrast is given for all color // schemes QPalette p = graphicsView->palette(); - p.setColor(QPalette::Active, QPalette::Text, p.color(QPalette::Active, QPalette::WindowText)); + p.setColor(QPalette::Active, QPalette::Text, p.color(QPalette::Active, QPalette::WindowText)); p.setColor(QPalette::Inactive, QPalette::Text, p.color(QPalette::Inactive, QPalette::WindowText)); p.setColor(QPalette::Disabled, QPalette::Text, p.color(QPalette::Disabled, QPalette::WindowText)); graphicsView->setPalette(p); @@ -123,11 +120,11 @@ void KItemListContainer::setEnabledFrame(bool enable) bool KItemListContainer::enabledFrame() const { - const QGraphicsView* graphicsView = qobject_cast(viewport()); + const QGraphicsView *graphicsView = qobject_cast(viewport()); return graphicsView->autoFillBackground(); } -void KItemListContainer::keyPressEvent(QKeyEvent* event) +void KItemListContainer::keyPressEvent(QKeyEvent *event) { // TODO: We should find a better way to handle the key press events in the view. // The reasons why we need this hack are: @@ -135,19 +132,19 @@ void KItemListContainer::keyPressEvent(QKeyEvent* event) // 2. By default, the KItemListView does not have the keyboard focus in the QGraphicsScene, so // simply sending the event to the QGraphicsView which is the KItemListContainer's viewport // does not work. - KItemListView* view = m_controller->view(); + KItemListView *view = m_controller->view(); if (view) { QApplication::sendEvent(view, event); } } -void KItemListContainer::showEvent(QShowEvent* event) +void KItemListContainer::showEvent(QShowEvent *event) { QAbstractScrollArea::showEvent(event); updateGeometries(); } -void KItemListContainer::resizeEvent(QResizeEvent* event) +void KItemListContainer::resizeEvent(QResizeEvent *event) { QAbstractScrollArea::resizeEvent(event); updateGeometries(); @@ -159,23 +156,21 @@ void KItemListContainer::scrollContentsBy(int dx, int dy) m_verticalSmoothScroller->scrollContentsBy(dy); } -void KItemListContainer::wheelEvent(QWheelEvent* event) +void KItemListContainer::wheelEvent(QWheelEvent *event) { if (event->modifiers().testFlag(Qt::ControlModifier)) { event->ignore(); return; } - KItemListView* view = m_controller->view(); + KItemListView *view = m_controller->view(); if (!view) { event->ignore(); return; } - const bool scrollHorizontally = (qAbs(event->angleDelta().y()) < qAbs(event->angleDelta().x())) || - (!verticalScrollBar()->isVisible()); - KItemListSmoothScroller* smoothScroller = scrollHorizontally ? - m_horizontalSmoothScroller : m_verticalSmoothScroller; + const bool scrollHorizontally = (qAbs(event->angleDelta().y()) < qAbs(event->angleDelta().x())) || (!verticalScrollBar()->isVisible()); + KItemListSmoothScroller *smoothScroller = scrollHorizontally ? m_horizontalSmoothScroller : m_verticalSmoothScroller; smoothScroller->handleWheelEvent(event); } @@ -186,27 +181,22 @@ void KItemListContainer::slotScrollOrientationChanged(Qt::Orientation current, Q updateSmoothScrollers(current); } -void KItemListContainer::slotModelChanged(KItemModelBase* current, KItemModelBase* previous) +void KItemListContainer::slotModelChanged(KItemModelBase *current, KItemModelBase *previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListContainer::slotViewChanged(KItemListView* current, KItemListView* previous) +void KItemListContainer::slotViewChanged(KItemListView *current, KItemListView *previous) { - QGraphicsScene* scene = static_cast(viewport())->scene(); + QGraphicsScene *scene = static_cast(viewport())->scene(); if (previous) { scene->removeItem(previous); - disconnect(previous, &KItemListView::scrollOrientationChanged, - this, &KItemListContainer::slotScrollOrientationChanged); - disconnect(previous, &KItemListView::scrollOffsetChanged, - this, &KItemListContainer::updateScrollOffsetScrollBar); - disconnect(previous, &KItemListView::maximumScrollOffsetChanged, - this, &KItemListContainer::updateScrollOffsetScrollBar); - disconnect(previous, &KItemListView::itemOffsetChanged, - this, &KItemListContainer::updateItemOffsetScrollBar); - disconnect(previous, &KItemListView::maximumItemOffsetChanged, - this, &KItemListContainer::updateItemOffsetScrollBar); + disconnect(previous, &KItemListView::scrollOrientationChanged, this, &KItemListContainer::slotScrollOrientationChanged); + disconnect(previous, &KItemListView::scrollOffsetChanged, this, &KItemListContainer::updateScrollOffsetScrollBar); + disconnect(previous, &KItemListView::maximumScrollOffsetChanged, this, &KItemListContainer::updateScrollOffsetScrollBar); + disconnect(previous, &KItemListView::itemOffsetChanged, this, &KItemListContainer::updateItemOffsetScrollBar); + disconnect(previous, &KItemListView::maximumItemOffsetChanged, this, &KItemListContainer::updateItemOffsetScrollBar); disconnect(previous, &KItemListView::scrollTo, this, &KItemListContainer::scrollTo); disconnect(m_horizontalSmoothScroller, &KItemListSmoothScroller::scrollingStopped, previous, &KItemListView::scrollingStopped); disconnect(m_verticalSmoothScroller, &KItemListSmoothScroller::scrollingStopped, previous, &KItemListView::scrollingStopped); @@ -215,16 +205,11 @@ void KItemListContainer::slotViewChanged(KItemListView* current, KItemListView* } if (current) { scene->addItem(current); - connect(current, &KItemListView::scrollOrientationChanged, - this, &KItemListContainer::slotScrollOrientationChanged); - connect(current, &KItemListView::scrollOffsetChanged, - this, &KItemListContainer::updateScrollOffsetScrollBar); - connect(current, &KItemListView::maximumScrollOffsetChanged, - this, &KItemListContainer::updateScrollOffsetScrollBar); - connect(current, &KItemListView::itemOffsetChanged, - this, &KItemListContainer::updateItemOffsetScrollBar); - connect(current, &KItemListView::maximumItemOffsetChanged, - this, &KItemListContainer::updateItemOffsetScrollBar); + connect(current, &KItemListView::scrollOrientationChanged, this, &KItemListContainer::slotScrollOrientationChanged); + connect(current, &KItemListView::scrollOffsetChanged, this, &KItemListContainer::updateScrollOffsetScrollBar); + connect(current, &KItemListView::maximumScrollOffsetChanged, this, &KItemListContainer::updateScrollOffsetScrollBar); + connect(current, &KItemListView::itemOffsetChanged, this, &KItemListContainer::updateItemOffsetScrollBar); + connect(current, &KItemListView::maximumItemOffsetChanged, this, &KItemListContainer::updateItemOffsetScrollBar); connect(current, &KItemListView::scrollTo, this, &KItemListContainer::scrollTo); connect(m_horizontalSmoothScroller, &KItemListSmoothScroller::scrollingStopped, current, &KItemListView::scrollingStopped); connect(m_verticalSmoothScroller, &KItemListSmoothScroller::scrollingStopped, current, &KItemListView::scrollingStopped); @@ -237,7 +222,7 @@ void KItemListContainer::slotViewChanged(KItemListView* current, KItemListView* void KItemListContainer::scrollTo(qreal offset) { - const KItemListView* view = m_controller->view(); + const KItemListView *view = m_controller->view(); if (view) { if (view->scrollOrientation() == Qt::Vertical) { m_verticalSmoothScroller->scrollTo(offset); @@ -249,13 +234,13 @@ void KItemListContainer::scrollTo(qreal offset) void KItemListContainer::updateScrollOffsetScrollBar() { - const KItemListView* view = m_controller->view(); + const KItemListView *view = m_controller->view(); if (!view) { return; } - KItemListSmoothScroller* smoothScroller = nullptr; - QScrollBar* scrollOffsetScrollBar = nullptr; + KItemListSmoothScroller *smoothScroller = nullptr; + QScrollBar *scrollOffsetScrollBar = nullptr; int singleStep = 0; int pageStep = 0; int maximum = 0; @@ -289,8 +274,7 @@ void KItemListContainer::updateScrollOffsetScrollBar() const int value = view->scrollOffset(); if (smoothScroller->requestScrollBarUpdate(maximum)) { - const bool updatePolicy = (scrollOffsetScrollBar->maximum() > 0 && maximum == 0) - || horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOn; + const bool updatePolicy = (scrollOffsetScrollBar->maximum() > 0 && maximum == 0) || horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOn; scrollOffsetScrollBar->setSingleStep(singleStep); scrollOffsetScrollBar->setPageStep(pageStep); @@ -307,13 +291,13 @@ void KItemListContainer::updateScrollOffsetScrollBar() void KItemListContainer::updateItemOffsetScrollBar() { - const KItemListView* view = m_controller->view(); + const KItemListView *view = m_controller->view(); if (!view) { return; } - KItemListSmoothScroller* smoothScroller = nullptr; - QScrollBar* itemOffsetScrollBar = nullptr; + KItemListSmoothScroller *smoothScroller = nullptr; + QScrollBar *itemOffsetScrollBar = nullptr; int singleStep = 0; int pageStep = 0; if (view->scrollOrientation() == Qt::Vertical) { @@ -356,23 +340,19 @@ void KItemListContainer::updateGeometries() scrollbarSpacing = style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &option, this); } - const int widthDec = verticalScrollBar()->isVisible() - ? extra + scrollbarSpacing + style()->pixelMetric(QStyle::PM_ScrollBarExtent, &option, this) - : extra; + const int widthDec = verticalScrollBar()->isVisible() ? extra + scrollbarSpacing + style()->pixelMetric(QStyle::PM_ScrollBarExtent, &option, this) : extra; - const int heightDec = horizontalScrollBar()->isVisible() - ? extra + scrollbarSpacing + style()->pixelMetric(QStyle::PM_ScrollBarExtent, &option, this) - : extra; + const int heightDec = + horizontalScrollBar()->isVisible() ? extra + scrollbarSpacing + style()->pixelMetric(QStyle::PM_ScrollBarExtent, &option, this) : extra; - const QRectF newGeometry(0, 0, rect.width() - widthDec, - rect.height() - heightDec); + const QRectF newGeometry(0, 0, rect.width() - widthDec, rect.height() - heightDec); if (m_controller->view()->geometry() != newGeometry) { m_controller->view()->setGeometry(newGeometry); // Get the real geometry of the view again since the scrollbars // visibilities and the view geometry may have changed in re-layout. - static_cast(viewport())->scene()->setSceneRect(m_controller->view()->geometry()); - static_cast(viewport())->viewport()->setGeometry(m_controller->view()->geometry().toRect()); + static_cast(viewport())->scene()->setSceneRect(m_controller->view()->geometry()); + static_cast(viewport())->viewport()->setGeometry(m_controller->view()->geometry().toRect()); updateScrollOffsetScrollBar(); updateItemOffsetScrollBar(); @@ -392,7 +372,7 @@ void KItemListContainer::updateSmoothScrollers(Qt::Orientation orientation) void KItemListContainer::updateScrollOffsetScrollBarPolicy() { - const KItemListView* view = m_controller->view(); + const KItemListView *view = m_controller->view(); Q_ASSERT(view); const bool vertical = (view->scrollOrientation() == Qt::Vertical); @@ -407,8 +387,7 @@ void KItemListContainer::updateScrollOffsetScrollBarPolicy() newViewSize.rheight() += scrollBarInc; } - const Qt::ScrollBarPolicy policy = view->scrollBarRequired(newViewSize) - ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAsNeeded; + const Qt::ScrollBarPolicy policy = view->scrollBarRequired(newViewSize) ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAsNeeded; if (vertical) { setVerticalScrollBarPolicy(policy); } else { diff --git a/src/kitemviews/kitemlistcontainer.h b/src/kitemviews/kitemlistcontainer.h index 9d96d2ce0c..6bb28469e9 100644 --- a/src/kitemviews/kitemlistcontainer.h +++ b/src/kitemviews/kitemlistcontainer.h @@ -37,24 +37,24 @@ public: * (the parent will be set to the KItemListContainer). * @param parent Optional parent widget. */ - explicit KItemListContainer(KItemListController* controller, QWidget* parent = nullptr); + explicit KItemListContainer(KItemListController *controller, QWidget *parent = nullptr); ~KItemListContainer() override; - KItemListController* controller() const; + KItemListController *controller() const; void setEnabledFrame(bool enable); bool enabledFrame() const; protected: - void keyPressEvent(QKeyEvent* event) override; - void showEvent(QShowEvent* event) override; - void resizeEvent(QResizeEvent* event) override; + void keyPressEvent(QKeyEvent *event) override; + void showEvent(QShowEvent *event) override; + void resizeEvent(QResizeEvent *event) override; void scrollContentsBy(int dx, int dy) override; - void wheelEvent(QWheelEvent* event) override; + void wheelEvent(QWheelEvent *event) override; private Q_SLOTS: void slotScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous); - void slotModelChanged(KItemModelBase* current, KItemModelBase* previous); - void slotViewChanged(KItemListView* current, KItemListView* previous); + void slotModelChanged(KItemModelBase *current, KItemModelBase *previous); + void slotViewChanged(KItemListView *current, KItemListView *previous); void scrollTo(qreal offset); void updateScrollOffsetScrollBar(); void updateItemOffsetScrollBar(); @@ -72,13 +72,11 @@ private: void updateScrollOffsetScrollBarPolicy(); private: - KItemListController* m_controller; + KItemListController *m_controller; - KItemListSmoothScroller* m_horizontalSmoothScroller; - KItemListSmoothScroller* m_verticalSmoothScroller; - QScroller* m_scroller; + KItemListSmoothScroller *m_horizontalSmoothScroller; + KItemListSmoothScroller *m_verticalSmoothScroller; + QScroller *m_scroller; }; #endif - - diff --git a/src/kitemviews/kitemlistcontroller.cpp b/src/kitemviews/kitemlistcontroller.cpp index 29a5bd87ad..54a856fb80 100644 --- a/src/kitemviews/kitemlistcontroller.cpp +++ b/src/kitemviews/kitemlistcontroller.cpp @@ -30,40 +30,37 @@ #include #include -KItemListController::KItemListController(KItemModelBase* model, KItemListView* view, QObject* parent) : - QObject(parent), - m_singleClickActivationEnforced(false), - m_selectionMode(false), - m_selectionTogglePressed(false), - m_clearSelectionIfItemsAreNotDragged(false), - m_isSwipeGesture(false), - m_dragActionOrRightClick(false), - m_scrollerIsScrolling(false), - m_pinchGestureInProgress(false), - m_mousePress(false), - m_isTouchEvent(false), - m_selectionBehavior(NoSelection), - m_autoActivationBehavior(ActivationAndExpansion), - m_mouseDoubleClickAction(ActivateItemOnly), - m_model(nullptr), - m_view(nullptr), - m_selectionManager(new KItemListSelectionManager(this)), - m_keyboardManager(new KItemListKeyboardSearchManager(this)), - m_pressedIndex(std::nullopt), - m_pressedMousePos(), - m_autoActivationTimer(nullptr), - m_swipeGesture(Qt::CustomGesture), - m_twoFingerTapGesture(Qt::CustomGesture), - m_oldSelection(), - m_keyboardAnchorIndex(-1), - m_keyboardAnchorPos(0) +KItemListController::KItemListController(KItemModelBase *model, KItemListView *view, QObject *parent) + : QObject(parent) + , m_singleClickActivationEnforced(false) + , m_selectionMode(false) + , m_selectionTogglePressed(false) + , m_clearSelectionIfItemsAreNotDragged(false) + , m_isSwipeGesture(false) + , m_dragActionOrRightClick(false) + , m_scrollerIsScrolling(false) + , m_pinchGestureInProgress(false) + , m_mousePress(false) + , m_isTouchEvent(false) + , m_selectionBehavior(NoSelection) + , m_autoActivationBehavior(ActivationAndExpansion) + , m_mouseDoubleClickAction(ActivateItemOnly) + , m_model(nullptr) + , m_view(nullptr) + , m_selectionManager(new KItemListSelectionManager(this)) + , m_keyboardManager(new KItemListKeyboardSearchManager(this)) + , m_pressedIndex(std::nullopt) + , m_pressedMousePos() + , m_autoActivationTimer(nullptr) + , m_swipeGesture(Qt::CustomGesture) + , m_twoFingerTapGesture(Qt::CustomGesture) + , m_oldSelection() + , m_keyboardAnchorIndex(-1) + , m_keyboardAnchorPos(0) { - connect(m_keyboardManager, &KItemListKeyboardSearchManager::changeCurrentItem, - this, &KItemListController::slotChangeCurrentItem); - connect(m_selectionManager, &KItemListSelectionManager::currentChanged, - m_keyboardManager, &KItemListKeyboardSearchManager::slotCurrentChanged); - connect(m_selectionManager, &KItemListSelectionManager::selectionChanged, - m_keyboardManager, &KItemListKeyboardSearchManager::slotSelectionChanged); + connect(m_keyboardManager, &KItemListKeyboardSearchManager::changeCurrentItem, this, &KItemListController::slotChangeCurrentItem); + connect(m_selectionManager, &KItemListSelectionManager::currentChanged, m_keyboardManager, &KItemListKeyboardSearchManager::slotCurrentChanged); + connect(m_selectionManager, &KItemListSelectionManager::selectionChanged, m_keyboardManager, &KItemListKeyboardSearchManager::slotSelectionChanged); m_autoActivationTimer = new QTimer(this); m_autoActivationTimer->setSingleShot(true); @@ -91,13 +88,13 @@ KItemListController::~KItemListController() Q_ASSERT(!m_model); } -void KItemListController::setModel(KItemModelBase* model) +void KItemListController::setModel(KItemModelBase *model) { if (m_model == model) { return; } - KItemModelBase* oldModel = m_model; + KItemModelBase *oldModel = m_model; if (oldModel) { oldModel->deleteLater(); } @@ -116,23 +113,23 @@ void KItemListController::setModel(KItemModelBase* model) Q_EMIT modelChanged(m_model, oldModel); } -KItemModelBase* KItemListController::model() const +KItemModelBase *KItemListController::model() const { return m_model; } -KItemListSelectionManager* KItemListController::selectionManager() const +KItemListSelectionManager *KItemListController::selectionManager() const { return m_selectionManager; } -void KItemListController::setView(KItemListView* view) +void KItemListController::setView(KItemListView *view) { if (m_view == view) { return; } - KItemListView* oldView = m_view; + KItemListView *oldView = m_view; if (oldView) { disconnect(oldView, &KItemListView::scrollOffsetChanged, this, &KItemListController::slotViewScrollOffsetChanged); oldView->deleteLater(); @@ -151,7 +148,7 @@ void KItemListController::setView(KItemListView* view) Q_EMIT viewChanged(m_view, oldView); } -KItemListView* KItemListController::view() const +KItemListView *KItemListController::view() const { return m_view; } @@ -189,7 +186,7 @@ KItemListController::MouseDoubleClickAction KItemListController::mouseDoubleClic int KItemListController::indexCloseToMousePressedPosition() const { - QHashIterator it(m_view->m_visibleGroups); + QHashIterator it(m_view->m_visibleGroups); while (it.hasNext()) { it.next(); KItemListGroupHeader *groupHeader = it.value(); @@ -231,7 +228,7 @@ bool KItemListController::selectionMode() const return m_selectionMode; } -bool KItemListController::keyPressEvent(QKeyEvent* event) +bool KItemListController::keyPressEvent(QKeyEvent *event) { int index = m_selectionManager->currentItem(); int key = event->key(); @@ -252,10 +249,8 @@ bool KItemListController::keyPressEvent(QKeyEvent* event) const bool shiftPressed = event->modifiers() & Qt::ShiftModifier; const bool controlPressed = event->modifiers() & Qt::ControlModifier; const bool shiftOrControlPressed = shiftPressed || controlPressed; - const bool navigationPressed = key == Qt::Key_Home || key == Qt::Key_End || - key == Qt::Key_PageUp || key == Qt::Key_PageDown || - key == Qt::Key_Up || key == Qt::Key_Down || - key == Qt::Key_Left || key == Qt::Key_Right; + const bool navigationPressed = key == Qt::Key_Home || key == Qt::Key_End || key == Qt::Key_PageUp || key == Qt::Key_PageDown || key == Qt::Key_Up + || key == Qt::Key_Down || key == Qt::Key_Left || key == Qt::Key_Right; const int itemCount = m_model->count(); @@ -263,11 +258,20 @@ bool KItemListController::keyPressEvent(QKeyEvent* event) // the arrow keys to simplify the event handling. if (m_view->scrollOrientation() == Qt::Horizontal) { switch (key) { - case Qt::Key_Up: key = Qt::Key_Left; break; - case Qt::Key_Down: key = Qt::Key_Right; break; - case Qt::Key_Left: key = Qt::Key_Up; break; - case Qt::Key_Right: key = Qt::Key_Down; break; - default: break; + case Qt::Key_Up: + key = Qt::Key_Left; + break; + case Qt::Key_Down: + key = Qt::Key_Right; + break; + case Qt::Key_Left: + key = Qt::Key_Up; + break; + case Qt::Key_Right: + key = Qt::Key_Down; + break; + default: + break; } } @@ -402,8 +406,7 @@ bool KItemListController::keyPressEvent(QKeyEvent* event) int index = -1; if (selectedItems.count() >= 2) { const int currentItemIndex = m_selectionManager->currentItem(); - index = selectedItems.contains(currentItemIndex) - ? currentItemIndex : selectedItems.first(); + index = selectedItems.contains(currentItemIndex) ? currentItemIndex : selectedItems.first(); } else if (selectedItems.count() == 1) { index = selectedItems.first(); } @@ -437,12 +440,12 @@ bool KItemListController::keyPressEvent(QKeyEvent* event) m_selectionManager->beginAnchoredSelection(index); break; } else if (m_keyboardManager->addKeyBeginsNewSearch()) { // File names shouldn't start with a space, - // so we can use this press as a keyboard shortcut instead. + // so we can use this press as a keyboard shortcut instead. Q_EMIT selectionModeChangeRequested(!m_selectionMode); break; } } - Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string. + Q_FALLTHROUGH(); // fall through to the default case and add the Space to the current search string. default: m_keyboardManager->addKeys(event->text()); // Make sure unconsumed events get propagated up the chain. #302329 @@ -487,7 +490,7 @@ bool KItemListController::keyPressEvent(QKeyEvent* event) return true; } -void KItemListController::slotChangeCurrentItem(const QString& text, bool searchFromNextItem) +void KItemListController::slotChangeCurrentItem(const QString &text, bool searchFromNextItem) { if (!m_model || m_model->count() == 0) { return; @@ -541,13 +544,13 @@ void KItemListController::slotAutoActivationTimeout() } } -bool KItemListController::inputMethodEvent(QInputMethodEvent* event) +bool KItemListController::inputMethodEvent(QInputMethodEvent *event) { Q_UNUSED(event) return false; } -bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform) +bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform) { m_mousePress = true; @@ -572,7 +575,7 @@ bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const return true; } -bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform) +bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform) { if (!m_view) { return false; @@ -607,7 +610,7 @@ bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const } } } else { - KItemListRubberBand* rubberBand = m_view->rubberBand(); + KItemListRubberBand *rubberBand = m_view->rubberBand(); if (rubberBand->isActive()) { QPointF endPos = transform.map(event->pos()); @@ -637,7 +640,7 @@ bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const return false; } -bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform) +bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform) { m_mousePress = false; m_isTouchEvent = false; @@ -650,7 +653,7 @@ bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, con m_view->m_tapAndHoldIndicator->setActive(false); } - KItemListRubberBand* rubberBand = m_view->rubberBand(); + KItemListRubberBand *rubberBand = m_view->rubberBand(); if (event->source() == Qt::MouseEventSynthesizedByQt && !rubberBand->isActive() && m_isTouchEvent) { return false; } @@ -660,7 +663,7 @@ bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, con return onRelease(transform.map(event->pos()), event->modifiers(), event->button(), false); } -bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform) +bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform) { const QPointF pos = transform.map(event->pos()); const std::optional index = m_view->itemAt(pos); @@ -689,16 +692,15 @@ bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, return true; } - bool emitItemActivated = !(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) && - (event->button() & Qt::LeftButton) && - index.has_value() && index.value() < m_model->count(); + bool emitItemActivated = !(m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick) || m_singleClickActivationEnforced) + && (event->button() & Qt::LeftButton) && index.has_value() && index.value() < m_model->count(); if (emitItemActivated) { Q_EMIT itemActivated(index.value()); } return false; } -bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform) +bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) @@ -708,7 +710,7 @@ bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, con return false; } -bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform) +bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) @@ -717,7 +719,7 @@ bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, con m_view->setAutoScroll(false); m_view->hideDropIndicator(); - KItemListWidget* widget = hoveredWidget(); + KItemListWidget *widget = hoveredWidget(); if (widget) { widget->setHovered(false); Q_EMIT itemUnhovered(widget->index()); @@ -725,18 +727,17 @@ bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, con return false; } -bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform) +bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform) { if (!m_model || !m_view) { return false; } - QUrl hoveredDir = m_model->directory(); - KItemListWidget* oldHoveredWidget = hoveredWidget(); + KItemListWidget *oldHoveredWidget = hoveredWidget(); const QPointF pos = transform.map(event->pos()); - KItemListWidget* newHoveredWidget = widgetForDropPos(pos); + KItemListWidget *newHoveredWidget = widgetForDropPos(pos); if (oldHoveredWidget != newHoveredWidget) { m_autoActivationTimer->stop(); @@ -795,7 +796,7 @@ bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, cons return false; } -bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform) +bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform) { if (!m_view) { return false; @@ -832,14 +833,14 @@ bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QT return true; } -bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform) +bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) return false; } -bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform) +bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform) { Q_UNUSED(transform) if (!m_model || !m_view) { @@ -853,8 +854,8 @@ bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const const auto oldHoveredExpansionWidgetIterator = std::find_if(visibleItemListWidgets.begin(), visibleItemListWidgets.end(), [](auto &widget) { return widget->expansionAreaHovered(); }); - const auto oldHoveredExpansionWidget = oldHoveredExpansionWidgetIterator == visibleItemListWidgets.end() ? - std::nullopt : std::make_optional(*oldHoveredExpansionWidgetIterator); + const auto oldHoveredExpansionWidget = + oldHoveredExpansionWidgetIterator == visibleItemListWidgets.end() ? std::nullopt : std::make_optional(*oldHoveredExpansionWidgetIterator); const auto unhoverOldHoveredWidget = [&]() { if (auto oldHoveredWidget = hoveredWidget(); oldHoveredWidget) { @@ -885,7 +886,6 @@ bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const // we also unhover any old icon+text hovers, in case the mouse movement from icon+text to expansion toggle is too fast (i.e. newHoveredWidget is never null between the transition) unhoverOldHoveredWidget(); - newHoveredWidget->setExpansionAreaHovered(true); } else { // make sure we unhover the old one first if old!=new @@ -922,7 +922,7 @@ bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const return false; } -bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform) +bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) @@ -935,7 +935,7 @@ bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const } const auto widgets = m_view->visibleItemListWidgets(); - for (KItemListWidget* widget : widgets) { + for (KItemListWidget *widget : widgets) { if (widget->isHovered()) { widget->setHovered(false); Q_EMIT itemUnhovered(widget->index()); @@ -944,21 +944,21 @@ bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const return false; } -bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform) +bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) return false; } -bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform) +bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) return false; } -bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& transform) +bool KItemListController::gestureEvent(QGestureEvent *event, const QTransform &transform) { if (!m_view) { return false; @@ -968,8 +968,8 @@ bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& t //we use this to get the right QWidget //the only exception is a tap gesture with state GestureStarted, we need to reset some variable if (!m_mousePress) { - if (QGesture* tap = event->gesture(Qt::TapGesture)) { - QTapGesture* tapGesture = static_cast(tap); + if (QGesture *tap = event->gesture(Qt::TapGesture)) { + QTapGesture *tapGesture = static_cast(tap); if (tapGesture->state() == Qt::GestureStarted) { tapTriggered(tapGesture, transform); } @@ -979,8 +979,8 @@ bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& t bool accepted = false; - if (QGesture* tap = event->gesture(Qt::TapGesture)) { - tapTriggered(static_cast(tap), transform); + if (QGesture *tap = event->gesture(Qt::TapGesture)) { + tapTriggered(static_cast(tap), transform); accepted = true; } if (event->gesture(Qt::TapAndHoldGesture)) { @@ -1002,7 +1002,7 @@ bool KItemListController::gestureEvent(QGestureEvent* event, const QTransform& t return accepted; } -bool KItemListController::touchBeginEvent(QTouchEvent* event, const QTransform& transform) +bool KItemListController::touchBeginEvent(QTouchEvent *event, const QTransform &transform) { Q_UNUSED(event) Q_UNUSED(transform) @@ -1011,7 +1011,7 @@ bool KItemListController::touchBeginEvent(QTouchEvent* event, const QTransform& return false; } -void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& transform) +void KItemListController::tapTriggered(QTapGesture *tap, const QTransform &transform) { static bool scrollerWasActive = false; @@ -1040,8 +1040,7 @@ void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& trans if (m_dragActionOrRightClick) { m_dragActionOrRightClick = false; - } - else { + } else { onPress(tap->hotSpot().toPoint(), tap->position().toPoint(), Qt::NoModifier, Qt::LeftButton); onRelease(transform.map(tap->position()), Qt::NoModifier, Qt::LeftButton, true); } @@ -1049,15 +1048,14 @@ void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& trans } } -void KItemListController::tapAndHoldTriggered(QGestureEvent* event, const QTransform& transform) +void KItemListController::tapAndHoldTriggered(QGestureEvent *event, const QTransform &transform) { - //the Qt TabAndHold gesture is triggerable with a mouse click, we don't want this if (!m_isTouchEvent) { return; } - const QTapAndHoldGesture* tap = static_cast(event->gesture(Qt::TapAndHoldGesture)); + const QTapAndHoldGesture *tap = static_cast(event->gesture(Qt::TapAndHoldGesture)); if (tap->state() == Qt::GestureFinished) { //if a pinch gesture is in progress we don't want a TabAndHold gesture if (m_pinchGestureInProgress) { @@ -1086,11 +1084,11 @@ void KItemListController::tapAndHoldTriggered(QGestureEvent* event, const QTrans } } -void KItemListController::pinchTriggered(QGestureEvent* event, const QTransform& transform) +void KItemListController::pinchTriggered(QGestureEvent *event, const QTransform &transform) { Q_UNUSED(transform) - const QPinchGesture* pinch = static_cast(event->gesture(Qt::PinchGesture)); + const QPinchGesture *pinch = static_cast(event->gesture(Qt::PinchGesture)); const qreal sensitivityModifier = 0.2; static qreal counter = 0; @@ -1114,11 +1112,11 @@ void KItemListController::pinchTriggered(QGestureEvent* event, const QTransform& } } -void KItemListController::swipeTriggered(QGestureEvent* event, const QTransform& transform) +void KItemListController::swipeTriggered(QGestureEvent *event, const QTransform &transform) { Q_UNUSED(transform) - const KTwoFingerSwipe* swipe = static_cast(event->gesture(m_swipeGesture)); + const KTwoFingerSwipe *swipe = static_cast(event->gesture(m_swipeGesture)); if (!swipe) { return; @@ -1145,9 +1143,9 @@ void KItemListController::swipeTriggered(QGestureEvent* event, const QTransform& } } -void KItemListController::twoFingerTapTriggered(QGestureEvent* event, const QTransform& transform) +void KItemListController::twoFingerTapTriggered(QGestureEvent *event, const QTransform &transform) { - const KTwoFingerTap* twoTap = static_cast(event->gesture(m_twoFingerTapGesture)); + const KTwoFingerTap *twoTap = static_cast(event->gesture(m_twoFingerTapGesture)); if (!twoTap) { return; @@ -1160,11 +1158,10 @@ void KItemListController::twoFingerTapTriggered(QGestureEvent* event, const QTra onPress(twoTap->screenPos().toPoint(), twoTap->pos().toPoint(), Qt::ControlModifier, Qt::LeftButton); onRelease(transform.map(twoTap->pos()), Qt::ControlModifier, Qt::LeftButton, false); } - } } -bool KItemListController::processEvent(QEvent* event, const QTransform& transform) +bool KItemListController::processEvent(QEvent *event, const QTransform &transform) { if (!event) { return false; @@ -1172,39 +1169,39 @@ bool KItemListController::processEvent(QEvent* event, const QTransform& transfor switch (event->type()) { case QEvent::KeyPress: - return keyPressEvent(static_cast(event)); + return keyPressEvent(static_cast(event)); case QEvent::InputMethod: - return inputMethodEvent(static_cast(event)); + return inputMethodEvent(static_cast(event)); case QEvent::GraphicsSceneMousePress: - return mousePressEvent(static_cast(event), QTransform()); + return mousePressEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneMouseMove: - return mouseMoveEvent(static_cast(event), QTransform()); + return mouseMoveEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneMouseRelease: - return mouseReleaseEvent(static_cast(event), QTransform()); + return mouseReleaseEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneMouseDoubleClick: - return mouseDoubleClickEvent(static_cast(event), QTransform()); + return mouseDoubleClickEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneWheel: - return wheelEvent(static_cast(event), QTransform()); + return wheelEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneDragEnter: - return dragEnterEvent(static_cast(event), QTransform()); + return dragEnterEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneDragLeave: - return dragLeaveEvent(static_cast(event), QTransform()); + return dragLeaveEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneDragMove: - return dragMoveEvent(static_cast(event), QTransform()); + return dragMoveEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneDrop: - return dropEvent(static_cast(event), QTransform()); + return dropEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneHoverEnter: - return hoverEnterEvent(static_cast(event), QTransform()); + return hoverEnterEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneHoverMove: - return hoverMoveEvent(static_cast(event), QTransform()); + return hoverMoveEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneHoverLeave: - return hoverLeaveEvent(static_cast(event), QTransform()); + return hoverLeaveEvent(static_cast(event), QTransform()); case QEvent::GraphicsSceneResize: - return resizeEvent(static_cast(event), transform); + return resizeEvent(static_cast(event), transform); case QEvent::Gesture: - return gestureEvent(static_cast(event), transform); + return gestureEvent(static_cast(event), transform); case QEvent::TouchBegin: - return touchBeginEvent(static_cast(event), transform); + return touchBeginEvent(static_cast(event), transform); default: break; } @@ -1218,7 +1215,7 @@ void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previ return; } - KItemListRubberBand* rubberBand = m_view->rubberBand(); + KItemListRubberBand *rubberBand = m_view->rubberBand(); if (rubberBand->isActive()) { const qreal diff = current - previous; // TODO: Ideally just QCursor::pos() should be used as @@ -1242,7 +1239,7 @@ void KItemListController::slotRubberBandChanged() return; } - const KItemListRubberBand* rubberBand = m_view->rubberBand(); + const KItemListRubberBand *rubberBand = m_view->rubberBand(); const QPointF startPos = rubberBand->startPosition(); const QPointF endPos = rubberBand->endPosition(); QRectF rubberBandRect = QRectF(startPos, endPos).normalized(); @@ -1257,8 +1254,7 @@ void KItemListController::slotRubberBandChanged() if (!m_oldSelection.isEmpty()) { // Clear the old selection that was available before the rubberband has // been activated in case if no Shift- or Control-key are pressed - const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier || - QApplication::keyboardModifiers() & Qt::ControlModifier; + const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier || QApplication::keyboardModifiers() & Qt::ControlModifier; if (!shiftOrControlPressed && !m_selectionMode) { m_oldSelection.clear(); } @@ -1268,7 +1264,7 @@ void KItemListController::slotRubberBandChanged() // Select all visible items that intersect with the rubberband const auto widgets = m_view->visibleItemListWidgets(); - for (const KItemListWidget* widget : widgets) { + for (const KItemListWidget *widget : widgets) { const int index = widget->index(); const QRectF widgetRect = m_view->itemRect(index); @@ -1284,8 +1280,7 @@ void KItemListController::slotRubberBandChanged() // Select all invisible items that intersect with the rubberband. Instead of // iterating all items only the area which might be touched by the rubberband // will be checked. - const bool increaseIndex = scrollVertical ? - startPos.y() > endPos.y(): startPos.x() > endPos.x(); + const bool increaseIndex = scrollVertical ? startPos.y() > endPos.y() : startPos.x() > endPos.x(); int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1; bool selectionFinished = false; @@ -1297,14 +1292,12 @@ void KItemListController::slotRubberBandChanged() if (increaseIndex) { ++index; - selectionFinished = (index >= m_model->count()) || - ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) || - (!scrollVertical && widgetRect.left() > rubberBandRect.right()); + selectionFinished = (index >= m_model->count()) || (scrollVertical && widgetRect.top() > rubberBandRect.bottom()) + || (!scrollVertical && widgetRect.left() > rubberBandRect.right()); } else { --index; - selectionFinished = (index < 0) || - ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) || - (!scrollVertical && widgetRect.right() < rubberBandRect.left()); + selectionFinished = (index < 0) || (scrollVertical && widgetRect.bottom() < rubberBandRect.top()) + || (!scrollVertical && widgetRect.right() < rubberBandRect.left()); } } while (!selectionFinished); @@ -1314,8 +1307,7 @@ void KItemListController::slotRubberBandChanged() // 1. All previously selected items which are not inside the rubberband, and // 2. all items inside the rubberband which have not been selected previously. m_selectionManager->setSelectedItems(m_oldSelection ^ selectedItems); - } - else { + } else { m_selectionManager->setSelectedItems(selectedItems + m_oldSelection); } } @@ -1339,7 +1331,7 @@ void KItemListController::startDragging() // The created drag object will be owned and deleted // by QApplication::activeWindow(). - QDrag* drag = new QDrag(QApplication::activeWindow()); + QDrag *drag = new QDrag(QApplication::activeWindow()); drag->setMimeData(data); const QPixmap pixmap = m_view->createDragPixmap(selectedItems); @@ -1354,12 +1346,12 @@ void KItemListController::startDragging() QAccessible::updateAccessibility(&accessibilityEvent); } -KItemListWidget* KItemListController::hoveredWidget() const +KItemListWidget *KItemListController::hoveredWidget() const { Q_ASSERT(m_view); const auto widgets = m_view->visibleItemListWidgets(); - for (KItemListWidget* widget : widgets) { + for (KItemListWidget *widget : widgets) { if (widget->isHovered()) { return widget; } @@ -1368,12 +1360,12 @@ KItemListWidget* KItemListController::hoveredWidget() const return nullptr; } -KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const +KItemListWidget *KItemListController::widgetForPos(const QPointF &pos) const { Q_ASSERT(m_view); const auto widgets = m_view->visibleItemListWidgets(); - for (KItemListWidget* widget : widgets) { + for (KItemListWidget *widget : widgets) { const QPointF mappedPos = widget->mapFromItem(m_view, pos); if (widget->contains(mappedPos) || widget->selectionRect().contains(mappedPos)) { return widget; @@ -1383,12 +1375,12 @@ KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const return nullptr; } -KItemListWidget* KItemListController::widgetForDropPos(const QPointF& pos) const +KItemListWidget *KItemListController::widgetForDropPos(const QPointF &pos) const { Q_ASSERT(m_view); const auto widgets = m_view->visibleItemListWidgets(); - for (KItemListWidget* widget : widgets) { + for (KItemListWidget *widget : widgets) { const QPointF mappedPos = widget->mapFromItem(m_view, pos); if (widget->contains(mappedPos)) { return widget; @@ -1400,9 +1392,8 @@ KItemListWidget* KItemListController::widgetForDropPos(const QPointF& pos) const void KItemListController::updateKeyboardAnchor() { - const bool validAnchor = m_keyboardAnchorIndex >= 0 && - m_keyboardAnchorIndex < m_model->count() && - keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos; + const bool validAnchor = + m_keyboardAnchorIndex >= 0 && m_keyboardAnchorIndex < m_model->count() && keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos; if (!validAnchor) { const int index = m_selectionManager->currentItem(); m_keyboardAnchorIndex = index; @@ -1501,7 +1492,7 @@ void KItemListController::updateExtendedSelectionRegion() } } -bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons) +bool KItemListController::onPress(const QPoint &screenPos, const QPointF &pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons) { Q_EMIT mouseButtonPressed(m_pressedIndex.value_or(-1), buttons); @@ -1544,16 +1535,14 @@ bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, c // - open the context menu and perform an action for all selected items. const bool shiftOrControlPressed = shiftPressed || controlPressed; const bool pressedItemAlreadySelected = m_pressedIndex.has_value() && m_selectionManager->isSelected(m_pressedIndex.value()); - const bool clearSelection = m_selectionBehavior == SingleSelection || - (!shiftOrControlPressed && !pressedItemAlreadySelected); - + const bool clearSelection = m_selectionBehavior == SingleSelection || (!shiftOrControlPressed && !pressedItemAlreadySelected); // When this method returns false, a rubberBand selection is created using KItemListController::startRubberBand via the caller. if (clearSelection) { const int selectedItemsCount = m_selectionManager->selectedItems().count(); m_selectionManager->clearSelection(); // clear and bail when we got an existing multi-selection - if (selectedItemsCount > 1 && m_pressedIndex.has_value()) { + if (selectedItemsCount > 1 && m_pressedIndex.has_value()) { const auto row = m_view->m_visibleItems.value(m_pressedIndex.value()); const auto mappedPos = row->mapFromItem(m_view, pos); if (pressedItemAlreadySelected || row->iconRect().contains(mappedPos) || row->textRect().contains(mappedPos)) { @@ -1597,7 +1586,6 @@ bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, c } if (rightClick) { - // Do header hit check and short circuit before commencing any state changing effects if (m_view->headerBoundaries().contains(pos)) { Q_EMIT headerContextMenuRequested(screenPos); @@ -1605,7 +1593,7 @@ bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, c } // Stop rubber band from persisting after right-clicks - KItemListRubberBand* rubberBand = m_view->rubberBand(); + KItemListRubberBand *rubberBand = m_view->rubberBand(); if (rubberBand->isActive()) { disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged); rubberBand->setActive(false); @@ -1687,7 +1675,7 @@ bool KItemListController::onPress(const QPoint& screenPos, const QPointF& pos, c return false; } -bool KItemListController::onRelease(const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch) +bool KItemListController::onRelease(const QPointF &pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch) { const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex.value_or(-1), m_pressedMousePos); if (isAboveSelectionToggle) { @@ -1702,12 +1690,11 @@ bool KItemListController::onRelease(const QPointF& pos, const Qt::KeyboardModifi } const bool controlPressed = modifiers & Qt::ControlModifier; - const bool shiftOrControlPressed = modifiers & Qt::ShiftModifier || - controlPressed; + const bool shiftOrControlPressed = modifiers & Qt::ShiftModifier || controlPressed; const std::optional index = m_view->itemAt(pos); - KItemListRubberBand* rubberBand = m_view->rubberBand(); + KItemListRubberBand *rubberBand = m_view->rubberBand(); bool rubberBandRelease = false; if (rubberBand->isActive()) { disconnect(rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListController::slotRubberBandChanged); @@ -1796,7 +1783,7 @@ void KItemListController::startRubberBand() } m_oldSelection = m_selectionManager->selectedItems(); - KItemListRubberBand* rubberBand = m_view->rubberBand(); + KItemListRubberBand *rubberBand = m_view->rubberBand(); rubberBand->setStartPosition(startPos); rubberBand->setEndPosition(startPos); rubberBand->setActive(true); diff --git a/src/kitemviews/kitemlistcontroller.h b/src/kitemviews/kitemlistcontroller.h index b6a2f05fee..d75a8a22d5 100644 --- a/src/kitemviews/kitemlistcontroller.h +++ b/src/kitemviews/kitemlistcontroller.h @@ -49,45 +49,35 @@ class QTouchEvent; class DOLPHIN_EXPORT KItemListController : public QObject { Q_OBJECT - Q_PROPERTY(KItemModelBase* model READ model WRITE setModel) + Q_PROPERTY(KItemModelBase *model READ model WRITE setModel) Q_PROPERTY(KItemListView *view READ view WRITE setView) Q_PROPERTY(SelectionBehavior selectionBehavior READ selectionBehavior WRITE setSelectionBehavior) Q_PROPERTY(AutoActivationBehavior autoActivationBehavior READ autoActivationBehavior WRITE setAutoActivationBehavior) Q_PROPERTY(MouseDoubleClickAction mouseDoubleClickAction READ mouseDoubleClickAction WRITE setMouseDoubleClickAction) public: - enum SelectionBehavior { - NoSelection, - SingleSelection, - MultiSelection - }; + enum SelectionBehavior { NoSelection, SingleSelection, MultiSelection }; Q_ENUM(SelectionBehavior) - enum AutoActivationBehavior { - ActivationAndExpansion, - ExpansionOnly - }; + enum AutoActivationBehavior { ActivationAndExpansion, ExpansionOnly }; - enum MouseDoubleClickAction { - ActivateAndExpandItem, - ActivateItemOnly - }; + enum MouseDoubleClickAction { ActivateAndExpandItem, ActivateItemOnly }; /** * @param model Model of the controller. The ownership is passed to the controller. * @param view View of the controller. The ownership is passed to the controller. * @param parent Optional parent object. */ - KItemListController(KItemModelBase* model, KItemListView* view, QObject* parent = nullptr); + KItemListController(KItemModelBase *model, KItemListView *view, QObject *parent = nullptr); ~KItemListController() override; - void setModel(KItemModelBase* model); - KItemModelBase* model() const; + void setModel(KItemModelBase *model); + KItemModelBase *model() const; - void setView(KItemListView* view); - KItemListView* view() const; + void setView(KItemListView *view); + KItemListView *view() const; - KItemListSelectionManager* selectionManager() const; + KItemListSelectionManager *selectionManager() const; void setSelectionBehavior(SelectionBehavior behavior); SelectionBehavior selectionBehavior() const; @@ -133,7 +123,7 @@ public: void setSelectionModeEnabled(bool enabled); bool selectionMode() const; - bool processEvent(QEvent* event, const QTransform& transform); + bool processEvent(QEvent *event, const QTransform &transform); Q_SIGNALS: /** @@ -154,17 +144,17 @@ Q_SIGNALS: * Emitted if a context-menu is requested for the item with * the index \a index. It is assured that the index is valid. */ - void itemContextMenuRequested(int index, const QPointF& pos); + void itemContextMenuRequested(int index, const QPointF &pos); /** * Emitted if a context-menu is requested for the KItemListView. */ - void viewContextMenuRequested(const QPointF& pos); + void viewContextMenuRequested(const QPointF &pos); /** * Emitted if a context-menu is requested for the header of the KItemListView. */ - void headerContextMenuRequested(const QPointF& pos); + void headerContextMenuRequested(const QPointF &pos); /** * Is emitted if the item with the index \p index gets hovered. @@ -203,13 +193,13 @@ Q_SIGNALS: * which is emitted if the drop event occurs on an empty area in * the view, and make sure that index is always >= 0 in itemDropEvent(). */ - void itemDropEvent(int index, QGraphicsSceneDragDropEvent* event); + void itemDropEvent(int index, QGraphicsSceneDragDropEvent *event); /** * Is emitted if a drop event is done between the item with the index * \a index and the previous item. */ - void aboveItemDropEvent(int index, QGraphicsSceneDragDropEvent* event); + void aboveItemDropEvent(int index, QGraphicsSceneDragDropEvent *event); /** * Is emitted if the Escape key is pressed. @@ -227,8 +217,8 @@ Q_SIGNALS: */ void selectionModeChangeRequested(bool enabled); - void modelChanged(KItemModelBase* current, KItemModelBase* previous); - void viewChanged(KItemListView* current, KItemListView* previous); + void modelChanged(KItemModelBase *current, KItemModelBase *previous); + void viewChanged(KItemListView *current, KItemListView *previous); void selectedItemTextPressed(int index); @@ -249,7 +239,7 @@ private Q_SLOTS: */ void slotRubberBandChanged(); - void slotChangeCurrentItem(const QString& text, bool searchFromNextItem); + void slotChangeCurrentItem(const QString &text, bool searchFromNextItem); void slotAutoActivationTimeout(); @@ -263,13 +253,13 @@ private: * @return Widget that is currently in the hovered state. 0 is returned * if no widget is marked as hovered. */ - KItemListWidget* hoveredWidget() const; + KItemListWidget *hoveredWidget() const; /** * @return Widget that is below the position \a pos. 0 is returned * if no widget is below the position. */ - KItemListWidget* widgetForPos(const QPointF& pos) const; + KItemListWidget *widgetForPos(const QPointF &pos) const; /** * @return Widget that should receive a drop event if an item is dropped at \a pos. 0 is returned @@ -278,7 +268,7 @@ private: * While widgetForPos() returns a widget if \a pos is anywhere inside the hover highlight area of the widget, * widgetForDropPos() only returns a widget if \a pos is directly above the widget (widget->contains(pos) == true). */ - KItemListWidget* widgetForDropPos(const QPointF& pos) const; + KItemListWidget *widgetForDropPos(const QPointF &pos) const; /** * Updates m_keyboardAnchorIndex and m_keyboardAnchorPos. If no anchor is @@ -315,30 +305,30 @@ private: */ void updateExtendedSelectionRegion(); - bool keyPressEvent(QKeyEvent* event); - bool inputMethodEvent(QInputMethodEvent* event); - bool mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform); - bool mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform); - bool mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform); - bool mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform); - bool dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform); - bool dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform); - bool dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform); - bool dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform); - bool hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform); - bool hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform); - bool hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform); - bool wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform); - bool resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform); - bool gestureEvent(QGestureEvent* event, const QTransform& transform); - bool touchBeginEvent(QTouchEvent* event, const QTransform& transform); - void tapTriggered(QTapGesture* tap, const QTransform& transform); - void tapAndHoldTriggered(QGestureEvent* event, const QTransform& transform); - void pinchTriggered(QGestureEvent* event, const QTransform& transform); - void swipeTriggered(QGestureEvent* event, const QTransform& transform); - void twoFingerTapTriggered(QGestureEvent* event, const QTransform& transform); - bool onPress(const QPoint& screenPos, const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons); - bool onRelease(const QPointF& pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch); + bool keyPressEvent(QKeyEvent *event); + bool inputMethodEvent(QInputMethodEvent *event); + bool mousePressEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform); + bool mouseMoveEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform); + bool mouseReleaseEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform); + bool mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform); + bool dragEnterEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform); + bool dragLeaveEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform); + bool dragMoveEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform); + bool dropEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform); + bool hoverEnterEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform); + bool hoverMoveEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform); + bool hoverLeaveEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform); + bool wheelEvent(QGraphicsSceneWheelEvent *event, const QTransform &transform); + bool resizeEvent(QGraphicsSceneResizeEvent *event, const QTransform &transform); + bool gestureEvent(QGestureEvent *event, const QTransform &transform); + bool touchBeginEvent(QTouchEvent *event, const QTransform &transform); + void tapTriggered(QTapGesture *tap, const QTransform &transform); + void tapAndHoldTriggered(QGestureEvent *event, const QTransform &transform); + void pinchTriggered(QGestureEvent *event, const QTransform &transform); + void swipeTriggered(QGestureEvent *event, const QTransform &transform); + void twoFingerTapTriggered(QGestureEvent *event, const QTransform &transform); + bool onPress(const QPoint &screenPos, const QPointF &pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons); + bool onRelease(const QPointF &pos, const Qt::KeyboardModifiers modifiers, const Qt::MouseButtons buttons, bool touch); void startRubberBand(); private: @@ -355,14 +345,14 @@ private: SelectionBehavior m_selectionBehavior; AutoActivationBehavior m_autoActivationBehavior; MouseDoubleClickAction m_mouseDoubleClickAction; - KItemModelBase* m_model; - KItemListView* m_view; - KItemListSelectionManager* m_selectionManager; - KItemListKeyboardSearchManager* m_keyboardManager; + KItemModelBase *m_model; + KItemListView *m_view; + KItemListSelectionManager *m_selectionManager; + KItemListKeyboardSearchManager *m_keyboardManager; std::optional m_pressedIndex; QPointF m_pressedMousePos; - QTimer* m_autoActivationTimer; + QTimer *m_autoActivationTimer; Qt::GestureType m_swipeGesture; Qt::GestureType m_twoFingerTapGesture; @@ -394,5 +384,3 @@ private: }; #endif - - diff --git a/src/kitemviews/kitemlistgroupheader.cpp b/src/kitemviews/kitemlistgroupheader.cpp index f0ff52503d..66cd74eb4b 100644 --- a/src/kitemviews/kitemlistgroupheader.cpp +++ b/src/kitemviews/kitemlistgroupheader.cpp @@ -14,17 +14,17 @@ #include #include -KItemListGroupHeader::KItemListGroupHeader(QGraphicsWidget* parent) : - QGraphicsWidget(parent), - m_dirtyCache(true), - m_role(), - m_data(), - m_styleOption(), - m_scrollOrientation(Qt::Vertical), - m_itemIndex(-1), - m_separatorColor(), - m_roleColor(), - m_roleBounds() +KItemListGroupHeader::KItemListGroupHeader(QGraphicsWidget *parent) + : QGraphicsWidget(parent) + , m_dirtyCache(true) + , m_role() + , m_data() + , m_styleOption() + , m_scrollOrientation(Qt::Vertical) + , m_itemIndex(-1) + , m_separatorColor() + , m_roleColor() + , m_roleBounds() { } @@ -32,7 +32,7 @@ KItemListGroupHeader::~KItemListGroupHeader() { } -void KItemListGroupHeader::setRole(const QByteArray& role) +void KItemListGroupHeader::setRole(const QByteArray &role) { if (m_role != role) { const QByteArray previous = m_role; @@ -47,7 +47,7 @@ QByteArray KItemListGroupHeader::role() const return m_role; } -void KItemListGroupHeader::setData(const QVariant& data) +void KItemListGroupHeader::setData(const QVariant &data) { if (m_data != data) { const QVariant previous = m_data; @@ -62,7 +62,7 @@ QVariant KItemListGroupHeader::data() const return m_data; } -void KItemListGroupHeader::setStyleOption(const KItemListStyleOption& option) +void KItemListGroupHeader::setStyleOption(const KItemListStyleOption &option) { if (m_styleOption == option) { return; @@ -74,7 +74,7 @@ void KItemListGroupHeader::setStyleOption(const KItemListStyleOption& option) styleOptionChanged(option, previous); } -const KItemListStyleOption& KItemListGroupHeader::styleOption() const +const KItemListStyleOption &KItemListGroupHeader::styleOption() const { return m_styleOption; } @@ -111,7 +111,7 @@ Qt::Orientation KItemListGroupHeader::scrollOrientation() const return m_scrollOrientation; } -void KItemListGroupHeader::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KItemListGroupHeader::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(painter) Q_UNUSED(option) @@ -125,19 +125,19 @@ void KItemListGroupHeader::paint(QPainter* painter, const QStyleOptionGraphicsIt paintRole(painter, m_roleBounds, m_roleColor); } -void KItemListGroupHeader::roleChanged(const QByteArray& current, const QByteArray& previous) +void KItemListGroupHeader::roleChanged(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListGroupHeader::dataChanged(const QVariant& current, const QVariant& previous) +void KItemListGroupHeader::dataChanged(const QVariant ¤t, const QVariant &previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListGroupHeader::styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) +void KItemListGroupHeader::styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -155,7 +155,7 @@ void KItemListGroupHeader::itemIndexChanged(int current, int previous) Q_UNUSED(previous) } -void KItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent* event) +void KItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent *event) { QGraphicsWidget::resizeEvent(event); if (event->oldSize().height() != event->newSize().height()) { @@ -190,22 +190,19 @@ void KItemListGroupHeader::updateSize() const int y = (m_scrollOrientation == Qt::Vertical) ? padding : horizontalMargin; - m_roleBounds = QRectF(horizontalMargin + padding, - y, - size().width() - 2 * padding - horizontalMargin, - roleHeight); + m_roleBounds = QRectF(horizontalMargin + padding, y, size().width() - 2 * padding - horizontalMargin, roleHeight); update(); } -QColor KItemListGroupHeader::mixedColor(const QColor& c1, const QColor& c2, int c1Percent) +QColor KItemListGroupHeader::mixedColor(const QColor &c1, const QColor &c2, int c1Percent) { Q_ASSERT(c1Percent >= 0 && c1Percent <= 100); const int c2Percent = 100 - c1Percent; - return QColor((c1.red() * c1Percent + c2.red() * c2Percent) / 100, + return QColor((c1.red() * c1Percent + c2.red() * c2Percent) / 100, (c1.green() * c1Percent + c2.green() * c2Percent) / 100, - (c1.blue() * c1Percent + c2.blue() * c2Percent) / 100); + (c1.blue() * c1Percent + c2.blue() * c2Percent) / 100); } QPalette::ColorRole KItemListGroupHeader::normalTextColorRole() const @@ -229,4 +226,3 @@ QColor KItemListGroupHeader::baseColor() const const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive; return styleOption().palette.color(group, normalBaseColorRole()); } - diff --git a/src/kitemviews/kitemlistgroupheader.h b/src/kitemviews/kitemlistgroupheader.h index 48af1e9e0d..1522af0ce8 100644 --- a/src/kitemviews/kitemlistgroupheader.h +++ b/src/kitemviews/kitemlistgroupheader.h @@ -28,17 +28,17 @@ class DOLPHIN_EXPORT KItemListGroupHeader : public QGraphicsWidget Q_OBJECT public: - explicit KItemListGroupHeader(QGraphicsWidget* parent = nullptr); + explicit KItemListGroupHeader(QGraphicsWidget *parent = nullptr); ~KItemListGroupHeader() override; - void setRole(const QByteArray& role); + void setRole(const QByteArray &role); QByteArray role() const; - void setData(const QVariant& data); + void setData(const QVariant &data); QVariant data() const; - void setStyleOption(const KItemListStyleOption& option); - const KItemListStyleOption& styleOption() const; + void setStyleOption(const KItemListStyleOption &option); + const KItemListStyleOption &styleOption() const; /** * Sets the scroll orientation that is used by the KItemListView. @@ -51,29 +51,29 @@ public: void setItemIndex(int index); int itemIndex() const; - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; protected: - virtual void paintRole(QPainter* painter, const QRectF& roleBounds, const QColor& color) = 0; - virtual void paintSeparator(QPainter* painter, const QColor& color) = 0; + virtual void paintRole(QPainter *painter, const QRectF &roleBounds, const QColor &color) = 0; + virtual void paintSeparator(QPainter *painter, const QColor &color) = 0; /** * Is called after the role has been changed and allows the derived class * to react on this change. */ - virtual void roleChanged(const QByteArray& current, const QByteArray& previous); + virtual void roleChanged(const QByteArray ¤t, const QByteArray &previous); /** * Is called after the role has been changed and allows the derived class * to react on this change. */ - virtual void dataChanged(const QVariant& current, const QVariant& previous); + virtual void dataChanged(const QVariant ¤t, const QVariant &previous); /** * Is called after the style option has been changed and allows the derived class * to react on this change. */ - virtual void styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous); + virtual void styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous); /** * Is called after the scroll orientation has been changed and allows the derived class @@ -87,7 +87,7 @@ protected: */ virtual void itemIndexChanged(int current, int previous); - void resizeEvent(QGraphicsSceneResizeEvent* event) override; + void resizeEvent(QGraphicsSceneResizeEvent *event) override; virtual QPalette::ColorRole normalTextColorRole() const; virtual QPalette::ColorRole normalBaseColorRole() const; @@ -96,7 +96,7 @@ private: void updateCache(); void updateSize(); - static QColor mixedColor(const QColor& c1, const QColor& c2, int c1Percent = 50); + static QColor mixedColor(const QColor &c1, const QColor &c2, int c1Percent = 50); QColor textColor() const; QColor baseColor() const; @@ -114,5 +114,3 @@ private: QRectF m_roleBounds; }; #endif - - diff --git a/src/kitemviews/kitemlistheader.cpp b/src/kitemviews/kitemlistheader.cpp index 64d6a25595..dfbe7ab2c7 100644 --- a/src/kitemviews/kitemlistheader.cpp +++ b/src/kitemviews/kitemlistheader.cpp @@ -28,7 +28,7 @@ bool KItemListHeader::automaticColumnResizing() const return m_headerWidget->automaticColumnResizing(); } -void KItemListHeader::setColumnWidth(const QByteArray& role, qreal width) +void KItemListHeader::setColumnWidth(const QByteArray &role, qreal width) { if (!m_headerWidget->automaticColumnResizing()) { m_headerWidget->setColumnWidth(role, width); @@ -37,16 +37,16 @@ void KItemListHeader::setColumnWidth(const QByteArray& role, qreal width) } } -qreal KItemListHeader::columnWidth(const QByteArray& role) const +qreal KItemListHeader::columnWidth(const QByteArray &role) const { return m_headerWidget->columnWidth(role); } -void KItemListHeader::setColumnWidths(const QHash& columnWidths) +void KItemListHeader::setColumnWidths(const QHash &columnWidths) { if (!m_headerWidget->automaticColumnResizing()) { const auto visibleRoles = m_view->visibleRoles(); - for (const QByteArray& role : visibleRoles) { + for (const QByteArray &role : visibleRoles) { const qreal width = columnWidths.value(role); m_headerWidget->setColumnWidth(role, width); } @@ -56,12 +56,13 @@ void KItemListHeader::setColumnWidths(const QHash& columnWidt } } -qreal KItemListHeader::preferredColumnWidth(const QByteArray& role) const +qreal KItemListHeader::preferredColumnWidth(const QByteArray &role) const { return m_headerWidget->preferredColumnWidth(role); } -void KItemListHeader::setSidePadding(qreal width){ +void KItemListHeader::setSidePadding(qreal width) +{ if (m_headerWidget->sidePadding() != width) { m_headerWidget->setSidePadding(width); if (m_headerWidget->automaticColumnResizing()) { @@ -71,22 +72,19 @@ void KItemListHeader::setSidePadding(qreal width){ } } -qreal KItemListHeader::sidePadding() const{ +qreal KItemListHeader::sidePadding() const +{ return m_headerWidget->sidePadding(); } -KItemListHeader::KItemListHeader(KItemListView* listView) : - QObject(listView), - m_view(listView) +KItemListHeader::KItemListHeader(KItemListView *listView) + : QObject(listView) + , m_view(listView) { m_headerWidget = m_view->m_headerWidget; Q_ASSERT(m_headerWidget); - connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, - this, &KItemListHeader::columnWidthChanged); - connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChangeFinished, - this, &KItemListHeader::columnWidthChangeFinished); - connect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, - this, &KItemListHeader::sidePaddingChanged); + connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, this, &KItemListHeader::columnWidthChanged); + connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChangeFinished, this, &KItemListHeader::columnWidthChangeFinished); + connect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, this, &KItemListHeader::sidePaddingChanged); } - diff --git a/src/kitemviews/kitemlistheader.h b/src/kitemviews/kitemlistheader.h index 66223f0c7e..04519f12c7 100644 --- a/src/kitemviews/kitemlistheader.h +++ b/src/kitemviews/kitemlistheader.h @@ -41,8 +41,8 @@ public: * the width only gets applied if KItemListHeader::automaticColumnResizing() * has been turned off. */ - void setColumnWidth(const QByteArray& role, qreal width); - qreal columnWidth(const QByteArray& role) const; + void setColumnWidth(const QByteArray &role, qreal width); + qreal columnWidth(const QByteArray &role) const; /** * Sets the widths of the columns for all roles. From a performance point of @@ -51,12 +51,12 @@ public: * Note that the widths only get applied if KItemListHeader::automaticColumnResizing() * has been turned off. */ - void setColumnWidths(const QHash& columnWidths); + void setColumnWidths(const QHash &columnWidths); /** * @return The column width that is required to show the role unclipped. */ - qreal preferredColumnWidth(const QByteArray& role) const; + qreal preferredColumnWidth(const QByteArray &role) const; /** * Sets the width of the column *before* the first column. @@ -72,27 +72,22 @@ Q_SIGNALS: * Is emitted if the width of a column has been adjusted by the user with the mouse * (no signal is emitted if KItemListHeader::setColumnWidth() is invoked). */ - void columnWidthChanged(const QByteArray& role, - qreal currentWidth, - qreal previousWidth); + void columnWidthChanged(const QByteArray &role, qreal currentWidth, qreal previousWidth); /** * Is emitted if the user has released the mouse button after adjusting the * width of a visible role. */ - void columnWidthChangeFinished(const QByteArray& role, - qreal currentWidth); + void columnWidthChangeFinished(const QByteArray &role, qreal currentWidth); private: - explicit KItemListHeader(KItemListView* listView); + explicit KItemListHeader(KItemListView *listView); private: - KItemListView* m_view; - KItemListHeaderWidget* m_headerWidget; + KItemListView *m_view; + KItemListHeaderWidget *m_headerWidget; friend class KItemListView; // Constructs the KItemListHeader instance }; #endif - - diff --git a/src/kitemviews/kitemlistselectionmanager.cpp b/src/kitemviews/kitemlistselectionmanager.cpp index ce0dc06deb..2a2fbac81d 100644 --- a/src/kitemviews/kitemlistselectionmanager.cpp +++ b/src/kitemviews/kitemlistselectionmanager.cpp @@ -9,13 +9,13 @@ #include "kitemlistselectionmanager.h" -KItemListSelectionManager::KItemListSelectionManager(QObject* parent) : - QObject(parent), - m_currentItem(-1), - m_anchorItem(-1), - m_selectedItems(), - m_isAnchoredSelectionActive(false), - m_model(nullptr) +KItemListSelectionManager::KItemListSelectionManager(QObject *parent) + : QObject(parent) + , m_currentItem(-1) + , m_anchorItem(-1) + , m_selectedItems() + , m_isAnchoredSelectionActive(false) + , m_model(nullptr) { } @@ -51,7 +51,7 @@ int KItemListSelectionManager::currentItem() const return m_currentItem; } -void KItemListSelectionManager::setSelectedItems(const KItemSet& items) +void KItemListSelectionManager::setSelectedItems(const KItemSet &items) { if (m_selectedItems != items) { const KItemSet previous = m_selectedItems; @@ -114,7 +114,7 @@ void KItemListSelectionManager::setSelected(int index, int count, SelectionMode count = qMin(count, m_model->count() - index); - const int endIndex = index + count -1; + const int endIndex = index + count - 1; switch (mode) { case Select: for (int i = index; i <= endIndex; ++i) { @@ -198,12 +198,12 @@ bool KItemListSelectionManager::isAnchoredSelectionActive() const return m_isAnchoredSelectionActive; } -KItemModelBase* KItemListSelectionManager::model() const +KItemModelBase *KItemListSelectionManager::model() const { return m_model; } -void KItemListSelectionManager::setModel(KItemModelBase* model) +void KItemListSelectionManager::setModel(KItemModelBase *model) { m_model = model; if (model && model->count() > 0) { @@ -211,7 +211,7 @@ void KItemListSelectionManager::setModel(KItemModelBase* model) } } -void KItemListSelectionManager::itemsInserted(const KItemRangeList& itemRanges) +void KItemListSelectionManager::itemsInserted(const KItemRangeList &itemRanges) { // Store the current selection (needed in the selectionChanged() signal) const KItemSet previousSelection = selectedItems(); @@ -222,7 +222,7 @@ void KItemListSelectionManager::itemsInserted(const KItemRangeList& itemRanges) } else { const int previousCurrent = m_currentItem; int inc = 0; - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { if (m_currentItem < itemRange.index) { break; } @@ -242,7 +242,7 @@ void KItemListSelectionManager::itemsInserted(const KItemRangeList& itemRanges) m_anchorItem = 0; } else { int inc = 0; - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { if (m_anchorItem < itemRange.index) { break; } @@ -256,9 +256,9 @@ void KItemListSelectionManager::itemsInserted(const KItemRangeList& itemRanges) const KItemSet previous = m_selectedItems; m_selectedItems.clear(); - for (int index: previous) { + for (int index : previous) { int inc = 0; - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { if (index < itemRange.index) { break; } @@ -274,7 +274,7 @@ void KItemListSelectionManager::itemsInserted(const KItemRangeList& itemRanges) } } -void KItemListSelectionManager::itemsRemoved(const KItemRangeList& itemRanges) +void KItemListSelectionManager::itemsRemoved(const KItemRangeList &itemRanges) { // Store the current selection (needed in the selectionChanged() signal) const KItemSet previousSelection = selectedItems(); @@ -307,7 +307,7 @@ void KItemListSelectionManager::itemsRemoved(const KItemRangeList& itemRanges) for (int oldIndex : previous) { const int index = indexAfterRangesRemoving(oldIndex, itemRanges, DiscardRemovedIndex); - if (index >= 0) { + if (index >= 0) { m_selectedItems.insert(index); } } @@ -322,7 +322,7 @@ void KItemListSelectionManager::itemsRemoved(const KItemRangeList& itemRanges) Q_ASSERT(m_anchorItem < m_model->count()); } -void KItemListSelectionManager::itemsMoved(const KItemRange& itemRange, const QList& movedToIndexes) +void KItemListSelectionManager::itemsMoved(const KItemRange &itemRange, const QList &movedToIndexes) { // Store the current selection (needed in the selectionChanged() signal) const KItemSet previousSelection = selectedItems(); @@ -359,8 +359,7 @@ void KItemListSelectionManager::itemsMoved(const KItemRange& itemRange, const QL for (int index : previous) { if (index >= itemRange.index && index < itemRange.index + itemRange.count) { m_selectedItems.insert(movedToIndexes.at(index - itemRange.index)); - } - else { + } else { m_selectedItems.insert(index); } } @@ -372,11 +371,10 @@ void KItemListSelectionManager::itemsMoved(const KItemRange& itemRange, const QL } } -int KItemListSelectionManager::indexAfterRangesRemoving(int index, const KItemRangeList& itemRanges, - const RangesRemovingBehaviour behaviour) const +int KItemListSelectionManager::indexAfterRangesRemoving(int index, const KItemRangeList &itemRanges, const RangesRemovingBehaviour behaviour) const { int dec = 0; - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { if (index < itemRange.index) { break; } @@ -397,4 +395,3 @@ int KItemListSelectionManager::indexAfterRangesRemoving(int index, const KItemRa } return qBound(-1, index - dec, m_model->count() - 1); } - diff --git a/src/kitemviews/kitemlistselectionmanager.h b/src/kitemviews/kitemlistselectionmanager.h index 2fc5061fea..ba9dd538ad 100644 --- a/src/kitemviews/kitemlistselectionmanager.h +++ b/src/kitemviews/kitemlistselectionmanager.h @@ -24,25 +24,18 @@ class DOLPHIN_EXPORT KItemListSelectionManager : public QObject { Q_OBJECT - enum RangesRemovingBehaviour { - DiscardRemovedIndex, - AdjustRemovedIndex - }; + enum RangesRemovingBehaviour { DiscardRemovedIndex, AdjustRemovedIndex }; public: - enum SelectionMode { - Select, - Deselect, - Toggle - }; + enum SelectionMode { Select, Deselect, Toggle }; - explicit KItemListSelectionManager(QObject* parent = nullptr); + explicit KItemListSelectionManager(QObject *parent = nullptr); ~KItemListSelectionManager() override; void setCurrentItem(int current); int currentItem() const; - void setSelectedItems(const KItemSet& items); + void setSelectedItems(const KItemSet &items); KItemSet selectedItems() const; bool isSelected(int index) const; bool hasSelection() const; @@ -61,24 +54,23 @@ public: void endAnchoredSelection(); bool isAnchoredSelectionActive() const; - KItemModelBase* model() const; + KItemModelBase *model() const; Q_SIGNALS: void currentChanged(int current, int previous); - void selectionChanged(const KItemSet& current, const KItemSet& previous); + void selectionChanged(const KItemSet ¤t, const KItemSet &previous); private: - void setModel(KItemModelBase* model); - void itemsInserted(const KItemRangeList& itemRanges); - void itemsRemoved(const KItemRangeList& itemRanges); - void itemsMoved(const KItemRange& itemRange, const QList& movedToIndexes); - + void setModel(KItemModelBase *model); + void itemsInserted(const KItemRangeList &itemRanges); + void itemsRemoved(const KItemRangeList &itemRanges); + void itemsMoved(const KItemRange &itemRange, const QList &movedToIndexes); /** * Helper method for itemsRemoved. Returns the changed index after removing * the given range. If the index is part of the range, -1 will be returned. */ - int indexAfterRangesRemoving(int index, const KItemRangeList& itemRanges, const RangesRemovingBehaviour behaviour) const; + int indexAfterRangesRemoving(int index, const KItemRangeList &itemRanges, const RangesRemovingBehaviour behaviour) const; private: int m_currentItem; @@ -86,10 +78,10 @@ private: KItemSet m_selectedItems; bool m_isAnchoredSelectionActive; - KItemModelBase* m_model; + KItemModelBase *m_model; friend class KItemListController; // Calls setModel() - friend class KItemListView; // Calls itemsInserted(), itemsRemoved() and itemsMoved() + friend class KItemListView; // Calls itemsInserted(), itemsRemoved() and itemsMoved() friend class KItemListSelectionManagerTest; }; diff --git a/src/kitemviews/kitemliststyleoption.cpp b/src/kitemviews/kitemliststyleoption.cpp index 6e4aaa96ee..7ca6bd1d5a 100644 --- a/src/kitemviews/kitemliststyleoption.cpp +++ b/src/kitemviews/kitemliststyleoption.cpp @@ -6,19 +6,18 @@ #include "kitemliststyleoption.h" - -KItemListStyleOption::KItemListStyleOption() : - rect(), - font(), - fontMetrics(QFont()), - palette(), - padding(-1), - horizontalMargin(-1), - verticalMargin(-1), - iconSize(-1), - extendedSelectionRegion(false), - maxTextLines(0), - maxTextWidth(0) +KItemListStyleOption::KItemListStyleOption() + : rect() + , font() + , fontMetrics(QFont()) + , palette() + , padding(-1) + , horizontalMargin(-1) + , verticalMargin(-1) + , iconSize(-1) + , extendedSelectionRegion(false) + , maxTextLines(0) + , maxTextWidth(0) { } @@ -26,22 +25,14 @@ KItemListStyleOption::~KItemListStyleOption() { } -bool KItemListStyleOption::operator==(const KItemListStyleOption& other) const +bool KItemListStyleOption::operator==(const KItemListStyleOption &other) const { - return rect == other.rect - && font == other.font - && fontMetrics == other.fontMetrics - && palette == other.palette - && padding == other.padding - && horizontalMargin == other.horizontalMargin - && verticalMargin == other.verticalMargin - && iconSize == other.iconSize - && extendedSelectionRegion == other.extendedSelectionRegion - && maxTextLines == other.maxTextLines - && maxTextWidth == other.maxTextWidth; + return rect == other.rect && font == other.font && fontMetrics == other.fontMetrics && palette == other.palette && padding == other.padding + && horizontalMargin == other.horizontalMargin && verticalMargin == other.verticalMargin && iconSize == other.iconSize + && extendedSelectionRegion == other.extendedSelectionRegion && maxTextLines == other.maxTextLines && maxTextWidth == other.maxTextWidth; } -bool KItemListStyleOption::operator!=(const KItemListStyleOption& other) const +bool KItemListStyleOption::operator!=(const KItemListStyleOption &other) const { return !(*this == other); } diff --git a/src/kitemviews/kitemliststyleoption.h b/src/kitemviews/kitemliststyleoption.h index 62e462a5dc..49dcc53c54 100644 --- a/src/kitemviews/kitemliststyleoption.h +++ b/src/kitemviews/kitemliststyleoption.h @@ -32,9 +32,7 @@ public: int maxTextLines; int maxTextWidth; - bool operator==(const KItemListStyleOption& other) const; - bool operator!=(const KItemListStyleOption& other) const; + bool operator==(const KItemListStyleOption &other) const; + bool operator!=(const KItemListStyleOption &other) const; }; #endif - - diff --git a/src/kitemviews/kitemlistview.cpp b/src/kitemviews/kitemlistview.cpp index 543be65182..d9455ce9e2 100644 --- a/src/kitemviews/kitemlistview.cpp +++ b/src/kitemviews/kitemlistview.cpp @@ -29,29 +29,29 @@ #include #include +namespace +{ +// Time in ms until reaching the autoscroll margin triggers +// an initial autoscrolling +const int InitialAutoScrollDelay = 700; -namespace { - // Time in ms until reaching the autoscroll margin triggers - // an initial autoscrolling - const int InitialAutoScrollDelay = 700; +// Delay in ms for triggering the next autoscroll +const int RepeatingAutoScrollDelay = 1000 / 60; - // Delay in ms for triggering the next autoscroll - const int RepeatingAutoScrollDelay = 1000 / 60; +// Copied from the Kirigami.Units.shortDuration +const int RubberFadeSpeed = 150; - // Copied from the Kirigami.Units.shortDuration - const int RubberFadeSpeed = 150; - - const char* RubberPropertyName = "_kitemviews_rubberBandPosition"; +const char *RubberPropertyName = "_kitemviews_rubberBandPosition"; } #ifndef QT_NO_ACCESSIBILITY -QAccessibleInterface* accessibleInterfaceFactory(const QString& key, QObject* object) +QAccessibleInterface *accessibleInterfaceFactory(const QString &key, QObject *object) { Q_UNUSED(key) - if (KItemListContainer* container = qobject_cast(object)) { + if (KItemListContainer *container = qobject_cast(object)) { return new KItemListContainerAccessible(container); - } else if (KItemListView* view = qobject_cast(object)) { + } else if (KItemListView *view = qobject_cast(object)) { return new KItemListViewAccessible(view); } @@ -59,44 +59,44 @@ QAccessibleInterface* accessibleInterfaceFactory(const QString& key, QObject* ob } #endif -KItemListView::KItemListView(QGraphicsWidget* parent) : - QGraphicsWidget(parent), - m_enabledSelectionToggles(false), - m_grouped(false), - m_highlightEntireRow(false), - m_alternateBackgrounds(false), - m_supportsItemExpanding(false), - m_editingRole(false), - m_activeTransactions(0), - m_endTransactionAnimationHint(Animation), - m_itemSize(), - m_controller(nullptr), - m_model(nullptr), - m_visibleRoles(), - m_widgetCreator(nullptr), - m_groupHeaderCreator(nullptr), - m_styleOption(), - m_visibleItems(), - m_visibleGroups(), - m_visibleCells(), - m_scrollBarExtent(0), - m_layouter(nullptr), - m_animation(nullptr), - m_oldScrollOffset(0), - m_oldMaximumScrollOffset(0), - m_oldItemOffset(0), - m_oldMaximumItemOffset(0), - m_skipAutoScrollForRubberBand(false), - m_rubberBand(nullptr), - m_tapAndHoldIndicator(nullptr), - m_mousePos(), - m_autoScrollIncrement(0), - m_autoScrollTimer(nullptr), - m_header(nullptr), - m_headerWidget(nullptr), - m_indicatorAnimation(nullptr), - m_dropIndicator(), - m_sizeHintResolver(nullptr) +KItemListView::KItemListView(QGraphicsWidget *parent) + : QGraphicsWidget(parent) + , m_enabledSelectionToggles(false) + , m_grouped(false) + , m_highlightEntireRow(false) + , m_alternateBackgrounds(false) + , m_supportsItemExpanding(false) + , m_editingRole(false) + , m_activeTransactions(0) + , m_endTransactionAnimationHint(Animation) + , m_itemSize() + , m_controller(nullptr) + , m_model(nullptr) + , m_visibleRoles() + , m_widgetCreator(nullptr) + , m_groupHeaderCreator(nullptr) + , m_styleOption() + , m_visibleItems() + , m_visibleGroups() + , m_visibleCells() + , m_scrollBarExtent(0) + , m_layouter(nullptr) + , m_animation(nullptr) + , m_oldScrollOffset(0) + , m_oldMaximumScrollOffset(0) + , m_oldItemOffset(0) + , m_oldMaximumItemOffset(0) + , m_skipAutoScrollForRubberBand(false) + , m_rubberBand(nullptr) + , m_tapAndHoldIndicator(nullptr) + , m_mousePos() + , m_autoScrollIncrement(0) + , m_autoScrollTimer(nullptr) + , m_header(nullptr) + , m_headerWidget(nullptr) + , m_indicatorAnimation(nullptr) + , m_dropIndicator() + , m_sizeHintResolver(nullptr) { setAcceptHoverEvents(true); setAcceptTouchEvents(true); @@ -106,8 +106,7 @@ KItemListView::KItemListView(QGraphicsWidget* parent) : m_layouter = new KItemListViewLayouter(m_sizeHintResolver, this); m_animation = new KItemListViewAnimation(this); - connect(m_animation, &KItemListViewAnimation::finished, - this, &KItemListView::slotAnimationFinished); + connect(m_animation, &KItemListViewAnimation::finished, this, &KItemListView::slotAnimationFinished); m_rubberBand = new KItemListRubberBand(this); connect(m_rubberBand, &KItemListRubberBand::activationChanged, this, &KItemListView::slotRubberBandActivationChanged); @@ -137,7 +136,6 @@ KItemListView::KItemListView(QGraphicsWidget* parent) : #ifndef QT_NO_ACCESSIBILITY QAccessible::installFactory(accessibleInterfaceFactory); #endif - } KItemListView::~KItemListView() @@ -218,7 +216,7 @@ int KItemListView::maximumVisibleItems() const return m_layouter->maximumVisibleItems(); } -void KItemListView::setVisibleRoles(const QList& roles) +void KItemListView::setVisibleRoles(const QList &roles) { const QList previousRoles = m_visibleRoles; m_visibleRoles = roles; @@ -233,7 +231,7 @@ void KItemListView::setVisibleRoles(const QList& roles) if (!m_headerWidget->automaticColumnResizing()) { // The column-width of new roles are still 0. Apply the preferred // column-width as default with. - for (const QByteArray& role : qAsConst(m_visibleRoles)) { + for (const QByteArray &role : qAsConst(m_visibleRoles)) { if (m_headerWidget->columnWidth(role) == 0) { const qreal width = m_headerWidget->preferredColumnWidth(role); m_headerWidget->setColumnWidth(role, width); @@ -244,14 +242,13 @@ void KItemListView::setVisibleRoles(const QList& roles) } } - const bool alternateBackgroundsChanged = m_itemSize.isEmpty() && - ((roles.count() > 1 && previousRoles.count() <= 1) || - (roles.count() <= 1 && previousRoles.count() > 1)); + const bool alternateBackgroundsChanged = + m_itemSize.isEmpty() && ((roles.count() > 1 && previousRoles.count() <= 1) || (roles.count() <= 1 && previousRoles.count() > 1)); - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); - KItemListWidget* widget = it.value(); + KItemListWidget *widget = it.value(); widget->setVisibleRoles(roles); if (alternateBackgroundsChanged) { updateAlternateBackgroundForWidget(widget); @@ -289,7 +286,7 @@ void KItemListView::setEnabledSelectionToggles(bool enabled) if (m_enabledSelectionToggles != enabled) { m_enabledSelectionToggles = enabled; - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); it.value()->setEnabledSelectionToggle(enabled); @@ -302,23 +299,23 @@ bool KItemListView::enabledSelectionToggles() const return m_enabledSelectionToggles; } -KItemListController* KItemListView::controller() const +KItemListController *KItemListView::controller() const { return m_controller; } -KItemModelBase* KItemListView::model() const +KItemModelBase *KItemListView::model() const { return m_model; } -void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator) +void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase *widgetCreator) { delete m_widgetCreator; m_widgetCreator = widgetCreator; } -KItemListWidgetCreatorBase* KItemListView::widgetCreator() const +KItemListWidgetCreatorBase *KItemListView::widgetCreator() const { if (!m_widgetCreator) { m_widgetCreator = defaultWidgetCreator(); @@ -326,13 +323,13 @@ KItemListWidgetCreatorBase* KItemListView::widgetCreator() const return m_widgetCreator; } -void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator) +void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase *groupHeaderCreator) { delete m_groupHeaderCreator; m_groupHeaderCreator = groupHeaderCreator; } -KItemListGroupHeaderCreatorBase* KItemListView::groupHeaderCreator() const +KItemListGroupHeaderCreatorBase *KItemListView::groupHeaderCreator() const { if (!m_groupHeaderCreator) { m_groupHeaderCreator = defaultGroupHeaderCreator(); @@ -345,12 +342,12 @@ QSizeF KItemListView::itemSize() const return m_itemSize; } -const KItemListStyleOption& KItemListView::styleOption() const +const KItemListStyleOption &KItemListView::styleOption() const { return m_styleOption; } -void KItemListView::setGeometry(const QRectF& rect) +void KItemListView::setGeometry(const QRectF &rect) { QGraphicsWidget::setGeometry(rect); @@ -365,8 +362,7 @@ void KItemListView::setGeometry(const QRectF& rect) applyAutomaticColumnWidths(); } else { const qreal requiredWidth = columnWidthsSum(); - const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth), - m_itemSize.height()); + const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth), m_itemSize.height()); m_layouter->setItemSize(dynamicItemSize); } } @@ -386,13 +382,13 @@ qreal KItemListView::verticalPageStep() const return size().height() - headerHeight; } -std::optional KItemListView::itemAt(const QPointF& pos) const +std::optional KItemListView::itemAt(const QPointF &pos) const { - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); - const KItemListWidget* widget = it.value(); + const KItemListWidget *widget = it.value(); const QPointF mappedPos = widget->mapFromItem(this, pos); if (widget->contains(mappedPos) || widget->selectionRect().contains(mappedPos)) { return it.key(); @@ -402,13 +398,13 @@ std::optional KItemListView::itemAt(const QPointF& pos) const return std::nullopt; } -bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const +bool KItemListView::isAboveSelectionToggle(int index, const QPointF &pos) const { if (!m_enabledSelectionToggles) { return false; } - const KItemListWidget* widget = m_visibleItems.value(index); + const KItemListWidget *widget = m_visibleItems.value(index); if (widget) { const QRectF selectionToggleRect = widget->selectionToggleRect(); if (!selectionToggleRect.isEmpty()) { @@ -419,9 +415,9 @@ bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const return false; } -bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const +bool KItemListView::isAboveExpansionToggle(int index, const QPointF &pos) const { - const KItemListWidget* widget = m_visibleItems.value(index); + const KItemListWidget *widget = m_visibleItems.value(index); if (widget) { const QRectF expansionToggleRect = widget->expansionToggleRect(); if (!expansionToggleRect.isEmpty()) { @@ -434,7 +430,7 @@ bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const bool KItemListView::isAboveText(int index, const QPointF &pos) const { - const KItemListWidget* widget = m_visibleItems.value(index); + const KItemListWidget *widget = m_visibleItems.value(index); if (widget) { const QRectF &textRect = widget->textRect(); if (!textRect.isEmpty()) { @@ -455,7 +451,7 @@ int KItemListView::lastVisibleIndex() const return m_layouter->lastVisibleIndex(); } -void KItemListView::calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint) const +void KItemListView::calculateItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint) const { widgetCreator()->calculateItemSizeHints(logicalHeightHints, logicalWidthHint, this); } @@ -509,7 +505,7 @@ QRectF KItemListView::itemContextRect(int index) const { QRectF contextRect; - const KItemListWidget* widget = m_visibleItems.value(index); + const KItemListWidget *widget = m_visibleItems.value(index); if (widget) { contextRect = widget->iconRect() | widget->textRect(); contextRect.translate(itemRect(index).topLeft()); @@ -533,8 +529,7 @@ void KItemListView::scrollToItem(int index) QRectF currentRect = itemRect(index); // Fix for Bug 311099 - View the underscore when using Ctrl + PagDown - currentRect.adjust(-m_styleOption.horizontalMargin, -m_styleOption.verticalMargin, - m_styleOption.horizontalMargin, m_styleOption.verticalMargin); + currentRect.adjust(-m_styleOption.horizontalMargin, -m_styleOption.verticalMargin, m_styleOption.horizontalMargin, m_styleOption.verticalMargin); if (!viewGeometry.contains(currentRect)) { qreal newOffset = scrollOffset(); @@ -593,8 +588,7 @@ void KItemListView::setHeaderVisible(bool visible) { if (visible && !m_headerWidget->isVisible()) { QStyleOptionHeader option; - const QSize headerSize = style()->sizeFromContents(QStyle::CT_HeaderSection, - &option, QSize()); + const QSize headerSize = style()->sizeFromContents(QStyle::CT_HeaderSection, &option, QSize()); m_headerWidget->setPos(0, 0); m_headerWidget->resize(size().width(), headerSize.height()); @@ -602,30 +596,20 @@ void KItemListView::setHeaderVisible(bool visible) m_headerWidget->setColumns(m_visibleRoles); m_headerWidget->setZValue(1); - connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, - this, &KItemListView::slotHeaderColumnWidthChanged); - connect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, - this, &KItemListView::slotSidePaddingChanged); - connect(m_headerWidget, &KItemListHeaderWidget::columnMoved, - this, &KItemListView::slotHeaderColumnMoved); - connect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged, - this, &KItemListView::sortOrderChanged); - connect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged, - this, &KItemListView::sortRoleChanged); + connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, this, &KItemListView::slotHeaderColumnWidthChanged); + connect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, this, &KItemListView::slotSidePaddingChanged); + connect(m_headerWidget, &KItemListHeaderWidget::columnMoved, this, &KItemListView::slotHeaderColumnMoved); + connect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged, this, &KItemListView::sortOrderChanged); + connect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged, this, &KItemListView::sortRoleChanged); m_layouter->setHeaderHeight(headerSize.height()); m_headerWidget->setVisible(true); } else if (!visible && m_headerWidget->isVisible()) { - disconnect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, - this, &KItemListView::slotHeaderColumnWidthChanged); - disconnect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, - this, &KItemListView::slotSidePaddingChanged); - disconnect(m_headerWidget, &KItemListHeaderWidget::columnMoved, - this, &KItemListView::slotHeaderColumnMoved); - disconnect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged, - this, &KItemListView::sortOrderChanged); - disconnect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged, - this, &KItemListView::sortRoleChanged); + disconnect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, this, &KItemListView::slotHeaderColumnWidthChanged); + disconnect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, this, &KItemListView::slotSidePaddingChanged); + disconnect(m_headerWidget, &KItemListHeaderWidget::columnMoved, this, &KItemListView::slotHeaderColumnMoved); + disconnect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged, this, &KItemListView::sortOrderChanged); + disconnect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged, this, &KItemListView::sortRoleChanged); m_layouter->setHeaderHeight(0); m_headerWidget->setVisible(false); @@ -637,18 +621,18 @@ bool KItemListView::isHeaderVisible() const return m_headerWidget->isVisible(); } -KItemListHeader* KItemListView::header() const +KItemListHeader *KItemListView::header() const { return m_header; } -QPixmap KItemListView::createDragPixmap(const KItemSet& indexes) const +QPixmap KItemListView::createDragPixmap(const KItemSet &indexes) const { QPixmap pixmap; if (indexes.count() == 1) { - KItemListWidget* item = m_visibleItems.value(indexes.first()); - QGraphicsView* graphicsView = scene()->views()[0]; + KItemListWidget *item = m_visibleItems.value(indexes.first()); + QGraphicsView *graphicsView = scene()->views()[0]; if (item && graphicsView) { pixmap = item->createDragPixmap(nullptr, graphicsView); } @@ -661,9 +645,9 @@ QPixmap KItemListView::createDragPixmap(const KItemSet& indexes) const return pixmap; } -void KItemListView::editRole(int index, const QByteArray& role) +void KItemListView::editRole(int index, const QByteArray &role) { - KStandardItemListWidget* widget = qobject_cast(m_visibleItems.value(index)); + KStandardItemListWidget *widget = qobject_cast(m_visibleItems.value(index)); if (!widget || m_editingRole) { return; } @@ -671,16 +655,13 @@ void KItemListView::editRole(int index, const QByteArray& role) m_editingRole = true; widget->setEditedRole(role); - connect(widget, &KItemListWidget::roleEditingCanceled, - this, &KItemListView::slotRoleEditingCanceled); - connect(widget, &KItemListWidget::roleEditingFinished, - this, &KItemListView::slotRoleEditingFinished); + connect(widget, &KItemListWidget::roleEditingCanceled, this, &KItemListView::slotRoleEditingCanceled); + connect(widget, &KItemListWidget::roleEditingFinished, this, &KItemListView::slotRoleEditingFinished); - connect(this, &KItemListView::scrollOffsetChanged, - widget, &KStandardItemListWidget::finishRoleEditing); + connect(this, &KItemListView::scrollOffsetChanged, widget, &KStandardItemListWidget::finishRoleEditing); } -void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KItemListView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QGraphicsWidget::paint(painter, option, widget); @@ -709,8 +690,7 @@ void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* opt } if (m_rubberBand->isActive()) { - QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), - m_rubberBand->endPosition()).normalized(); + QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), m_rubberBand->endPosition()).normalized(); const QPointF topLeft = rubberBandRect.topLeft(); if (scrollOrientation() == Qt::Vertical) { @@ -729,8 +709,8 @@ void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* opt if (m_tapAndHoldIndicator->isActive()) { const QPointF indicatorSize = m_tapAndHoldIndicator->endPosition(); - const QRectF rubberBandRect = QRectF(m_tapAndHoldIndicator->startPosition() - indicatorSize, - (m_tapAndHoldIndicator->startPosition()) + indicatorSize).normalized(); + const QRectF rubberBandRect = + QRectF(m_tapAndHoldIndicator->startPosition() - indicatorSize, (m_tapAndHoldIndicator->startPosition()) + indicatorSize).normalized(); QStyleOptionRubberBand opt; initStyleOption(&opt); opt.shape = QRubberBand::Rectangle; @@ -766,7 +746,7 @@ QVariant KItemListView::itemChange(GraphicsItemChange change, const QVariant &va return QGraphicsItem::itemChange(change, value); } -void KItemListView::setItemSize(const QSizeF& size) +void KItemListView::setItemSize(const QSizeF &size) { const QSizeF previousSize = m_itemSize; if (size == previousSize) { @@ -776,13 +756,9 @@ void KItemListView::setItemSize(const QSizeF& size) // Skip animations when the number of rows or columns // are changed in the grid layout. Although the animation // engine can handle this usecase, it looks obtrusive. - const bool animate = !changesItemGridLayout(m_layouter->size(), - size, - m_layouter->itemMargin()); + const bool animate = !changesItemGridLayout(m_layouter->size(), size, m_layouter->itemMargin()); - const bool alternateBackgroundsChanged = m_alternateBackgrounds && - (( m_itemSize.isEmpty() && !size.isEmpty()) || - (!m_itemSize.isEmpty() && size.isEmpty())); + const bool alternateBackgroundsChanged = m_alternateBackgrounds && ((m_itemSize.isEmpty() && !size.isEmpty()) || (!m_itemSize.isEmpty() && size.isEmpty())); m_itemSize = size; @@ -812,7 +788,7 @@ void KItemListView::setItemSize(const QSizeF& size) onItemSizeChanged(size, previousSize); } -void KItemListView::setStyleOption(const KItemListStyleOption& option) +void KItemListView::setStyleOption(const KItemListStyleOption &option) { if (m_styleOption == option) { return; @@ -827,9 +803,7 @@ void KItemListView::setStyleOption(const KItemListStyleOption& option) // Skip animations when the number of rows or columns // are changed in the grid layout. Although the animation // engine can handle this usecase, it looks obtrusive. - animate = !changesItemGridLayout(m_layouter->size(), - m_layouter->itemSize(), - margin); + animate = !changesItemGridLayout(m_layouter->size(), m_layouter->itemSize(), margin); m_layouter->setItemMargin(margin); } @@ -837,14 +811,13 @@ void KItemListView::setStyleOption(const KItemListStyleOption& option) updateGroupHeaderHeight(); } - if (animate && - (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) { + if (animate && (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) { // Animating a change of the maximum text size just results in expensive // temporary eliding and clipping operations and does not look good visually. animate = false; } - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); it.value()->setStyleOption(option); @@ -873,13 +846,12 @@ void KItemListView::setScrollOrientation(Qt::Orientation orientation) m_sizeHintResolver->clearCache(); if (m_grouped) { - QMutableHashIterator it (m_visibleGroups); + QMutableHashIterator it(m_visibleGroups); while (it.hasNext()) { it.next(); it.value()->setScrollOrientation(orientation); } updateGroupHeaderHeight(); - } doLayout(NoAnimation); @@ -893,34 +865,34 @@ Qt::Orientation KItemListView::scrollOrientation() const return m_layouter->scrollOrientation(); } -KItemListWidgetCreatorBase* KItemListView::defaultWidgetCreator() const +KItemListWidgetCreatorBase *KItemListView::defaultWidgetCreator() const { return nullptr; } -KItemListGroupHeaderCreatorBase* KItemListView::defaultGroupHeaderCreator() const +KItemListGroupHeaderCreatorBase *KItemListView::defaultGroupHeaderCreator() const { return nullptr; } -void KItemListView::initializeItemListWidget(KItemListWidget* item) +void KItemListView::initializeItemListWidget(KItemListWidget *item) { Q_UNUSED(item) } -bool KItemListView::itemSizeHintUpdateRequired(const QSet& changedRoles) const +bool KItemListView::itemSizeHintUpdateRequired(const QSet &changedRoles) const { Q_UNUSED(changedRoles) return true; } -void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous) +void KItemListView::onControllerChanged(KItemListController *current, KItemListController *previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous) +void KItemListView::onModelChanged(KItemModelBase *current, KItemModelBase *previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -932,7 +904,7 @@ void KItemListView::onScrollOrientationChanged(Qt::Orientation current, Qt::Orie Q_UNUSED(previous) } -void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous) +void KItemListView::onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -944,13 +916,13 @@ void KItemListView::onScrollOffsetChanged(qreal current, qreal previous) Q_UNUSED(previous) } -void KItemListView::onVisibleRolesChanged(const QList& current, const QList& previous) +void KItemListView::onVisibleRolesChanged(const QList ¤t, const QList &previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) +void KItemListView::onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -974,7 +946,7 @@ void KItemListView::onTransactionEnd() { } -bool KItemListView::event(QEvent* event) +bool KItemListView::event(QEvent *event) { switch (event->type()) { case QEvent::PaletteChange: @@ -996,13 +968,13 @@ bool KItemListView::event(QEvent* event) return QGraphicsWidget::event(event); } -void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event) +void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent *event) { m_mousePos = transform().map(event->pos()); event->accept(); } -void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event) +void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { QGraphicsWidget::mouseMoveEvent(event); @@ -1012,13 +984,13 @@ void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event) } } -void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event) +void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent *event) { event->setAccepted(true); setAutoScroll(true); } -void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent* event) +void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event) { QGraphicsWidget::dragMoveEvent(event); @@ -1028,19 +1000,19 @@ void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent* event) } } -void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent* event) +void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) { QGraphicsWidget::dragLeaveEvent(event); setAutoScroll(false); } -void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event) +void KItemListView::dropEvent(QGraphicsSceneDragDropEvent *event) { QGraphicsWidget::dropEvent(event); setAutoScroll(false); } -QList KItemListView::visibleItemListWidgets() const +QList KItemListView::visibleItemListWidgets() const { return m_visibleItems.values(); } @@ -1066,7 +1038,7 @@ void KItemListView::updatePalette() } } -void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) +void KItemListView::slotItemsInserted(const KItemRangeList &itemRanges) { if (m_itemSize.isEmpty()) { updatePreferredColumnWidths(itemRanges); @@ -1082,7 +1054,7 @@ void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) m_sizeHintResolver->itemsInserted(itemRanges); int previouslyInsertedCount = 0; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { // range.index is related to the model before anything has been inserted. // As in each loop the current item-range gets inserted the index must // be increased by the already previously inserted items. @@ -1096,7 +1068,7 @@ void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) // Determine which visible items must be moved QList itemsToMove; - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); const int visibleItemIndex = it.key(); @@ -1110,7 +1082,7 @@ void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) // from the highest index to the lowest index to prevent overlaps when setting the new index. std::sort(itemsToMove.begin(), itemsToMove.end()); for (int i = itemsToMove.count() - 1; i >= 0; --i) { - KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]); + KItemListWidget *widget = m_visibleItems.value(itemsToMove[i]); Q_ASSERT(widget); const int newIndex = widget->index() + count; if (hasMultipleRanges) { @@ -1126,8 +1098,8 @@ void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) // the size of the layouter will be decreased before calling doLayout(): This prevents // an unnecessary temporary animation due to the geometry change of the inserted scrollbar. const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical); - const bool decreaseLayouterSize = ( verticalScrollOrientation && maximumScrollOffset() > size().height()) || - (!verticalScrollOrientation && maximumScrollOffset() > size().width()); + const bool decreaseLayouterSize = (verticalScrollOrientation && maximumScrollOffset() > size().height()) + || (!verticalScrollOrientation && maximumScrollOffset() > size().width()); if (decreaseLayouterSize) { const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent); @@ -1175,7 +1147,7 @@ void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges) } } -void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges) +void KItemListView::slotItemsRemoved(const KItemRangeList &itemRanges) { if (m_itemSize.isEmpty()) { // Don't pass the item-range: The preferred column-widths of @@ -1193,7 +1165,7 @@ void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges) m_sizeHintResolver->itemsRemoved(itemRanges); for (int i = itemRanges.count() - 1; i >= 0; --i) { - const KItemRange& range = itemRanges[i]; + const KItemRange &range = itemRanges[i]; const int index = range.index; const int count = range.count; if (index < 0 || count <= 0) { @@ -1211,7 +1183,7 @@ void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges) // Iterate over a const copy because the container is mutated within the loop // directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374) const auto visibleItems = m_visibleItems; - for (KItemListWidget* widget : visibleItems) { + for (KItemListWidget *widget : visibleItems) { const int i = widget->index(); if (i < firstRemovedIndex) { continue; @@ -1248,7 +1220,7 @@ void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges) // order to prevent overlaps when setting the new index. std::sort(itemsToMove.begin(), itemsToMove.end()); for (int i : qAsConst(itemsToMove)) { - KItemListWidget* widget = m_visibleItems.value(i); + KItemListWidget *widget = m_visibleItems.value(i); Q_ASSERT(widget); const int newIndex = i - count; if (hasMultipleRanges) { @@ -1293,7 +1265,7 @@ void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges) } } -void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList& movedToIndexes) +void KItemListView::slotItemsMoved(const KItemRange &itemRange, const QList &movedToIndexes) { m_sizeHintResolver->itemsMoved(itemRange, movedToIndexes); m_layouter->markAsDirty(); @@ -1306,7 +1278,7 @@ void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1); for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) { - KItemListWidget* widget = m_visibleItems.value(index); + KItemListWidget *widget = m_visibleItems.value(index); if (widget) { updateWidgetProperties(widget, index); initializeItemListWidget(widget); @@ -1317,15 +1289,14 @@ void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList updateSiblingsInformation(); } -void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges, - const QSet& roles) +void KItemListView::slotItemsChanged(const KItemRangeList &itemRanges, const QSet &roles) { const bool updateSizeHints = itemSizeHintUpdateRequired(roles); if (updateSizeHints && m_itemSize.isEmpty()) { updatePreferredColumnWidths(itemRanges); } - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { const int index = itemRange.index; const int count = itemRange.count; @@ -1337,7 +1308,7 @@ void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges, // Apply the changed roles to the visible item-widgets const int lastIndex = index + count - 1; for (int i = index; i <= lastIndex; ++i) { - KItemListWidget* widget = m_visibleItems.value(i); + KItemListWidget *widget = m_visibleItems.value(i); if (widget) { widget->setData(m_model->data(i), roles); } @@ -1377,7 +1348,7 @@ void KItemListView::slotGroupedSortingChanged(bool current) // Clear all visible headers. Note that the QHashIterator takes a copy of // m_visibleGroups. Therefore, it remains valid even if items are removed // from m_visibleGroups in recycleGroupHeaderForWidget(). - QHashIterator it(m_visibleGroups); + QHashIterator it(m_visibleGroups); while (it.hasNext()) { it.next(); recycleGroupHeaderForWidget(it.key()); @@ -1405,7 +1376,7 @@ void KItemListView::slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder pr } } -void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous) +void KItemListView::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -1422,12 +1393,12 @@ void KItemListView::slotCurrentChanged(int current, int previous) // In SingleSelection mode (e.g., in the Places Panel), the current item is // always the selected item. It is not necessary to highlight the current item then. if (m_controller->selectionBehavior() != KItemListController::SingleSelection) { - KItemListWidget* previousWidget = m_visibleItems.value(previous, nullptr); + KItemListWidget *previousWidget = m_visibleItems.value(previous, nullptr); if (previousWidget) { previousWidget->setCurrent(false); } - KItemListWidget* currentWidget = m_visibleItems.value(current, nullptr); + KItemListWidget *currentWidget = m_visibleItems.value(current, nullptr); if (currentWidget) { currentWidget->setCurrent(true); } @@ -1438,23 +1409,22 @@ void KItemListView::slotCurrentChanged(int current, int previous) QAccessible::updateAccessibility(&ev); } -void KItemListView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous) +void KItemListView::slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous) { Q_UNUSED(previous) - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); const int index = it.key(); - KItemListWidget* widget = it.value(); + KItemListWidget *widget = it.value(); widget->setSelected(current.contains(index)); } } -void KItemListView::slotAnimationFinished(QGraphicsWidget* widget, - KItemListViewAnimation::AnimationType type) +void KItemListView::slotAnimationFinished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type) { - KItemListWidget* itemListWidget = qobject_cast(widget); + KItemListWidget *itemListWidget = qobject_cast(widget); Q_ASSERT(itemListWidget); if (type == KItemListViewAnimation::DeleteAnimation) { @@ -1470,8 +1440,7 @@ void KItemListView::slotAnimationFinished(QGraphicsWidget* widget, widgetCreator()->recycle(itemListWidget); } else { const int index = itemListWidget->index(); - const bool invisible = (index < m_layouter->firstVisibleIndex()) || - (index > m_layouter->lastVisibleIndex()); + const bool invisible = (index < m_layouter->firstVisibleIndex()) || (index > m_layouter->lastVisibleIndex()); if (invisible && !m_animation->isStarted(itemListWidget)) { recycleWidget(itemListWidget); } @@ -1490,8 +1459,7 @@ void KItemListView::slotRubberBandActivationChanged(bool active) connect(m_rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListView::slotRubberBandPosChanged); m_skipAutoScrollForRubberBand = true; } else { - QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), - m_rubberBand->endPosition()).normalized(); + QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), m_rubberBand->endPosition()).normalized(); auto animation = new QVariantAnimation(this); animation->setStartValue(1.0); @@ -1504,7 +1472,7 @@ void KItemListView::slotRubberBandActivationChanged(bool active) curve.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0)); animation->setEasingCurve(curve); - connect(animation, &QVariantAnimation::valueChanged, this, [=](const QVariant&) { + connect(animation, &QVariantAnimation::valueChanged, this, [=](const QVariant &) { update(); }); connect(animation, &QVariantAnimation::finished, this, [=]() { @@ -1522,9 +1490,7 @@ void KItemListView::slotRubberBandActivationChanged(bool active) update(); } -void KItemListView::slotHeaderColumnWidthChanged(const QByteArray& role, - qreal currentWidth, - qreal previousWidth) +void KItemListView::slotHeaderColumnWidthChanged(const QByteArray &role, qreal currentWidth, qreal previousWidth) { Q_UNUSED(role) Q_UNUSED(currentWidth) @@ -1545,9 +1511,7 @@ void KItemListView::slotSidePaddingChanged(qreal width) doLayout(NoAnimation); } -void KItemListView::slotHeaderColumnMoved(const QByteArray& role, - int currentIndex, - int previousIndex) +void KItemListView::slotHeaderColumnMoved(const QByteArray &role, int currentIndex, int previousIndex) { Q_ASSERT(m_visibleRoles[previousIndex] == role); @@ -1597,9 +1561,8 @@ void KItemListView::triggerAutoScrolling() // an autoscrolling. const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small - const qreal diff = (scrollOrientation() == Qt::Vertical) - ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y() - : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x(); + const qreal diff = (scrollOrientation() == Qt::Vertical) ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y() + : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x(); if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) { // The rubberband direction is different from the scroll direction (e.g. the rubberband has // been moved up although the autoscroll direction might be down) @@ -1623,14 +1586,14 @@ void KItemListView::triggerAutoScrolling() void KItemListView::slotGeometryOfGroupHeaderParentChanged() { - KItemListWidget* widget = qobject_cast(sender()); + KItemListWidget *widget = qobject_cast(sender()); Q_ASSERT(widget); - KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget); + KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget); Q_ASSERT(groupHeader); updateGroupHeaderLayout(widget); } -void KItemListView::slotRoleEditingCanceled(int index, const QByteArray& role, const QVariant& value) +void KItemListView::slotRoleEditingCanceled(int index, const QByteArray &role, const QVariant &value) { disconnectRoleEditingSignals(index); @@ -1638,7 +1601,7 @@ void KItemListView::slotRoleEditingCanceled(int index, const QByteArray& role, c Q_EMIT roleEditingCanceled(index, role, value); } -void KItemListView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value) +void KItemListView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value) { disconnectRoleEditingSignals(index); @@ -1646,12 +1609,12 @@ void KItemListView::slotRoleEditingFinished(int index, const QByteArray& role, c Q_EMIT roleEditingFinished(index, role, value); } -void KItemListView::setController(KItemListController* controller) +void KItemListView::setController(KItemListController *controller) { if (m_controller != controller) { - KItemListController* previous = m_controller; + KItemListController *previous = m_controller; if (previous) { - KItemListSelectionManager* selectionManager = previous->selectionManager(); + KItemListSelectionManager *selectionManager = previous->selectionManager(); disconnect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged); disconnect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged); } @@ -1659,7 +1622,7 @@ void KItemListView::setController(KItemListController* controller) m_controller = controller; if (controller) { - KItemListSelectionManager* selectionManager = controller->selectionManager(); + KItemListSelectionManager *selectionManager = controller->selectionManager(); connect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged); connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged); } @@ -1668,31 +1631,23 @@ void KItemListView::setController(KItemListController* controller) } } -void KItemListView::setModel(KItemModelBase* model) +void KItemListView::setModel(KItemModelBase *model) { if (m_model == model) { return; } - KItemModelBase* previous = m_model; + KItemModelBase *previous = m_model; if (m_model) { - disconnect(m_model, &KItemModelBase::itemsChanged, - this, &KItemListView::slotItemsChanged); - disconnect(m_model, &KItemModelBase::itemsInserted, - this, &KItemListView::slotItemsInserted); - disconnect(m_model, &KItemModelBase::itemsRemoved, - this, &KItemListView::slotItemsRemoved); - disconnect(m_model, &KItemModelBase::itemsMoved, - this, &KItemListView::slotItemsMoved); - disconnect(m_model, &KItemModelBase::groupsChanged, - this, &KItemListView::slotGroupsChanged); - disconnect(m_model, &KItemModelBase::groupedSortingChanged, - this, &KItemListView::slotGroupedSortingChanged); - disconnect(m_model, &KItemModelBase::sortOrderChanged, - this, &KItemListView::slotSortOrderChanged); - disconnect(m_model, &KItemModelBase::sortRoleChanged, - this, &KItemListView::slotSortRoleChanged); + disconnect(m_model, &KItemModelBase::itemsChanged, this, &KItemListView::slotItemsChanged); + disconnect(m_model, &KItemModelBase::itemsInserted, this, &KItemListView::slotItemsInserted); + disconnect(m_model, &KItemModelBase::itemsRemoved, this, &KItemListView::slotItemsRemoved); + disconnect(m_model, &KItemModelBase::itemsMoved, this, &KItemListView::slotItemsMoved); + disconnect(m_model, &KItemModelBase::groupsChanged, this, &KItemListView::slotGroupsChanged); + disconnect(m_model, &KItemModelBase::groupedSortingChanged, this, &KItemListView::slotGroupedSortingChanged); + disconnect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListView::slotSortOrderChanged); + disconnect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListView::slotSortRoleChanged); m_sizeHintResolver->itemsRemoved(KItemRangeList() << KItemRange(0, m_model->count())); } @@ -1702,22 +1657,14 @@ void KItemListView::setModel(KItemModelBase* model) m_grouped = model->groupedSorting(); if (m_model) { - connect(m_model, &KItemModelBase::itemsChanged, - this, &KItemListView::slotItemsChanged); - connect(m_model, &KItemModelBase::itemsInserted, - this, &KItemListView::slotItemsInserted); - connect(m_model, &KItemModelBase::itemsRemoved, - this, &KItemListView::slotItemsRemoved); - connect(m_model, &KItemModelBase::itemsMoved, - this, &KItemListView::slotItemsMoved); - connect(m_model, &KItemModelBase::groupsChanged, - this, &KItemListView::slotGroupsChanged); - connect(m_model, &KItemModelBase::groupedSortingChanged, - this, &KItemListView::slotGroupedSortingChanged); - connect(m_model, &KItemModelBase::sortOrderChanged, - this, &KItemListView::slotSortOrderChanged); - connect(m_model, &KItemModelBase::sortRoleChanged, - this, &KItemListView::slotSortRoleChanged); + connect(m_model, &KItemModelBase::itemsChanged, this, &KItemListView::slotItemsChanged); + connect(m_model, &KItemModelBase::itemsInserted, this, &KItemListView::slotItemsInserted); + connect(m_model, &KItemModelBase::itemsRemoved, this, &KItemListView::slotItemsRemoved); + connect(m_model, &KItemModelBase::itemsMoved, this, &KItemListView::slotItemsMoved); + connect(m_model, &KItemModelBase::groupsChanged, this, &KItemListView::slotGroupsChanged); + connect(m_model, &KItemModelBase::groupedSortingChanged, this, &KItemListView::slotGroupedSortingChanged); + connect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListView::slotSortOrderChanged); + connect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListView::slotSortRoleChanged); const int itemCount = m_model->count(); if (itemCount > 0) { @@ -1728,7 +1675,7 @@ void KItemListView::setModel(KItemModelBase* model) onModelChanged(model, previous); } -KItemListRubberBand* KItemListView::rubberBand() const +KItemListRubberBand *KItemListView::rubberBand() const { return m_rubberBand; } @@ -1781,7 +1728,7 @@ void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int cha const QRectF itemBounds = m_layouter->itemRect(i); const QPointF newPos = itemBounds.topLeft(); - KItemListWidget* widget = m_visibleItems.value(i); + KItemListWidget *widget = m_visibleItems.value(i); if (!widget) { if (!reusableItems.isEmpty()) { // Reuse a KItemListWidget instance from an invisible item @@ -1805,8 +1752,7 @@ void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int cha const int previousIndex = i - changedCount; const QRectF itemRect = m_layouter->itemRect(previousIndex); if (itemRect.isEmpty()) { - const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical) - ? QPointF(0, size().height()) : QPointF(size().width(), 0); + const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical) ? QPointF(0, size().height()) : QPointF(size().width(), 0); widget->setPos(invisibleOldPos); } else { widget->setPos(itemRect.topLeft()); @@ -1825,7 +1771,7 @@ void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int cha if (animate) { if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) { - m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos); + m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos); applyNewPos = false; } @@ -1910,7 +1856,7 @@ void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int cha if (m_grouped) { // Update the layout of all visible group headers - QHashIterator it(m_visibleGroups); + QHashIterator it(m_visibleGroups); while (it.hasNext()) { it.next(); updateGroupHeaderLayout(it.key()); @@ -1920,9 +1866,7 @@ void KItemListView::doLayout(LayoutAnimationHint hint, int changedIndex, int cha emitOffsetChanges(); } -QList KItemListView::recycleInvisibleItems(int firstVisibleIndex, - int lastVisibleIndex, - LayoutAnimationHint hint) +QList KItemListView::recycleInvisibleItems(int firstVisibleIndex, int lastVisibleIndex, LayoutAnimationHint hint) { // Determine all items that are completely invisible and might be // reused for items that just got (at least partly) visible. If the @@ -1932,11 +1876,11 @@ QList KItemListView::recycleInvisibleItems(int firstVisibleIndex, QList items; - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); - KItemListWidget* widget = it.value(); + KItemListWidget *widget = it.value(); const int index = widget->index(); const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex); @@ -1961,7 +1905,7 @@ QList KItemListView::recycleInvisibleItems(int firstVisibleIndex, return items; } -bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos) +bool KItemListView::moveWidget(KItemListWidget *widget, const QPointF &newPos) { if (widget->pos() == newPos) { return false; @@ -2025,9 +1969,9 @@ void KItemListView::emitOffsetChanges() } } -KItemListWidget* KItemListView::createWidget(int index) +KItemListWidget *KItemListView::createWidget(int index) { - KItemListWidget* widget = widgetCreator()->create(this); + KItemListWidget *widget = widgetCreator()->create(this); widget->setFlag(QGraphicsItem::ItemStacksBehindParent); m_visibleItems.insert(index, widget); @@ -2037,7 +1981,7 @@ KItemListWidget* KItemListView::createWidget(int index) return widget; } -void KItemListView::recycleWidget(KItemListWidget* widget) +void KItemListView::recycleWidget(KItemListWidget *widget) { if (m_grouped) { recycleGroupHeaderForWidget(widget); @@ -2050,7 +1994,7 @@ void KItemListView::recycleWidget(KItemListWidget* widget) widgetCreator()->recycle(widget); } -void KItemListView::setWidgetIndex(KItemListWidget* widget, int index) +void KItemListView::setWidgetIndex(KItemListWidget *widget, int index) { const int oldIndex = widget->index(); m_visibleItems.remove(oldIndex); @@ -2062,7 +2006,7 @@ void KItemListView::setWidgetIndex(KItemListWidget* widget, int index) widget->setIndex(index); } -void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index) +void KItemListView::moveWidgetToIndex(KItemListWidget *widget, int index) { const int oldIndex = widget->index(); const Cell oldCell = m_visibleCells.value(oldIndex); @@ -2071,29 +2015,33 @@ void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index) const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index)); const bool vertical = (scrollOrientation() == Qt::Vertical); - const bool updateCell = (vertical && oldCell.row == newCell.row) || - (!vertical && oldCell.column == newCell.column); + const bool updateCell = (vertical && oldCell.row == newCell.row) || (!vertical && oldCell.column == newCell.column); if (updateCell) { m_visibleCells.insert(index, newCell); } } -void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType) +void KItemListView::setLayouterSize(const QSizeF &size, SizeType sizeType) { switch (sizeType) { - case LayouterSize: m_layouter->setSize(size); break; - case ItemSize: m_layouter->setItemSize(size); break; - default: break; + case LayouterSize: + m_layouter->setSize(size); + break; + case ItemSize: + m_layouter->setItemSize(size); + break; + default: + break; } } -void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index) +void KItemListView::updateWidgetProperties(KItemListWidget *widget, int index) { widget->setVisibleRoles(m_visibleRoles); updateWidgetColumnWidths(widget); widget->setStyleOption(m_styleOption); - const KItemListSelectionManager* selectionManager = m_controller->selectionManager(); + const KItemListSelectionManager *selectionManager = m_controller->selectionManager(); // In SingleSelection mode (e.g., in the Places Panel), the current item is // always the selected item. It is not necessary to highlight the current item then. @@ -2113,7 +2061,7 @@ void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index) } } -void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget) +void KItemListView::updateGroupHeaderForWidget(KItemListWidget *widget) { Q_ASSERT(m_grouped); @@ -2125,12 +2073,12 @@ void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget) return; } - const QList > groups = model()->groups(); + const QList> groups = model()->groups(); if (groups.isEmpty() || !groupHeaderCreator()) { return; } - KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget); + KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget); if (!groupHeader) { groupHeader = groupHeaderCreator()->create(this); groupHeader->setParentItem(widget); @@ -2150,9 +2098,9 @@ void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget) groupHeader->show(); } -void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget) +void KItemListView::updateGroupHeaderLayout(KItemListWidget *widget) { - KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget); + KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget); Q_ASSERT(groupHeader); const int index = widget->index(); @@ -2175,9 +2123,9 @@ void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget) } } -void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget) +void KItemListView::recycleGroupHeaderForWidget(KItemListWidget *widget) { - KItemListGroupHeader* header = m_visibleGroups.value(widget); + KItemListGroupHeader *header = m_visibleGroups.value(widget); if (header) { header->setParentItem(nullptr); groupHeaderCreator()->recycle(header); @@ -2191,7 +2139,7 @@ void KItemListView::updateVisibleGroupHeaders() Q_ASSERT(m_grouped); m_layouter->markAsDirty(); - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); updateGroupHeaderForWidget(it.value()); @@ -2202,7 +2150,7 @@ int KItemListView::groupIndexForItem(int index) const { Q_ASSERT(m_grouped); - const QList > groups = model()->groups(); + const QList> groups = model()->groups(); if (groups.isEmpty()) { return -1; } @@ -2230,14 +2178,14 @@ int KItemListView::groupIndexForItem(int index) const void KItemListView::updateAlternateBackgrounds() { - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); updateAlternateBackgroundForWidget(it.value()); } } -void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget) +void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget *widget) { bool enabled = useAlternateBackgrounds(); if (enabled) { @@ -2246,7 +2194,7 @@ void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget) if (m_grouped) { const int groupIndex = groupIndexForItem(index); if (groupIndex >= 0) { - const QList > groups = model()->groups(); + const QList> groups = model()->groups(); const int indexOfFirstGroupItem = groups[groupIndex].first; const int relativeIndex = index - indexOfFirstGroupItem; enabled = (relativeIndex & 0x1) > 0; @@ -2261,7 +2209,7 @@ bool KItemListView::useAlternateBackgrounds() const return m_alternateBackgrounds && m_itemSize.isEmpty(); } -QHash KItemListView::preferredColumnWidths(const KItemRangeList& itemRanges) const +QHash KItemListView::preferredColumnWidths(const KItemRangeList &itemRanges) const { QElapsedTimer timer; timer.start(); @@ -2271,9 +2219,9 @@ QHash KItemListView::preferredColumnWidths(const KItemRangeLi // Calculate the minimum width for each column that is required // to show the headline unclipped. const QFontMetricsF fontMetrics(m_headerWidget->font()); - const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin); + const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin); const int headerMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderMargin); - for (const QByteArray& visibleRole : qAsConst(m_visibleRoles)) { + for (const QByteArray &visibleRole : qAsConst(m_visibleRoles)) { const QString headerText = m_model->roleDescription(visibleRole); const qreal headerWidth = fontMetrics.horizontalAdvance(headerText) + gripMargin + headerMargin * 2; widths.insert(visibleRole, headerWidth); @@ -2281,15 +2229,15 @@ QHash KItemListView::preferredColumnWidths(const KItemRangeLi // Calculate the preferred column widths for each item and ignore values // smaller than the width for showing the headline unclipped. - const KItemListWidgetCreatorBase* creator = widgetCreator(); + const KItemListWidgetCreatorBase *creator = widgetCreator(); int calculatedItemCount = 0; bool maxTimeExceeded = false; - for (const KItemRange& itemRange : itemRanges) { + for (const KItemRange &itemRange : itemRanges) { const int startIndex = itemRange.index; const int endIndex = startIndex + itemRange.count - 1; for (int i = startIndex; i <= endIndex; ++i) { - for (const QByteArray& visibleRole : qAsConst(m_visibleRoles)) { + for (const QByteArray &visibleRole : qAsConst(m_visibleRoles)) { qreal maxWidth = widths.value(visibleRole, 0); const qreal width = creator->preferredRoleColumnWidth(visibleRole, i, this); maxWidth = qMax(width, maxWidth); @@ -2317,38 +2265,37 @@ void KItemListView::applyColumnWidthsFromHeader() { // Apply the new size to the layouter const qreal requiredWidth = columnWidthsSum() + m_headerWidget->sidePadding(); - const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth), - m_itemSize.height()); + const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth), m_itemSize.height()); m_layouter->setItemSize(dynamicItemSize); // Update the role sizes for all visible widgets - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); updateWidgetColumnWidths(it.value()); } } -void KItemListView::updateWidgetColumnWidths(KItemListWidget* widget) +void KItemListView::updateWidgetColumnWidths(KItemListWidget *widget) { - for (const QByteArray& role : qAsConst(m_visibleRoles)) { + for (const QByteArray &role : qAsConst(m_visibleRoles)) { widget->setColumnWidth(role, m_headerWidget->columnWidth(role)); } widget->setSidePadding(m_headerWidget->sidePadding()); } -void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges) +void KItemListView::updatePreferredColumnWidths(const KItemRangeList &itemRanges) { Q_ASSERT(m_itemSize.isEmpty()); const int itemCount = m_model->count(); int rangesItemCount = 0; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { rangesItemCount += range.count; } if (itemCount == rangesItemCount) { const QHash preferredWidths = preferredColumnWidths(itemRanges); - for (const QByteArray& role : qAsConst(m_visibleRoles)) { + for (const QByteArray &role : qAsConst(m_visibleRoles)) { m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role)); } } else { @@ -2362,7 +2309,7 @@ void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges QHashIterator it(updatedWidths); while (it.hasNext()) { it.next(); - const QByteArray& role = it.key(); + const QByteArray &role = it.key(); const qreal updatedWidth = it.value(); const qreal currentWidth = m_headerWidget->preferredColumnWidth(role); if (updatedWidth > currentWidth) { @@ -2403,7 +2350,7 @@ void KItemListView::applyAutomaticColumnWidths() // size does not use the available view-size the size of the // first role will get stretched. - for (const QByteArray& role : qAsConst(m_visibleRoles)) { + for (const QByteArray &role : qAsConst(m_visibleRoles)) { const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role); m_headerWidget->setColumnWidth(role, preferredWidth); } @@ -2414,7 +2361,7 @@ void KItemListView::applyAutomaticColumnWidths() qreal requiredWidth = columnWidthsSum() + m_headerWidget->sidePadding() + m_headerWidget->sidePadding(); // Adding the padding a second time so we have the same padding symmetrically on both sides of the view. - // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files. + // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files. const qreal availableWidth = size().width(); if (requiredWidth < availableWidth) { // Stretch the first column to use the whole remaining width @@ -2442,7 +2389,7 @@ void KItemListView::applyAutomaticColumnWidths() m_layouter->setItemSize(dynamicItemSize); // Update the role sizes for all visible widgets - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); updateWidgetColumnWidths(it.value()); @@ -2452,7 +2399,7 @@ void KItemListView::applyAutomaticColumnWidths() qreal KItemListView::columnWidthsSum() const { qreal widthsSum = 0; - for (const QByteArray& role : qAsConst(m_visibleRoles)) { + for (const QByteArray &role : qAsConst(m_visibleRoles)) { widthsSum += m_headerWidget->columnWidth(role); } return widthsSum; @@ -2463,9 +2410,7 @@ QRectF KItemListView::headerBoundaries() const return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF(); } -bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize, - const QSizeF& newItemSize, - const QSizeF& newItemMargin) const +bool KItemListView::changesItemGridLayout(const QSizeF &newGridSize, const QSizeF &newItemSize, const QSizeF &newItemMargin) const { if (newItemSize.isEmpty() || newGridSize.isEmpty()) { return false; @@ -2474,26 +2419,18 @@ bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize, if (m_layouter->scrollOrientation() == Qt::Vertical) { const qreal itemWidth = m_layouter->itemSize().width(); if (itemWidth > 0) { - const int newColumnCount = itemsPerSize(newGridSize.width(), - newItemSize.width(), - newItemMargin.width()); + const int newColumnCount = itemsPerSize(newGridSize.width(), newItemSize.width(), newItemMargin.width()); if (m_model->count() > newColumnCount) { - const int oldColumnCount = itemsPerSize(m_layouter->size().width(), - itemWidth, - m_layouter->itemMargin().width()); + const int oldColumnCount = itemsPerSize(m_layouter->size().width(), itemWidth, m_layouter->itemMargin().width()); return oldColumnCount != newColumnCount; } } } else { const qreal itemHeight = m_layouter->itemSize().height(); if (itemHeight > 0) { - const int newRowCount = itemsPerSize(newGridSize.height(), - newItemSize.height(), - newItemMargin.height()); + const int newRowCount = itemsPerSize(newGridSize.height(), newItemSize.height(), newItemMargin.height()); if (m_model->count() > newRowCount) { - const int oldRowCount = itemsPerSize(m_layouter->size().height(), - itemHeight, - m_layouter->itemMargin().height()); + const int oldRowCount = itemsPerSize(m_layouter->size().height(), itemHeight, m_layouter->itemMargin().height()); return oldRowCount != newRowCount; } } @@ -2514,15 +2451,13 @@ bool KItemListView::animateChangedItemCount(int changedItemCount) const return false; } - const int maximum = (scrollOrientation() == Qt::Vertical) - ? m_layouter->size().width() / m_layouter->itemSize().width() - : m_layouter->size().height() / m_layouter->itemSize().height(); + const int maximum = (scrollOrientation() == Qt::Vertical) ? m_layouter->size().width() / m_layouter->itemSize().width() + : m_layouter->size().height() / m_layouter->itemSize().height(); // Only animate if up to 2/3 of a row or column are inserted or removed return changedItemCount <= maximum * 2 / 3; } - -bool KItemListView::scrollBarRequired(const QSizeF& size) const +bool KItemListView::scrollBarRequired(const QSizeF &size) const { const QSizeF oldSize = m_layouter->size(); @@ -2530,16 +2465,15 @@ bool KItemListView::scrollBarRequired(const QSizeF& size) const const qreal maxOffset = m_layouter->maximumScrollOffset(); m_layouter->setSize(oldSize); - return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height() - : maxOffset > size.width(); + return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height() : maxOffset > size.width(); } -int KItemListView::showDropIndicator(const QPointF& pos) +int KItemListView::showDropIndicator(const QPointF &pos) { - QHashIterator it(m_visibleItems); + QHashIterator it(m_visibleItems); while (it.hasNext()) { it.next(); - const KItemListWidget* widget = it.value(); + const KItemListWidget *widget = it.value(); const QPointF mappedPos = widget->mapFromItem(this, pos); const QRectF rect = itemRect(widget->index()); @@ -2552,7 +2486,7 @@ int KItemListView::showDropIndicator(const QPointF& pos) } } - const bool isAboveItem = (mappedPos.y () < rect.height() / 2); + const bool isAboveItem = (mappedPos.y() < rect.height() / 2); const qreal y = isAboveItem ? rect.top() : rect.bottom(); const QRectF draggingInsertIndicator(rect.left(), y, rect.width(), 1); @@ -2592,7 +2526,7 @@ void KItemListView::updateGroupHeaderHeight() // from m_styleOption. groupHeaderHeight += 2 * m_styleOption.horizontalMargin; groupHeaderMargin = m_styleOption.horizontalMargin; - } else if (m_itemSize.isEmpty()){ + } else if (m_itemSize.isEmpty()) { groupHeaderHeight += 4 * m_styleOption.padding; groupHeaderMargin = m_styleOption.iconSize / 2; } else { @@ -2613,10 +2547,9 @@ void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex) if (firstIndex < 0 || lastIndex < 0) { firstIndex = m_layouter->firstVisibleIndex(); - lastIndex = m_layouter->lastVisibleIndex(); + lastIndex = m_layouter->lastVisibleIndex(); } else { - const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() && - lastIndex >= m_layouter->firstVisibleIndex()); + const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() && lastIndex >= m_layouter->firstVisibleIndex()); if (!isRangeVisible) { return; } @@ -2632,7 +2565,7 @@ void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex) // contain a siblings information which can be used as base. int rootIndex = firstIndex; - KItemListWidget* widget = m_visibleItems.value(firstIndex - 1); + KItemListWidget *widget = m_visibleItems.value(firstIndex - 1); if (!widget) { // There is no visible widget before the range, check whether there // is one after the range: @@ -2685,7 +2618,7 @@ void KItemListView::updateSiblingsInformation(int firstIndex, int lastIndex) if (i >= firstIndex) { // The index represents a visible item. Apply the parent-siblings // and update the sibling of the current item. - KItemListWidget* widget = m_visibleItems.value(i); + KItemListWidget *widget = m_visibleItems.value(i); if (!widget) { continue; } @@ -2734,7 +2667,7 @@ bool KItemListView::hasSiblingSuccessor(int index) const void KItemListView::disconnectRoleEditingSignals(int index) { - KStandardItemListWidget* widget = qobject_cast(m_visibleItems.value(index)); + KStandardItemListWidget *widget = qobject_cast(m_visibleItems.value(index)); if (!widget) { return; } @@ -2777,20 +2710,18 @@ int KItemListView::itemsPerSize(qreal size, qreal itemSize, qreal itemMargin) return count; } - - KItemListCreatorBase::~KItemListCreatorBase() { qDeleteAll(m_recycleableWidgets); qDeleteAll(m_createdWidgets); } -void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget) +void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget *widget) { m_createdWidgets.insert(widget); } -void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget) +void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget *widget) { Q_ASSERT(m_createdWidgets.contains(widget)); m_createdWidgets.remove(widget); @@ -2803,13 +2734,13 @@ void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget) } } -QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget() +QGraphicsWidget *KItemListCreatorBase::popRecycleableWidget() { if (m_recycleableWidgets.isEmpty()) { return nullptr; } - QGraphicsWidget* widget = m_recycleableWidgets.takeLast(); + QGraphicsWidget *widget = m_recycleableWidgets.takeLast(); m_createdWidgets.insert(widget); return widget; } @@ -2818,7 +2749,7 @@ KItemListWidgetCreatorBase::~KItemListWidgetCreatorBase() { } -void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget) +void KItemListWidgetCreatorBase::recycle(KItemListWidget *widget) { widget->setParentItem(nullptr); widget->setOpacity(1.0); @@ -2829,9 +2760,8 @@ KItemListGroupHeaderCreatorBase::~KItemListGroupHeaderCreatorBase() { } -void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header) +void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader *header) { header->setOpacity(1.0); pushRecycleableWidget(header); } - diff --git a/src/kitemviews/kitemlistview.h b/src/kitemviews/kitemlistview.h index 27bddd0d9d..e9b4a62dd0 100644 --- a/src/kitemviews/kitemlistview.h +++ b/src/kitemviews/kitemlistview.h @@ -57,7 +57,7 @@ class DOLPHIN_EXPORT KItemListView : public QGraphicsWidget Q_PROPERTY(qreal itemOffset READ itemOffset WRITE setItemOffset) public: - explicit KItemListView(QGraphicsWidget* parent = nullptr); + explicit KItemListView(QGraphicsWidget *parent = nullptr); ~KItemListView() override; /** @@ -83,7 +83,7 @@ public: int maximumVisibleItems() const; - void setVisibleRoles(const QList& roles); + void setVisibleRoles(const QList &roles); QList visibleRoles() const; /** @@ -106,14 +106,14 @@ public: * initialized by KItemListController::setView() and will * result in calling KItemListController::onControllerChanged(). */ - KItemListController* controller() const; + KItemListController *controller() const; /** * @return Model of the item-list. The model gets * initialized by KItemListController::setModel() and will * result in calling KItemListController::onModelChanged(). */ - KItemModelBase* model() const; + KItemModelBase *model() const; /** * Sets the creator that creates a widget showing the @@ -126,8 +126,8 @@ public: * The ownership of the widget creator is transferred to * the item-list view. **/ - void setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator); - KItemListWidgetCreatorBase* widgetCreator() const; + void setWidgetCreator(KItemListWidgetCreatorBase *widgetCreator); + KItemListWidgetCreatorBase *widgetCreator() const; /** * Sets the creator that creates a group header. Usually it is sufficient @@ -139,8 +139,8 @@ public: * The ownership of the gropup header creator is transferred to * the item-list view. **/ - void setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator); - KItemListGroupHeaderCreatorBase* groupHeaderCreator() const; + void setGroupHeaderCreator(KItemListGroupHeaderCreatorBase *groupHeaderCreator); + KItemListGroupHeaderCreatorBase *groupHeaderCreator() const; /** * @return The basic size of all items. The size of an item may be larger than @@ -148,9 +148,9 @@ public: */ QSizeF itemSize() const; - const KItemListStyleOption& styleOption() const; + const KItemListStyleOption &styleOption() const; - void setGeometry(const QRectF& rect) override; + void setGeometry(const QRectF &rect) override; /** * @return The page step which should be used by the vertical scroll bar. @@ -165,10 +165,10 @@ public: * items are considered. std::nullopt is returned if * no item is below the position. */ - std::optional itemAt(const QPointF& pos) const; - bool isAboveSelectionToggle(int index, const QPointF& pos) const; - bool isAboveExpansionToggle(int index, const QPointF& pos) const; - bool isAboveText(int index, const QPointF& pos) const; + std::optional itemAt(const QPointF &pos) const; + bool isAboveSelectionToggle(int index, const QPointF &pos) const; + bool isAboveExpansionToggle(int index, const QPointF &pos) const; + bool isAboveText(int index, const QPointF &pos) const; /** * @return Index of the first item that is at least partly visible. @@ -191,7 +191,7 @@ public: * @note the logical height (width) is actually the * width (height) if the scroll orientation is Qt::Vertical! */ - void calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint) const; + void calculateItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint) const; /** * If set to true, items having child-items can be expanded to show the child-items as @@ -269,20 +269,20 @@ public: * @return Header of the list. The header is also available if it is not shown * (see KItemListView::setHeaderShown()). */ - KItemListHeader* header() const; + KItemListHeader *header() const; /** * @return Pixmap that is used for a drag operation based on the * items given by \a indexes. */ - virtual QPixmap createDragPixmap(const KItemSet& indexes) const; + virtual QPixmap createDragPixmap(const KItemSet &indexes) const; /** * Lets the user edit the role \a role for item with the index \a index. */ - void editRole(int index, const QByteArray& role); + void editRole(int index, const QByteArray &role); - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; Q_SIGNALS: void scrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous); @@ -308,7 +308,7 @@ Q_SIGNALS: * the current sort role. Note that no signal will be emitted if the * sort role of the model has been changed without user interaction. */ - void sortRoleChanged(const QByteArray& current, const QByteArray& previous); + void sortRoleChanged(const QByteArray ¤t, const QByteArray &previous); /** * Is emitted if the user has changed the visible roles by moving a header @@ -316,10 +316,10 @@ Q_SIGNALS: * emitted if the roles have been changed without user interaction by * KItemListView::setVisibleRoles(). */ - void visibleRolesChanged(const QList& current, const QList& previous); + void visibleRolesChanged(const QList ¤t, const QList &previous); - void roleEditingCanceled(int index, const QByteArray& role, const QVariant& value); - void roleEditingFinished(int index, const QByteArray& role, const QVariant& value); + void roleEditingCanceled(int index, const QByteArray &role, const QVariant &value); + void roleEditingFinished(int index, const QByteArray &role, const QVariant &value); /** * Emitted once scrolling has finished, or immediately if no scrolling was necessary @@ -329,8 +329,8 @@ Q_SIGNALS: protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - void setItemSize(const QSizeF& size); - void setStyleOption(const KItemListStyleOption& option); + void setItemSize(const QSizeF &size); + void setStyleOption(const KItemListStyleOption &option); /** * If the scroll-orientation is vertical, the items are ordered @@ -346,7 +346,7 @@ protected: * @return New instance of the widget-creator that should be used per * default. */ - virtual KItemListWidgetCreatorBase* defaultWidgetCreator() const; + virtual KItemListWidgetCreatorBase *defaultWidgetCreator() const; /** * Factory method for creating a default group-header-creator. The method will be used @@ -354,13 +354,13 @@ protected: * @return New instance of the group-header-creator that should be used per * default. */ - virtual KItemListGroupHeaderCreatorBase* defaultGroupHeaderCreator() const; + virtual KItemListGroupHeaderCreatorBase *defaultGroupHeaderCreator() const; /** * Is called when creating a new KItemListWidget instance and allows derived * classes to do a custom initialization. */ - virtual void initializeItemListWidget(KItemListWidget* item); + virtual void initializeItemListWidget(KItemListWidget *item); /** * @return True if at least one of the changed roles \p changedRoles might result @@ -370,52 +370,50 @@ protected: * to return false in case if a role-change will not result in a changed * item-size hint. */ - virtual bool itemSizeHintUpdateRequired(const QSet& changedRoles) const; + virtual bool itemSizeHintUpdateRequired(const QSet &changedRoles) const; - virtual void onControllerChanged(KItemListController* current, KItemListController* previous); - virtual void onModelChanged(KItemModelBase* current, KItemModelBase* previous); + virtual void onControllerChanged(KItemListController *current, KItemListController *previous); + virtual void onModelChanged(KItemModelBase *current, KItemModelBase *previous); virtual void onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous); - virtual void onItemSizeChanged(const QSizeF& current, const QSizeF& previous); + virtual void onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous); virtual void onScrollOffsetChanged(qreal current, qreal previous); - virtual void onVisibleRolesChanged(const QList& current, const QList& previous); - virtual void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous); + virtual void onVisibleRolesChanged(const QList ¤t, const QList &previous); + virtual void onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous); virtual void onHighlightEntireRowChanged(bool highlightEntireRow); virtual void onSupportsItemExpandingChanged(bool supportsExpanding); virtual void onTransactionBegin(); virtual void onTransactionEnd(); - bool event(QEvent* event) override; - void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - void dragEnterEvent(QGraphicsSceneDragDropEvent* event) override; - void dragMoveEvent(QGraphicsSceneDragDropEvent* event) override; - void dragLeaveEvent(QGraphicsSceneDragDropEvent* event) override; - void dropEvent(QGraphicsSceneDragDropEvent* event) override; + bool event(QEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void dragEnterEvent(QGraphicsSceneDragDropEvent *event) override; + void dragMoveEvent(QGraphicsSceneDragDropEvent *event) override; + void dragLeaveEvent(QGraphicsSceneDragDropEvent *event) override; + void dropEvent(QGraphicsSceneDragDropEvent *event) override; - QList visibleItemListWidgets() const; + QList visibleItemListWidgets() const; virtual void updateFont(); virtual void updatePalette(); protected Q_SLOTS: - virtual void slotItemsInserted(const KItemRangeList& itemRanges); - virtual void slotItemsRemoved(const KItemRangeList& itemRanges); - virtual void slotItemsMoved(const KItemRange& itemRange, const QList& movedToIndexes); - virtual void slotItemsChanged(const KItemRangeList& itemRanges, - const QSet& roles); + virtual void slotItemsInserted(const KItemRangeList &itemRanges); + virtual void slotItemsRemoved(const KItemRangeList &itemRanges); + virtual void slotItemsMoved(const KItemRange &itemRange, const QList &movedToIndexes); + virtual void slotItemsChanged(const KItemRangeList &itemRanges, const QSet &roles); virtual void slotGroupsChanged(); virtual void slotGroupedSortingChanged(bool current); virtual void slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous); - virtual void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous); + virtual void slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous); virtual void slotCurrentChanged(int current, int previous); - virtual void slotSelectionChanged(const KItemSet& current, const KItemSet& previous); + virtual void slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous); private Q_SLOTS: - void slotAnimationFinished(QGraphicsWidget* widget, - KItemListViewAnimation::AnimationType type); + void slotAnimationFinished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type); void slotRubberBandPosChanged(); void slotRubberBandActivationChanged(bool active); @@ -426,9 +424,7 @@ private Q_SLOTS: * will be turned off as soon as this method has been called at * least once. */ - void slotHeaderColumnWidthChanged(const QByteArray& role, - qreal currentWidth, - qreal previousWidth); + void slotHeaderColumnWidthChanged(const QByteArray &role, qreal currentWidth, qreal previousWidth); void slotSidePaddingChanged(qreal width); @@ -436,9 +432,7 @@ private Q_SLOTS: * Is invoked if a column has been moved by the user. Applies * the moved role to the view. */ - void slotHeaderColumnMoved(const QByteArray& role, - int currentIndex, - int previousIndex); + void slotHeaderColumnMoved(const QByteArray &role, int currentIndex, int previousIndex); /** * Triggers the autoscrolling if autoScroll() is enabled by checking the @@ -455,26 +449,18 @@ private Q_SLOTS: */ void slotGeometryOfGroupHeaderParentChanged(); - void slotRoleEditingCanceled(int index, const QByteArray& role, const QVariant& value); - void slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value); + void slotRoleEditingCanceled(int index, const QByteArray &role, const QVariant &value); + void slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value); private: - enum LayoutAnimationHint - { - NoAnimation, - Animation - }; + enum LayoutAnimationHint { NoAnimation, Animation }; - enum SizeType - { - LayouterSize, - ItemSize - }; + enum SizeType { LayouterSize, ItemSize }; - void setController(KItemListController* controller); - void setModel(KItemModelBase* model); + void setController(KItemListController *controller); + void setModel(KItemModelBase *model); - KItemListRubberBand* rubberBand() const; + KItemListRubberBand *rubberBand() const; void doLayout(LayoutAnimationHint hint, int changedIndex = 0, int changedCount = 0); @@ -485,9 +471,7 @@ private: * won't be reused. Reusing items is faster in comparison to deleting invisible * items and creating a new instance for visible items. */ - QList recycleInvisibleItems(int firstVisibleIndex, - int lastVisibleIndex, - LayoutAnimationHint hint); + QList recycleInvisibleItems(int firstVisibleIndex, int lastVisibleIndex, LayoutAnimationHint hint); /** * Helper method for doLayout: Starts a moving-animation for the widget to the given @@ -495,19 +479,19 @@ private: * the same row or column, otherwise the create-animation is used instead. * @return True if the moving-animation has been applied. */ - bool moveWidget(KItemListWidget* widget, const QPointF& newPos); + bool moveWidget(KItemListWidget *widget, const QPointF &newPos); void emitOffsetChanges(); - KItemListWidget* createWidget(int index); - void recycleWidget(KItemListWidget* widget); + KItemListWidget *createWidget(int index); + void recycleWidget(KItemListWidget *widget); /** * Changes the index of the widget to \a index and assures a consistent * update for m_visibleItems and m_visibleCells. The cell-information * for the new index will not be updated and be initialized as empty cell. */ - void setWidgetIndex(KItemListWidget* widget, int index); + void setWidgetIndex(KItemListWidget *widget, int index); /** * Changes the index of the widget to \a index. In opposite to @@ -515,36 +499,36 @@ private: * This update gives doLayout() the chance to animate the moving * of the item visually (see moveWidget()). */ - void moveWidgetToIndex(KItemListWidget* widget, int index); + void moveWidgetToIndex(KItemListWidget *widget, int index); /** * Helper method for prepareLayoutForIncreasedItemCount(). */ - void setLayouterSize(const QSizeF& size, SizeType sizeType); + void setLayouterSize(const QSizeF &size, SizeType sizeType); /** * Helper method for createWidget() and setWidgetIndex() to update the properties * of the itemlist widget. */ - void updateWidgetProperties(KItemListWidget* widget, int index); + void updateWidgetProperties(KItemListWidget *widget, int index); /** * Helper method for updateWidgetPropertes() to create or update * the itemlist group-header. */ - void updateGroupHeaderForWidget(KItemListWidget* widget); + void updateGroupHeaderForWidget(KItemListWidget *widget); /** * Updates the position and size of the group-header that belongs * to the itemlist widget \a widget. The given widget must represent * the first item of a group. */ - void updateGroupHeaderLayout(KItemListWidget* widget); + void updateGroupHeaderLayout(KItemListWidget *widget); /** * Recycles the group-header for the widget. */ - void recycleGroupHeaderForWidget(KItemListWidget* widget); + void recycleGroupHeaderForWidget(KItemListWidget *widget); /** * Helper method for slotGroupedSortingChanged(), slotSortOrderChanged() @@ -570,7 +554,7 @@ private: * Updates the alternateBackground-property of the widget dependent * on the state of useAlternateBackgrounds() and the grouping state. */ - void updateAlternateBackgroundForWidget(KItemListWidget* widget); + void updateAlternateBackgroundForWidget(KItemListWidget *widget); /** * @return True if alternate backgrounds should be used for the items. @@ -586,7 +570,7 @@ private: * KItemListView::setItemSize()). Per default an empty hash * is returned. */ - QHash preferredColumnWidths(const KItemRangeList& itemRanges) const; + QHash preferredColumnWidths(const KItemRangeList &itemRanges) const; /** * Applies the column-widths from m_headerWidget to the layout @@ -597,13 +581,13 @@ private: /** * Applies the column-widths from m_headerWidget to \a widget. */ - void updateWidgetColumnWidths(KItemListWidget* widget); + void updateWidgetColumnWidths(KItemListWidget *widget); /** * Updates the preferred column-widths of m_groupHeaderWidget by * invoking KItemListView::columnWidths(). */ - void updatePreferredColumnWidths(const KItemRangeList& itemRanges); + void updatePreferredColumnWidths(const KItemRangeList &itemRanges); /** * Convenience method for @@ -633,9 +617,7 @@ private: * the new grid- and item-size. Used to determine whether an animation * should be done when applying the new layout. */ - bool changesItemGridLayout(const QSizeF& newGridSize, - const QSizeF& newItemSize, - const QSizeF& newItemMargin) const; + bool changesItemGridLayout(const QSizeF &newGridSize, const QSizeF &newItemSize, const QSizeF &newItemMargin) const; /** * @param changedItemCount Number of inserted or removed items. @@ -650,7 +632,7 @@ private: * when using a size of \p size for the view. Calling the method is rather * expansive as a temporary relayout needs to be done. */ - bool scrollBarRequired(const QSizeF& size) const; + bool scrollBarRequired(const QSizeF &size) const; /** * Shows a drop-indicator between items dependent on the given @@ -659,7 +641,7 @@ private: * @return Index of the item where the dropping is done. An index of -1 * indicates that the item has been dropped after the last item. */ - int showDropIndicator(const QPointF& pos); + int showDropIndicator(const QPointF &pos); void hideDropIndicator(); /** @@ -721,28 +703,35 @@ private: LayoutAnimationHint m_endTransactionAnimationHint; QSizeF m_itemSize; - KItemListController* m_controller; - KItemModelBase* m_model; + KItemListController *m_controller; + KItemModelBase *m_model; QList m_visibleRoles; - mutable KItemListWidgetCreatorBase* m_widgetCreator; - mutable KItemListGroupHeaderCreatorBase* m_groupHeaderCreator; + mutable KItemListWidgetCreatorBase *m_widgetCreator; + mutable KItemListGroupHeaderCreatorBase *m_groupHeaderCreator; KItemListStyleOption m_styleOption; - QHash m_visibleItems; - QHash m_visibleGroups; + QHash m_visibleItems; + QHash m_visibleGroups; - struct Cell - { - Cell() : column(-1), row(-1) {} - Cell(int c, int r) : column(c), row(r) {} + struct Cell { + Cell() + : column(-1) + , row(-1) + { + } + Cell(int c, int r) + : column(c) + , row(r) + { + } int column; int row; }; QHash m_visibleCells; int m_scrollBarExtent; - KItemListViewLayouter* m_layouter; - KItemListViewAnimation* m_animation; + KItemListViewLayouter *m_layouter; + KItemListViewAnimation *m_animation; qreal m_oldScrollOffset; qreal m_oldMaximumScrollOffset; @@ -750,17 +739,17 @@ private: qreal m_oldMaximumItemOffset; bool m_skipAutoScrollForRubberBand; - KItemListRubberBand* m_rubberBand; - KItemListRubberBand* m_tapAndHoldIndicator; + KItemListRubberBand *m_rubberBand; + KItemListRubberBand *m_tapAndHoldIndicator; QPointF m_mousePos; int m_autoScrollIncrement; - QTimer* m_autoScrollTimer; + QTimer *m_autoScrollTimer; - KItemListHeader* m_header; - KItemListHeaderWidget* m_headerWidget; + KItemListHeader *m_header; + KItemListHeaderWidget *m_headerWidget; - QPropertyAnimation* m_indicatorAnimation; + QPropertyAnimation *m_indicatorAnimation; // When dragging items into the view where the sort-role of the model // is empty, a visual indicator should be shown during dragging where @@ -770,12 +759,12 @@ private: // by KItemListView::showDropIndicator() and KItemListView::hideDropIndicator(). QRectF m_dropIndicator; - QList m_rubberBandAnimations; + QList m_rubberBandAnimations; - KItemListSizeHintResolver* m_sizeHintResolver; + KItemListSizeHintResolver *m_sizeHintResolver; friend class KItemListContainer; // Accesses scrollBarRequired() - friend class KItemListHeader; // Accesses m_headerWidget + friend class KItemListHeader; // Accesses m_headerWidget friend class KItemListController; friend class KItemListControllerTest; friend class KItemListViewAccessible; @@ -794,13 +783,13 @@ public: virtual ~KItemListCreatorBase(); protected: - void addCreatedWidget(QGraphicsWidget* widget); - void pushRecycleableWidget(QGraphicsWidget* widget); - QGraphicsWidget* popRecycleableWidget(); + void addCreatedWidget(QGraphicsWidget *widget); + void pushRecycleableWidget(QGraphicsWidget *widget); + QGraphicsWidget *popRecycleableWidget(); private: - QSet m_createdWidgets; - QList m_recycleableWidgets; + QSet m_createdWidgets; + QList m_recycleableWidgets; }; /** @@ -817,54 +806,51 @@ class DOLPHIN_EXPORT KItemListWidgetCreatorBase : public KItemListCreatorBase public: ~KItemListWidgetCreatorBase() override; - virtual KItemListWidget* create(KItemListView* view) = 0; + virtual KItemListWidget *create(KItemListView *view) = 0; - virtual void recycle(KItemListWidget* widget); + virtual void recycle(KItemListWidget *widget); - virtual void calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const = 0; + virtual void calculateItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const = 0; - virtual qreal preferredRoleColumnWidth(const QByteArray& role, - int index, - const KItemListView* view) const = 0; + virtual qreal preferredRoleColumnWidth(const QByteArray &role, int index, const KItemListView *view) const = 0; }; /** * @brief Template class for creating KItemListWidgets. */ -template +template class KItemListWidgetCreator : public KItemListWidgetCreatorBase { public: KItemListWidgetCreator(); ~KItemListWidgetCreator() override; - KItemListWidget* create(KItemListView* view) override; + KItemListWidget *create(KItemListView *view) override; - void calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const override; + void calculateItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const override; + + qreal preferredRoleColumnWidth(const QByteArray &role, int index, const KItemListView *view) const override; - qreal preferredRoleColumnWidth(const QByteArray& role, - int index, - const KItemListView* view) const override; private: - KItemListWidgetInformant* m_informant; + KItemListWidgetInformant *m_informant; }; -template -KItemListWidgetCreator::KItemListWidgetCreator() : - m_informant(T::createInformant()) +template +KItemListWidgetCreator::KItemListWidgetCreator() + : m_informant(T::createInformant()) { } -template +template KItemListWidgetCreator::~KItemListWidgetCreator() { delete m_informant; } -template -KItemListWidget* KItemListWidgetCreator::create(KItemListView* view) +template +KItemListWidget *KItemListWidgetCreator::create(KItemListView *view) { - KItemListWidget* widget = static_cast(popRecycleableWidget()); + KItemListWidget *widget = static_cast(popRecycleableWidget()); if (!widget) { widget = new T(m_informant, view); addCreatedWidget(widget); @@ -874,15 +860,15 @@ KItemListWidget* KItemListWidgetCreator::create(KItemListView* view) } template -void KItemListWidgetCreator::calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const +void KItemListWidgetCreator::calculateItemSizeHints(QVector> &logicalHeightHints, + qreal &logicalWidthHint, + const KItemListView *view) const { return m_informant->calculateItemSizeHints(logicalHeightHints, logicalWidthHint, view); } template -qreal KItemListWidgetCreator::preferredRoleColumnWidth(const QByteArray& role, - int index, - const KItemListView* view) const +qreal KItemListWidgetCreator::preferredRoleColumnWidth(const QByteArray &role, int index, const KItemListView *view) const { return m_informant->preferredRoleColumnWidth(role, index, view); } @@ -899,27 +885,27 @@ class DOLPHIN_EXPORT KItemListGroupHeaderCreatorBase : public KItemListCreatorBa { public: ~KItemListGroupHeaderCreatorBase() override; - virtual KItemListGroupHeader* create(KItemListView* view) = 0; - virtual void recycle(KItemListGroupHeader* header); + virtual KItemListGroupHeader *create(KItemListView *view) = 0; + virtual void recycle(KItemListGroupHeader *header); }; -template +template class KItemListGroupHeaderCreator : public KItemListGroupHeaderCreatorBase { public: ~KItemListGroupHeaderCreator() override; - KItemListGroupHeader* create(KItemListView* view) override; + KItemListGroupHeader *create(KItemListView *view) override; }; -template +template KItemListGroupHeaderCreator::~KItemListGroupHeaderCreator() { } -template -KItemListGroupHeader* KItemListGroupHeaderCreator::create(KItemListView* view) +template +KItemListGroupHeader *KItemListGroupHeaderCreator::create(KItemListView *view) { - KItemListGroupHeader* widget = static_cast(popRecycleableWidget()); + KItemListGroupHeader *widget = static_cast(popRecycleableWidget()); if (!widget) { widget = new T(view); addCreatedWidget(widget); diff --git a/src/kitemviews/kitemlistviewaccessible.cpp b/src/kitemviews/kitemlistviewaccessible.cpp index a1afadff4b..a75df8b760 100644 --- a/src/kitemviews/kitemlistviewaccessible.cpp +++ b/src/kitemviews/kitemlistviewaccessible.cpp @@ -16,13 +16,13 @@ #include #include -KItemListView* KItemListViewAccessible::view() const +KItemListView *KItemListViewAccessible::view() const { - return qobject_cast(object()); + return qobject_cast(object()); } -KItemListViewAccessible::KItemListViewAccessible(KItemListView* view_) : - QAccessibleObject(view_) +KItemListViewAccessible::KItemListViewAccessible(KItemListView *view_) + : QAccessibleObject(view_) { Q_ASSERT(view()); m_cells.resize(childCount()); @@ -37,10 +37,10 @@ KItemListViewAccessible::~KItemListViewAccessible() } } -void* KItemListViewAccessible::interface_cast(QAccessible::InterfaceType type) +void *KItemListViewAccessible::interface_cast(QAccessible::InterfaceType type) { if (type == QAccessible::TableInterface) { - return static_cast(this); + return static_cast(this); } return nullptr; } @@ -49,7 +49,7 @@ void KItemListViewAccessible::modelReset() { } -QAccessibleInterface* KItemListViewAccessible::cell(int index) const +QAccessibleInterface *KItemListViewAccessible::cell(int index) const { if (index < 0 || index >= view()->model()->count()) { return nullptr; @@ -69,12 +69,12 @@ QAccessibleInterface* KItemListViewAccessible::cell(int index) const return QAccessible::accessibleInterface(idWrapper.id); } -QAccessibleInterface* KItemListViewAccessible::cellAt(int row, int column) const +QAccessibleInterface *KItemListViewAccessible::cellAt(int row, int column) const { return cell(columnCount() * row + column); } -QAccessibleInterface* KItemListViewAccessible::caption() const +QAccessibleInterface *KItemListViewAccessible::caption() const { return nullptr; } @@ -128,9 +128,9 @@ QString KItemListViewAccessible::rowDescription(int) const return QString(); } -QList KItemListViewAccessible::selectedCells() const +QList KItemListViewAccessible::selectedCells() const { - QList cells; + QList cells; const auto items = view()->controller()->selectionManager()->selectedItems(); cells.reserve(items.count()); for (int index : items) { @@ -149,7 +149,7 @@ QList KItemListViewAccessible::selectedRows() const return QList(); } -QAccessibleInterface* KItemListViewAccessible::summary() const +QAccessibleInterface *KItemListViewAccessible::summary() const { return nullptr; } @@ -184,8 +184,9 @@ bool KItemListViewAccessible::unselectColumn(int) return true; } -void KItemListViewAccessible::modelChange(QAccessibleTableModelChangeEvent* /*event*/) -{} +void KItemListViewAccessible::modelChange(QAccessibleTableModelChangeEvent * /*event*/) +{ +} QAccessible::Role KItemListViewAccessible::role() const { @@ -198,14 +199,14 @@ QAccessible::State KItemListViewAccessible::state() const return s; } -QAccessibleInterface* KItemListViewAccessible::childAt(int x, int y) const +QAccessibleInterface *KItemListViewAccessible::childAt(int x, int y) const { const QPointF point = QPointF(x, y); const std::optional itemIndex = view()->itemAt(view()->mapFromScene(point)); return child(itemIndex.value_or(-1)); } -QAccessibleInterface* KItemListViewAccessible::parent() const +QAccessibleInterface *KItemListViewAccessible::parent() const { // FIXME: return KItemListContainerAccessible here return nullptr; @@ -216,9 +217,9 @@ int KItemListViewAccessible::childCount() const return view()->model()->count(); } -int KItemListViewAccessible::indexOfChild(const QAccessibleInterface* interface) const +int KItemListViewAccessible::indexOfChild(const QAccessibleInterface *interface) const { - const KItemListAccessibleCell* widget = static_cast(interface); + const KItemListAccessibleCell *widget = static_cast(interface); return widget->index(); } @@ -233,7 +234,7 @@ QRect KItemListViewAccessible::rect() const return QRect(); } - const QGraphicsScene* scene = view()->scene(); + const QGraphicsScene *scene = view()->scene(); if (scene) { const QPoint origin = scene->views().at(0)->mapToGlobal(QPoint(0, 0)); const QRect viewRect = view()->geometry().toRect(); @@ -243,7 +244,7 @@ QRect KItemListViewAccessible::rect() const } } -QAccessibleInterface* KItemListViewAccessible::child(int index) const +QAccessibleInterface *KItemListViewAccessible::child(int index) const { if (index >= 0 && index < childCount()) { return cell(index); @@ -251,25 +252,25 @@ QAccessibleInterface* KItemListViewAccessible::child(int index) const return nullptr; } -KItemListViewAccessible::AccessibleIdWrapper::AccessibleIdWrapper() : - isValid(false), - id(0) +KItemListViewAccessible::AccessibleIdWrapper::AccessibleIdWrapper() + : isValid(false) + , id(0) { } // Table Cell -KItemListAccessibleCell::KItemListAccessibleCell(KItemListView* view, int index) : - m_view(view), - m_index(index) +KItemListAccessibleCell::KItemListAccessibleCell(KItemListView *view, int index) + : m_view(view) + , m_index(index) { Q_ASSERT(index >= 0 && index < view->model()->count()); } -void* KItemListAccessibleCell::interface_cast(QAccessible::InterfaceType type) +void *KItemListAccessibleCell::interface_cast(QAccessible::InterfaceType type) { if (type == QAccessible::TableCellInterface) { - return static_cast(this); + return static_cast(this); } return nullptr; } @@ -284,14 +285,14 @@ int KItemListAccessibleCell::rowExtent() const return 1; } -QList KItemListAccessibleCell::rowHeaderCells() const +QList KItemListAccessibleCell::rowHeaderCells() const { - return QList(); + return QList(); } -QList KItemListAccessibleCell::columnHeaderCells() const +QList KItemListAccessibleCell::columnHeaderCells() const { - return QList(); + return QList(); } int KItemListAccessibleCell::columnIndex() const @@ -309,7 +310,7 @@ bool KItemListAccessibleCell::isSelected() const return m_view->controller()->selectionManager()->isSelected(m_index); } -QAccessibleInterface* KItemListAccessibleCell::table() const +QAccessibleInterface *KItemListAccessibleCell::table() const { return QAccessible::queryAccessibleInterface(m_view); } @@ -381,11 +382,11 @@ QString KItemListAccessibleCell::text(QAccessible::Text t) const return QString(); } -void KItemListAccessibleCell::setText(QAccessible::Text, const QString&) +void KItemListAccessibleCell::setText(QAccessible::Text, const QString &) { } -QAccessibleInterface* KItemListAccessibleCell::child(int) const +QAccessibleInterface *KItemListAccessibleCell::child(int) const { return nullptr; } @@ -395,7 +396,7 @@ bool KItemListAccessibleCell::isValid() const return m_view && (m_index >= 0) && (m_index < m_view->model()->count()); } -QAccessibleInterface* KItemListAccessibleCell::childAt(int, int) const +QAccessibleInterface *KItemListAccessibleCell::childAt(int, int) const { return nullptr; } @@ -405,13 +406,13 @@ int KItemListAccessibleCell::childCount() const return 0; } -int KItemListAccessibleCell::indexOfChild(const QAccessibleInterface* child) const +int KItemListAccessibleCell::indexOfChild(const QAccessibleInterface *child) const { Q_UNUSED(child) return -1; } -QAccessibleInterface* KItemListAccessibleCell::parent() const +QAccessibleInterface *KItemListAccessibleCell::parent() const { return QAccessible::queryAccessibleInterface(m_view); } @@ -421,14 +422,14 @@ int KItemListAccessibleCell::index() const return m_index; } -QObject* KItemListAccessibleCell::object() const +QObject *KItemListAccessibleCell::object() const { return nullptr; } // Container Interface -KItemListContainerAccessible::KItemListContainerAccessible(KItemListContainer* container) : - QAccessibleWidget(container) +KItemListContainerAccessible::KItemListContainerAccessible(KItemListContainer *container) + : QAccessibleWidget(container) { } @@ -441,7 +442,7 @@ int KItemListContainerAccessible::childCount() const return 1; } -int KItemListContainerAccessible::indexOfChild(const QAccessibleInterface* child) const +int KItemListContainerAccessible::indexOfChild(const QAccessibleInterface *child) const { if (child->object() == container()->controller()->view()) { return 0; @@ -449,7 +450,7 @@ int KItemListContainerAccessible::indexOfChild(const QAccessibleInterface* child return -1; } -QAccessibleInterface* KItemListContainerAccessible::child(int index) const +QAccessibleInterface *KItemListContainerAccessible::child(int index) const { if (index == 0) { return QAccessible::queryAccessibleInterface(container()->controller()->view()); @@ -457,9 +458,9 @@ QAccessibleInterface* KItemListContainerAccessible::child(int index) const return nullptr; } -const KItemListContainer* KItemListContainerAccessible::container() const +const KItemListContainer *KItemListContainerAccessible::container() const { - return qobject_cast(object()); + return qobject_cast(object()); } #endif // QT_NO_ACCESSIBILITY diff --git a/src/kitemviews/kitemlistviewaccessible.h b/src/kitemviews/kitemlistviewaccessible.h index cdef2ccca9..628c32fc25 100644 --- a/src/kitemviews/kitemlistviewaccessible.h +++ b/src/kitemviews/kitemlistviewaccessible.h @@ -19,29 +19,29 @@ class KItemListView; class KItemListContainer; -class DOLPHIN_EXPORT KItemListViewAccessible: public QAccessibleObject, public QAccessibleTableInterface +class DOLPHIN_EXPORT KItemListViewAccessible : public QAccessibleObject, public QAccessibleTableInterface { public: - explicit KItemListViewAccessible(KItemListView* view); + explicit KItemListViewAccessible(KItemListView *view); ~KItemListViewAccessible() override; - void* interface_cast(QAccessible::InterfaceType type) override; + void *interface_cast(QAccessible::InterfaceType type) override; QAccessible::Role role() const override; QAccessible::State state() const override; QString text(QAccessible::Text t) const override; QRect rect() const override; - QAccessibleInterface* child(int index) const override; + QAccessibleInterface *child(int index) const override; int childCount() const override; - int indexOfChild(const QAccessibleInterface*) const override; - QAccessibleInterface* childAt(int x, int y) const override; - QAccessibleInterface* parent() const override; + int indexOfChild(const QAccessibleInterface *) const override; + QAccessibleInterface *childAt(int x, int y) const override; + QAccessibleInterface *parent() const override; // Table interface - QAccessibleInterface* cellAt(int row, int column) const override; - QAccessibleInterface* caption() const override; - QAccessibleInterface* summary() const override; + QAccessibleInterface *cellAt(int row, int column) const override; + QAccessibleInterface *caption() const override; + QAccessibleInterface *summary() const override; QString columnDescription(int column) const override; QString rowDescription(int row) const override; int columnCount() const override; @@ -51,7 +51,7 @@ public: int selectedCellCount() const override; int selectedColumnCount() const override; int selectedRowCount() const override; - QList selectedCells() const override; + QList selectedCells() const override; QList selectedColumns() const override; QList selectedRows() const override; bool isColumnSelected(int column) const override; @@ -60,9 +60,9 @@ public: bool selectColumn(int column) override; bool unselectRow(int row) override; bool unselectColumn(int column) override; - void modelChange(QAccessibleTableModelChangeEvent*) override; + void modelChange(QAccessibleTableModelChangeEvent *) override; - KItemListView* view() const; + KItemListView *view() const; protected: virtual void modelReset(); @@ -70,10 +70,11 @@ protected: * Create an QAccessibleTableCellInterface representing the table * cell at the @index. Index is 0-based. */ - inline QAccessibleInterface* cell(int index) const; + inline QAccessibleInterface *cell(int index) const; private: - class AccessibleIdWrapper { + class AccessibleIdWrapper + { public: AccessibleIdWrapper(); bool isValid; @@ -82,37 +83,37 @@ private: mutable QVector m_cells; }; -class DOLPHIN_EXPORT KItemListAccessibleCell: public QAccessibleInterface, public QAccessibleTableCellInterface +class DOLPHIN_EXPORT KItemListAccessibleCell : public QAccessibleInterface, public QAccessibleTableCellInterface { public: - KItemListAccessibleCell(KItemListView* view, int m_index); + KItemListAccessibleCell(KItemListView *view, int m_index); - void* interface_cast(QAccessible::InterfaceType type) override; - QObject* object() const override; + void *interface_cast(QAccessible::InterfaceType type) override; + QObject *object() const override; bool isValid() const override; QAccessible::Role role() const override; QAccessible::State state() const override; QRect rect() const override; QString text(QAccessible::Text t) const override; - void setText(QAccessible::Text t, const QString& text) override; + void setText(QAccessible::Text t, const QString &text) override; - QAccessibleInterface* child(int index) const override; + QAccessibleInterface *child(int index) const override; int childCount() const override; - QAccessibleInterface* childAt(int x, int y) const override; - int indexOfChild(const QAccessibleInterface*) const override; + QAccessibleInterface *childAt(int x, int y) const override; + int indexOfChild(const QAccessibleInterface *) const override; - QAccessibleInterface* parent() const override; + QAccessibleInterface *parent() const override; bool isExpandable() const; // Cell Interface int columnExtent() const override; - QList columnHeaderCells() const override; + QList columnHeaderCells() const override; int columnIndex() const override; int rowExtent() const override; - QList rowHeaderCells() const override; + QList rowHeaderCells() const override; int rowIndex() const override; bool isSelected() const override; - QAccessibleInterface* table() const override; + QAccessibleInterface *table() const override; inline int index() const; @@ -124,15 +125,15 @@ private: class DOLPHIN_EXPORT KItemListContainerAccessible : public QAccessibleWidget { public: - explicit KItemListContainerAccessible(KItemListContainer* container); + explicit KItemListContainerAccessible(KItemListContainer *container); ~KItemListContainerAccessible() override; - QAccessibleInterface* child(int index) const override; + QAccessibleInterface *child(int index) const override; int childCount() const override; - int indexOfChild(const QAccessibleInterface* child) const override; + int indexOfChild(const QAccessibleInterface *child) const override; private: - const KItemListContainer* container() const; + const KItemListContainer *container() const; }; #endif // QT_NO_ACCESSIBILITY diff --git a/src/kitemviews/kitemlistwidget.cpp b/src/kitemviews/kitemlistwidget.cpp index ae721c7e41..25a3475175 100644 --- a/src/kitemviews/kitemlistwidget.cpp +++ b/src/kitemviews/kitemlistwidget.cpp @@ -27,28 +27,28 @@ KItemListWidgetInformant::~KItemListWidgetInformant() { } -KItemListWidget::KItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) : - QGraphicsWidget(parent), - m_informant(informant), - m_index(-1), - m_selected(false), - m_current(false), - m_hovered(false), - m_expansionAreaHovered(false), - m_alternateBackground(false), - m_enabledSelectionToggle(false), - m_data(), - m_visibleRoles(), - m_columnWidths(), - m_styleOption(), - m_siblingsInfo(), - m_hoverOpacity(0), - m_hoverCache(nullptr), - m_hoverAnimation(nullptr), - m_hoverSequenceIndex(0), - m_selectionToggle(nullptr), - m_editedRole(), - m_iconSize(-1) +KItemListWidget::KItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent) + : QGraphicsWidget(parent) + , m_informant(informant) + , m_index(-1) + , m_selected(false) + , m_current(false) + , m_hovered(false) + , m_expansionAreaHovered(false) + , m_alternateBackground(false) + , m_enabledSelectionToggle(false) + , m_data() + , m_visibleRoles() + , m_columnWidths() + , m_styleOption() + , m_siblingsInfo() + , m_hoverOpacity(0) + , m_hoverCache(nullptr) + , m_hoverAnimation(nullptr) + , m_hoverSequenceIndex(0) + , m_selectionToggle(nullptr) + , m_editedRole() + , m_iconSize(-1) { connect(&m_hoverSequenceTimer, &QTimer::timeout, this, &KItemListWidget::slotHoverSequenceTimerTimeout); } @@ -79,15 +79,14 @@ int KItemListWidget::index() const return m_index; } -void KItemListWidget::setData(const QHash& data, - const QSet& roles) +void KItemListWidget::setData(const QHash &data, const QSet &roles) { clearHoverCache(); if (roles.isEmpty()) { m_data = data; dataChanged(m_data); } else { - for (const QByteArray& role : roles) { + for (const QByteArray &role : roles) { m_data[role] = data[role]; } dataChanged(m_data, roles); @@ -100,7 +99,7 @@ QHash KItemListWidget::data() const return m_data; } -void KItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KItemListWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) @@ -112,10 +111,7 @@ void KItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* o if (m_selected && m_editedRole.isEmpty()) { const QStyle::State activeState(isActiveWindow() ? QStyle::State_Active : 0); - drawItemStyleOption(painter, widget, activeState | - QStyle::State_Enabled | - QStyle::State_Selected | - QStyle::State_Item); + drawItemStyleOption(painter, widget, activeState | QStyle::State_Enabled | QStyle::State_Selected | QStyle::State_Item); } if (m_current && m_editedRole.isEmpty()) { @@ -139,10 +135,7 @@ void KItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* o QPainter pixmapPainter(m_hoverCache); const QStyle::State activeState(isActiveWindow() ? QStyle::State_Active : 0); - drawItemStyleOption(&pixmapPainter, widget, activeState | - QStyle::State_Enabled | - QStyle::State_MouseOver | - QStyle::State_Item); + drawItemStyleOption(&pixmapPainter, widget, activeState | QStyle::State_Enabled | QStyle::State_MouseOver | QStyle::State_Item); } const qreal opacity = painter->opacity(); @@ -152,7 +145,7 @@ void KItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* o } } -void KItemListWidget::setVisibleRoles(const QList& roles) +void KItemListWidget::setVisibleRoles(const QList &roles) { const QList previousRoles = m_visibleRoles; m_visibleRoles = roles; @@ -166,8 +159,7 @@ QList KItemListWidget::visibleRoles() const return m_visibleRoles; } - -void KItemListWidget::setColumnWidth(const QByteArray& role, qreal width) +void KItemListWidget::setColumnWidth(const QByteArray &role, qreal width) { const qreal previousWidth = m_columnWidths.value(role); if (previousWidth != width) { @@ -177,24 +169,26 @@ void KItemListWidget::setColumnWidth(const QByteArray& role, qreal width) } } -qreal KItemListWidget::columnWidth(const QByteArray& role) const +qreal KItemListWidget::columnWidth(const QByteArray &role) const { return m_columnWidths.value(role); } -qreal KItemListWidget::sidePadding() const { +qreal KItemListWidget::sidePadding() const +{ return m_sidePadding; } -void KItemListWidget::setSidePadding(qreal width) { - if (m_sidePadding != width){ +void KItemListWidget::setSidePadding(qreal width) +{ + if (m_sidePadding != width) { m_sidePadding = width; sidePaddingChanged(width); update(); } } -void KItemListWidget::setStyleOption(const KItemListStyleOption& option) +void KItemListWidget::setStyleOption(const KItemListStyleOption &option) { if (m_styleOption == option) { return; @@ -207,7 +201,7 @@ void KItemListWidget::setStyleOption(const KItemListStyleOption& option) update(); } -const KItemListStyleOption& KItemListWidget::styleOption() const +const KItemListStyleOption &KItemListWidget::styleOption() const { return m_styleOption; } @@ -308,7 +302,7 @@ bool KItemListWidget::expansionAreaHovered() const return m_expansionAreaHovered; } -void KItemListWidget::setHoverPosition(const QPointF& pos) +void KItemListWidget::setHoverPosition(const QPointF &pos) { if (m_selectionToggle) { m_selectionToggle->setHovered(selectionToggleRect().contains(pos)); @@ -353,7 +347,7 @@ bool KItemListWidget::enabledSelectionToggle() const return m_enabledSelectionToggle; } -void KItemListWidget::setSiblingsInformation(const QBitArray& siblings) +void KItemListWidget::setSiblingsInformation(const QBitArray &siblings) { const QBitArray previous = m_siblingsInfo; m_siblingsInfo = siblings; @@ -366,7 +360,7 @@ QBitArray KItemListWidget::siblingsInformation() const return m_siblingsInfo; } -void KItemListWidget::setEditedRole(const QByteArray& role) +void KItemListWidget::setEditedRole(const QByteArray &role) { if (m_editedRole != role) { const QByteArray previous = m_editedRole; @@ -394,16 +388,13 @@ int KItemListWidget::iconSize() const return m_iconSize; } -bool KItemListWidget::contains(const QPointF& point) const +bool KItemListWidget::contains(const QPointF &point) const { if (!QGraphicsWidget::contains(point)) { return false; } - return iconRect().contains(point) || - textRect().contains(point) || - expansionToggleRect().contains(point) || - selectionToggleRect().contains(point); + return iconRect().contains(point) || textRect().contains(point) || expansionToggleRect().contains(point) || selectionToggleRect().contains(point); } QRectF KItemListWidget::textFocusRect() const @@ -421,8 +412,7 @@ QRectF KItemListWidget::expansionToggleRect() const return QRectF(); } -QPixmap KItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem* option, - QWidget* widget) +QPixmap KItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem *option, QWidget *widget) { QPixmap pixmap(size().toSize() * widget->devicePixelRatio()); pixmap.setDevicePixelRatio(widget->devicePixelRatio()); @@ -446,23 +436,19 @@ QPixmap KItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem* option return pixmap; } -void KItemListWidget::dataChanged(const QHash& current, - const QSet& roles) +void KItemListWidget::dataChanged(const QHash ¤t, const QSet &roles) { Q_UNUSED(current) Q_UNUSED(roles) } -void KItemListWidget::visibleRolesChanged(const QList& current, - const QList& previous) +void KItemListWidget::visibleRolesChanged(const QList ¤t, const QList &previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListWidget::columnWidthChanged(const QByteArray& role, - qreal current, - qreal previous) +void KItemListWidget::columnWidthChanged(const QByteArray &role, qreal current, qreal previous) { Q_UNUSED(role) Q_UNUSED(current) @@ -474,8 +460,7 @@ void KItemListWidget::sidePaddingChanged(qreal width) Q_UNUSED(width) } -void KItemListWidget::styleOptionChanged(const KItemListStyleOption& current, - const KItemListStyleOption& previous) +void KItemListWidget::styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) { Q_UNUSED(previous) @@ -505,13 +490,13 @@ void KItemListWidget::alternateBackgroundChanged(bool enabled) Q_UNUSED(enabled) } -void KItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous) +void KItemListWidget::siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) } -void KItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous) +void KItemListWidget::editedRoleChanged(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -523,13 +508,13 @@ void KItemListWidget::iconSizeChanged(int current, int previous) Q_UNUSED(previous) } -void KItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event) +void KItemListWidget::resizeEvent(QGraphicsSceneResizeEvent *event) { QGraphicsWidget::resizeEvent(event); clearHoverCache(); if (m_selectionToggle) { - const QRectF& toggleRect = selectionToggleRect(); + const QRectF &toggleRect = selectionToggleRect(); m_selectionToggle->setPos(toggleRect.topLeft()); m_selectionToggle->resize(toggleRect.size()); } @@ -608,7 +593,7 @@ void KItemListWidget::clearHoverCache() m_hoverCache = nullptr; } -void KItemListWidget::drawItemStyleOption(QPainter* painter, QWidget* widget, QStyle::State styleState) +void KItemListWidget::drawItemStyleOption(QPainter *painter, QWidget *widget, QStyle::State styleState) { QStyleOptionViewItem viewItemOption; initStyleOption(&viewItemOption); @@ -618,4 +603,3 @@ void KItemListWidget::drawItemStyleOption(QPainter* painter, QWidget* widget, QS viewItemOption.rect = selectionRect().toRect(); style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &viewItemOption, painter, widget); } - diff --git a/src/kitemviews/kitemlistwidget.h b/src/kitemviews/kitemlistwidget.h index eeaed09c0b..4634ecc0d6 100644 --- a/src/kitemviews/kitemlistwidget.h +++ b/src/kitemviews/kitemlistwidget.h @@ -35,11 +35,9 @@ public: KItemListWidgetInformant(); virtual ~KItemListWidgetInformant(); - virtual void calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const = 0; + virtual void calculateItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const = 0; - virtual qreal preferredRoleColumnWidth(const QByteArray& role, - int index, - const KItemListView* view) const = 0; + virtual qreal preferredRoleColumnWidth(const QByteArray &role, int index, const KItemListView *view) const = 0; }; /** @@ -56,13 +54,13 @@ class DOLPHIN_EXPORT KItemListWidget : public QGraphicsWidget Q_PROPERTY(int iconSize READ iconSize WRITE setIconSize) public: - KItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent); + KItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent); ~KItemListWidget() override; void setIndex(int index); int index() const; - void setData(const QHash& data, const QSet& roles = QSet()); + void setData(const QHash &data, const QSet &roles = QSet()); QHash data() const; /** @@ -70,23 +68,23 @@ public: * to show the data of the custom model provided by KItemListWidget::data(). * @reimp */ - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; - void setVisibleRoles(const QList& roles); + void setVisibleRoles(const QList &roles); QList visibleRoles() const; /** * Sets the width of a role that should be used if the alignment of the content * should be done in columns. */ - void setColumnWidth(const QByteArray& role, qreal width); - qreal columnWidth(const QByteArray& role) const; + void setColumnWidth(const QByteArray &role, qreal width); + qreal columnWidth(const QByteArray &role) const; void setSidePadding(qreal width); qreal sidePadding() const; - void setStyleOption(const KItemListStyleOption& option); - const KItemListStyleOption& styleOption() const; + void setStyleOption(const KItemListStyleOption &option); + const KItemListStyleOption &styleOption() const; // TODO: Hides QGraphicsItem::setSelected()/isSelected(). Replace // this by using the default mechanism. @@ -102,7 +100,7 @@ public: void setExpansionAreaHovered(bool hover); bool expansionAreaHovered() const; - void setHoverPosition(const QPointF& pos); + void setHoverPosition(const QPointF &pos); void setAlternateBackground(bool enable); bool alternateBackground() const; @@ -117,7 +115,7 @@ public: * The sibling information is useful for drawing the branches in * tree views. */ - void setSiblingsInformation(const QBitArray& siblings); + void setSiblingsInformation(const QBitArray &siblings); QBitArray siblingsInformation() const; /** @@ -127,7 +125,7 @@ public: * the role is empty. Derived classes must implement * editedRoleChanged(). */ - void setEditedRole(const QByteArray& role); + void setEditedRole(const QByteArray &role); QByteArray editedRole() const; /** @@ -143,7 +141,7 @@ public: * or KItemListWidget::expansionToggleRect(). * @reimp */ - bool contains(const QPointF& point) const override; + bool contains(const QPointF &point) const override; /** * @return Rectangle for the area that shows the icon. @@ -187,26 +185,26 @@ public: * @return Pixmap that is used when dragging an item. Per default the current state of the * widget is returned as pixmap. */ - virtual QPixmap createDragPixmap(const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr); + virtual QPixmap createDragPixmap(const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr); Q_SIGNALS: - void roleEditingCanceled(int index, const QByteArray& role, const QVariant& value); - void roleEditingFinished(int index, const QByteArray& role, const QVariant& value); + void roleEditingCanceled(int index, const QByteArray &role, const QVariant &value); + void roleEditingFinished(int index, const QByteArray &role, const QVariant &value); protected: - virtual void dataChanged(const QHash& current, const QSet& roles = QSet()); - virtual void visibleRolesChanged(const QList& current, const QList& previous); - virtual void columnWidthChanged(const QByteArray& role, qreal current, qreal previous); + virtual void dataChanged(const QHash ¤t, const QSet &roles = QSet()); + virtual void visibleRolesChanged(const QList ¤t, const QList &previous); + virtual void columnWidthChanged(const QByteArray &role, qreal current, qreal previous); virtual void sidePaddingChanged(qreal width); - virtual void styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous); + virtual void styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous); virtual void currentChanged(bool current); virtual void selectedChanged(bool selected); virtual void hoveredChanged(bool hovered); virtual void alternateBackgroundChanged(bool enabled); - virtual void siblingsInformationChanged(const QBitArray& current, const QBitArray& previous); - virtual void editedRoleChanged(const QByteArray& current, const QByteArray& previous); + virtual void siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous); + virtual void editedRoleChanged(const QByteArray ¤t, const QByteArray &previous); virtual void iconSizeChanged(int current, int previous); - void resizeEvent(QGraphicsSceneResizeEvent* event) override; + void resizeEvent(QGraphicsSceneResizeEvent *event) override; void clearHoverCache(); /** @@ -234,7 +232,7 @@ protected: int hoverSequenceIndex() const; - const KItemListWidgetInformant* informant() const; + const KItemListWidgetInformant *informant() const; private Q_SLOTS: void slotHoverAnimationFinished(); @@ -243,12 +241,12 @@ private Q_SLOTS: private: void initializeSelectionToggle(); void setHoverOpacity(qreal opacity); - void drawItemStyleOption(QPainter* painter, QWidget* widget, QStyle::State styleState); + void drawItemStyleOption(QPainter *painter, QWidget *widget, QStyle::State styleState); private: Q_PROPERTY(qreal hoverOpacity READ hoverOpacity WRITE setHoverOpacity) - KItemListWidgetInformant* m_informant; + KItemListWidgetInformant *m_informant; int m_index; bool m_selected; bool m_current; @@ -264,23 +262,21 @@ private: QBitArray m_siblingsInfo; qreal m_hoverOpacity; - mutable QPixmap* m_hoverCache; - QPropertyAnimation* m_hoverAnimation; + mutable QPixmap *m_hoverCache; + QPropertyAnimation *m_hoverAnimation; int m_hoverSequenceIndex; QTimer m_hoverSequenceTimer; - KItemListSelectionToggle* m_selectionToggle; + KItemListSelectionToggle *m_selectionToggle; QByteArray m_editedRole; int m_iconSize; }; -inline const KItemListWidgetInformant* KItemListWidget::informant() const +inline const KItemListWidgetInformant *KItemListWidget::informant() const { return m_informant; } #endif - - diff --git a/src/kitemviews/kitemmodelbase.cpp b/src/kitemviews/kitemmodelbase.cpp index 5c6141ce22..e302d60939 100644 --- a/src/kitemviews/kitemmodelbase.cpp +++ b/src/kitemviews/kitemmodelbase.cpp @@ -8,19 +8,19 @@ #include "kitemmodelbase.h" -KItemModelBase::KItemModelBase(QObject* parent) : - QObject(parent), - m_groupedSorting(false), - m_sortRole(), - m_sortOrder(Qt::AscendingOrder) +KItemModelBase::KItemModelBase(QObject *parent) + : QObject(parent) + , m_groupedSorting(false) + , m_sortRole() + , m_sortOrder(Qt::AscendingOrder) { } -KItemModelBase::KItemModelBase(const QByteArray& sortRole, QObject* parent) : - QObject(parent), - m_groupedSorting(false), - m_sortRole(sortRole), - m_sortOrder(Qt::AscendingOrder) +KItemModelBase::KItemModelBase(const QByteArray &sortRole, QObject *parent) + : QObject(parent) + , m_groupedSorting(false) + , m_sortRole(sortRole) + , m_sortOrder(Qt::AscendingOrder) { } @@ -49,7 +49,7 @@ bool KItemModelBase::groupedSorting() const return m_groupedSorting; } -void KItemModelBase::setSortRole(const QByteArray& role, bool resortItems) +void KItemModelBase::setSortRole(const QByteArray &role, bool resortItems) { if (role != m_sortRole) { const QByteArray previous = m_sortRole; @@ -74,14 +74,14 @@ void KItemModelBase::setSortOrder(Qt::SortOrder order) } } -QString KItemModelBase::roleDescription(const QByteArray& role) const +QString KItemModelBase::roleDescription(const QByteArray &role) const { return role; } -QList > KItemModelBase::groups() const +QList> KItemModelBase::groups() const { - return QList >(); + return QList>(); } bool KItemModelBase::setExpanded(int index, bool expanded) @@ -109,13 +109,13 @@ int KItemModelBase::expandedParentsCount(int index) const return 0; } -QMimeData* KItemModelBase::createMimeData(const KItemSet& indexes) const +QMimeData *KItemModelBase::createMimeData(const KItemSet &indexes) const { Q_UNUSED(indexes) return nullptr; } -int KItemModelBase::indexForKeyboardSearch(const QString& text, int startFromIndex) const +int KItemModelBase::indexForKeyboardSearch(const QString &text, int startFromIndex) const { Q_UNUSED(text) Q_UNUSED(startFromIndex) @@ -138,7 +138,7 @@ void KItemModelBase::onGroupedSortingChanged(bool current) Q_UNUSED(current) } -void KItemModelBase::onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems) +void KItemModelBase::onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems) { Q_UNUSED(current) Q_UNUSED(previous) diff --git a/src/kitemviews/kitemmodelbase.h b/src/kitemviews/kitemmodelbase.h index 2ce4c9fd31..4e1fd8a8fe 100644 --- a/src/kitemviews/kitemmodelbase.h +++ b/src/kitemviews/kitemmodelbase.h @@ -40,8 +40,8 @@ class DOLPHIN_EXPORT KItemModelBase : public QObject Q_OBJECT public: - explicit KItemModelBase(QObject* parent = nullptr); - explicit KItemModelBase(const QByteArray& sortRole, QObject* parent = nullptr); + explicit KItemModelBase(QObject *parent = nullptr); + explicit KItemModelBase(const QByteArray &sortRole, QObject *parent = nullptr); ~KItemModelBase() override; /** @return The number of items. */ @@ -56,7 +56,7 @@ public: * The default implementation does not set the data, and will always return * false. */ - virtual bool setData(int index, const QHash& values); + virtual bool setData(int index, const QHash &values); /** * Enables/disables the grouped sorting. The method KItemModelBase::onGroupedSortingChanged() will be @@ -73,7 +73,7 @@ public: * signal sortRoleChanged() will be emitted. * The implementation should resort only if \a resortItems is true. */ - void setSortRole(const QByteArray& role, bool resortItems = true); + void setSortRole(const QByteArray &role, bool resortItems = true); QByteArray sortRole() const; /** @@ -88,7 +88,7 @@ public: * @return Translated description for the \p role. The description is e.g. used * for the header in KItemListView. */ - virtual QString roleDescription(const QByteArray& role) const; + virtual QString roleDescription(const QByteArray &role) const; /** * @return List of group headers. Each list-item consists of the index of the item @@ -96,7 +96,7 @@ public: * as QVariant. The value is shown by an instance of KItemListGroupHeader. * Per default an empty list is returned. */ - virtual QList > groups() const; + virtual QList> groups() const; /** * Expands the item with the index \a index if \a expanded is true. @@ -136,7 +136,7 @@ public: * caller of this method. The method must be implemented if dragging of * items should be possible. */ - virtual QMimeData* createMimeData(const KItemSet& indexes) const; + virtual QMimeData *createMimeData(const KItemSet &indexes) const; /** * @return Reimplement this to return the index for the first item @@ -144,7 +144,7 @@ public: * @param text the text which has been typed in through the keyboard * @param startFromIndex the index from which to start searching from */ - virtual int indexForKeyboardSearch(const QString& text, int startFromIndex = 0) const; + virtual int indexForKeyboardSearch(const QString &text, int startFromIndex = 0) const; /** * @return True, if the item with the index \a index basically supports dropping. @@ -196,7 +196,7 @@ Q_SIGNALS: * - They don't overlap * - The index of item-range n is smaller than the index of item-range n + 1. */ - void itemsInserted(const KItemRangeList& itemRanges); + void itemsInserted(const KItemRangeList &itemRanges); /** * Is emitted if one or more items have been removed. Each item-range consists @@ -210,7 +210,7 @@ Q_SIGNALS: * - They don't overlap * - The index of item-range n is smaller than the index of item-range n + 1. */ - void itemsRemoved(const KItemRangeList& itemRanges); + void itemsRemoved(const KItemRangeList &itemRanges); /** * Is emitted if one ore more items get moved. @@ -225,9 +225,9 @@ Q_SIGNALS: * This signal implies that the groups might have changed. Therefore, * gropusChanged() is not emitted if this signal is emitted. */ - void itemsMoved(const KItemRange& itemRange, const QList& movedToIndexes); + void itemsMoved(const KItemRange &itemRange, const QList &movedToIndexes); - void itemsChanged(const KItemRangeList& itemRanges, const QSet& roles); + void itemsChanged(const KItemRangeList &itemRanges, const QSet &roles); /** * Is emitted if the groups have changed, even though the order of the @@ -236,7 +236,7 @@ Q_SIGNALS: void groupsChanged(); void groupedSortingChanged(bool current); - void sortRoleChanged(const QByteArray& current, const QByteArray& previous); + void sortRoleChanged(const QByteArray ¤t, const QByteArray &previous); void sortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous); protected: @@ -255,7 +255,7 @@ protected: * itemsInserted() signal afterwards. * The implementation should resort only if \a resortItems is true. */ - virtual void onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems = true); + virtual void onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems = true); /** * Is invoked if the sort order has been changed by KItemModelBase::setSortOrder(). Allows @@ -279,5 +279,3 @@ inline Qt::SortOrder KItemModelBase::sortOrder() const } #endif - - diff --git a/src/kitemviews/kitemrange.h b/src/kitemviews/kitemrange.h index 0ea068062c..81d457aaa1 100644 --- a/src/kitemviews/kitemrange.h +++ b/src/kitemviews/kitemrange.h @@ -12,37 +12,41 @@ #include -struct KItemRange -{ +struct KItemRange { KItemRange(int index = 0, int count = 0); int index; int count; - bool operator == (const KItemRange& other) const; + bool operator==(const KItemRange &other) const; }; -inline KItemRange::KItemRange(int index, int count) : - index(index), - count(count) +inline KItemRange::KItemRange(int index, int count) + : index(index) + , count(count) { } -inline bool KItemRange::operator == (const KItemRange& other) const +inline bool KItemRange::operator==(const KItemRange &other) const { return index == other.index && count == other.count; } - class KItemRangeList : public QList { public: - KItemRangeList() : QList() {} - explicit KItemRangeList(const QList& list) : QList(list) {} + KItemRangeList() + : QList() + { + } + explicit KItemRangeList(const QList &list) + : QList(list) + { + } template - static KItemRangeList fromSortedContainer(const Container& container); + static KItemRangeList fromSortedContainer(const Container &container); - KItemRangeList& operator<<(const KItemRange& range) + KItemRangeList &operator<<(const KItemRange &range) { append(range); return *this; @@ -50,7 +54,7 @@ public: }; template -KItemRangeList KItemRangeList::fromSortedContainer(const Container& container) +KItemRangeList KItemRangeList::fromSortedContainer(const Container &container) { typename Container::const_iterator it = container.constBegin(); const typename Container::const_iterator end = container.constEnd(); diff --git a/src/kitemviews/kitemset.cpp b/src/kitemviews/kitemset.cpp index 1200bc7a97..b3a9909af3 100644 --- a/src/kitemviews/kitemset.cpp +++ b/src/kitemviews/kitemset.cpp @@ -6,7 +6,6 @@ #include "kitemset.h" - KItemSet::iterator KItemSet::insert(int i) { if (m_itemRanges.empty()) { @@ -128,7 +127,7 @@ KItemSet::iterator KItemSet::erase(iterator it) } } -KItemSet KItemSet::operator+(const KItemSet& other) const +KItemSet KItemSet::operator+(const KItemSet &other) const { KItemSet sum; @@ -170,8 +169,7 @@ KItemSet KItemSet::operator+(const KItemSet& other) const count = qMax(count, it2->index + it2->count - index); ++it2; } - } while ((it1 != end1 && it1->index <= index + count) - || (it2 != end2 && it2->index <= index + count)); + } while ((it1 != end1 && it1->index <= index + count) || (it2 != end2 && it2->index <= index + count)); sum.m_itemRanges.append(KItemRange(index, count)); } @@ -180,7 +178,7 @@ KItemSet KItemSet::operator+(const KItemSet& other) const return sum; } -KItemSet KItemSet::operator^(const KItemSet& other) const +KItemSet KItemSet::operator^(const KItemSet &other) const { // We are looking for all ints which are either in *this or in other, // but not in both. @@ -197,14 +195,14 @@ KItemSet KItemSet::operator^(const KItemSet& other) const const QVector::iterator end = rangeBoundaries.end(); QVector::iterator it = begin; - for (const KItemRange& range : qAsConst(m_itemRanges)) { + for (const KItemRange &range : qAsConst(m_itemRanges)) { *it++ = range.index; *it++ = range.index + range.count; } const QVector::iterator middle = it; - for (const KItemRange& range : qAsConst(other.m_itemRanges)) { + for (const KItemRange &range : qAsConst(other.m_itemRanges)) { *it++ = range.index; *it++ = range.index + range.count; } diff --git a/src/kitemviews/kitemset.h b/src/kitemviews/kitemset.h index 2d0137e0f0..fd73c0e02d 100644 --- a/src/kitemviews/kitemset.h +++ b/src/kitemviews/kitemset.h @@ -4,7 +4,6 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ - #ifndef KITEMSET_H #define KITEMSET_H @@ -33,9 +32,9 @@ class DOLPHIN_EXPORT KItemSet { public: KItemSet(); - KItemSet(const KItemSet& other); + KItemSet(const KItemSet &other); ~KItemSet(); - KItemSet& operator=(const KItemSet& other); + KItemSet &operator=(const KItemSet &other); /** * Returns the number of items in the set. @@ -46,25 +45,25 @@ public: bool isEmpty() const; void clear(); - bool operator==(const KItemSet& other) const; - bool operator!=(const KItemSet& other) const; + bool operator==(const KItemSet &other) const; + bool operator!=(const KItemSet &other) const; class iterator { - iterator(const KItemRangeList::iterator& rangeIt, int offset) : - m_rangeIt(rangeIt), - m_offset(offset) + iterator(const KItemRangeList::iterator &rangeIt, int offset) + : m_rangeIt(rangeIt) + , m_offset(offset) { } public: - iterator(const iterator& other) : - m_rangeIt(other.m_rangeIt), - m_offset(other.m_offset) + iterator(const iterator &other) + : m_rangeIt(other.m_rangeIt) + , m_offset(other.m_offset) { } - iterator& operator=(const iterator& other) + iterator &operator=(const iterator &other) { m_rangeIt = other.m_rangeIt; m_offset = other.m_offset; @@ -78,17 +77,17 @@ public: return m_rangeIt->index + m_offset; } - inline bool operator==(const iterator& other) const + inline bool operator==(const iterator &other) const { return m_rangeIt == other.m_rangeIt && m_offset == other.m_offset; } - inline bool operator!=(const iterator& other) const + inline bool operator!=(const iterator &other) const { return !(*this == other); } - inline iterator& operator++() + inline iterator &operator++() { ++m_offset; @@ -107,7 +106,7 @@ public: return r; } - inline iterator& operator--() + inline iterator &operator--() { if (m_offset == 0) { --m_rangeIt; @@ -134,29 +133,28 @@ public: friend class KItemSet; }; - class const_iterator { - const_iterator(KItemRangeList::const_iterator rangeIt, int offset) : - m_rangeIt(rangeIt), - m_offset(offset) + const_iterator(KItemRangeList::const_iterator rangeIt, int offset) + : m_rangeIt(rangeIt) + , m_offset(offset) { } public: - const_iterator(const const_iterator& other) : - m_rangeIt(other.m_rangeIt), - m_offset(other.m_offset) + const_iterator(const const_iterator &other) + : m_rangeIt(other.m_rangeIt) + , m_offset(other.m_offset) { } - explicit const_iterator(const iterator& other) : - m_rangeIt(other.m_rangeIt), - m_offset(other.m_offset) + explicit const_iterator(const iterator &other) + : m_rangeIt(other.m_rangeIt) + , m_offset(other.m_offset) { } - const_iterator& operator=(const const_iterator& other) + const_iterator &operator=(const const_iterator &other) { m_rangeIt = other.m_rangeIt; m_offset = other.m_offset; @@ -170,17 +168,17 @@ public: return m_rangeIt->index + m_offset; } - inline bool operator==(const const_iterator& other) const + inline bool operator==(const const_iterator &other) const { return m_rangeIt == other.m_rangeIt && m_offset == other.m_offset; } - inline bool operator!=(const const_iterator& other) const + inline bool operator!=(const const_iterator &other) const { return !(*this == other); } - inline const_iterator& operator++() + inline const_iterator &operator++() { ++m_offset; @@ -199,7 +197,7 @@ public: return r; } - inline const_iterator& operator--() + inline const_iterator &operator--() { if (m_offset == 0) { --m_rangeIt; @@ -246,16 +244,16 @@ public: * Returns a new set which contains all items that are contained in this * KItemSet, in \a other, or in both. */ - KItemSet operator+(const KItemSet& other) const; + KItemSet operator+(const KItemSet &other) const; /** * Returns a new set which contains all items that are contained either in * this KItemSet, or in \a other, but not in both (the symmetric difference * of both KItemSets). */ - KItemSet operator^(const KItemSet& other) const; + KItemSet operator^(const KItemSet &other) const; - KItemSet& operator<<(int i); + KItemSet &operator<<(int i); private: /** @@ -282,28 +280,28 @@ private: friend class KItemSetTest; }; -inline KItemSet::KItemSet() : - m_itemRanges() +inline KItemSet::KItemSet() + : m_itemRanges() { } -inline KItemSet::KItemSet(const KItemSet& other) : - m_itemRanges(other.m_itemRanges) +inline KItemSet::KItemSet(const KItemSet &other) + : m_itemRanges(other.m_itemRanges) { } inline KItemSet::~KItemSet() = default; -inline KItemSet& KItemSet::operator=(const KItemSet& other) +inline KItemSet &KItemSet::operator=(const KItemSet &other) { - m_itemRanges=other.m_itemRanges; + m_itemRanges = other.m_itemRanges; return *this; } inline int KItemSet::count() const { int result = 0; - for (const KItemRange& range : qAsConst(m_itemRanges)) { + for (const KItemRange &range : qAsConst(m_itemRanges)) { result += range.count; } return result; @@ -319,12 +317,12 @@ inline void KItemSet::clear() m_itemRanges.clear(); } -inline bool KItemSet::operator==(const KItemSet& other) const +inline bool KItemSet::operator==(const KItemSet &other) const { return m_itemRanges == other.m_itemRanges; } -inline bool KItemSet::operator!=(const KItemSet& other) const +inline bool KItemSet::operator!=(const KItemSet &other) const { return m_itemRanges != other.m_itemRanges; } @@ -403,11 +401,11 @@ inline int KItemSet::first() const inline int KItemSet::last() const { - const KItemRange& lastRange = m_itemRanges.last(); + const KItemRange &lastRange = m_itemRanges.last(); return lastRange.index + lastRange.count - 1; } -inline KItemSet& KItemSet::operator<<(int i) +inline KItemSet &KItemSet::operator<<(int i) { insert(i); return *this; diff --git a/src/kitemviews/kstandarditemlistgroupheader.cpp b/src/kitemviews/kstandarditemlistgroupheader.cpp index 28497ddfc2..e8468dacc5 100644 --- a/src/kitemviews/kstandarditemlistgroupheader.cpp +++ b/src/kitemviews/kstandarditemlistgroupheader.cpp @@ -11,20 +11,19 @@ #include #include -KStandardItemListGroupHeader::KStandardItemListGroupHeader(QGraphicsWidget* parent) : - KItemListGroupHeader(parent), - m_dirtyCache(true), - m_text(), - m_pixmap() +KStandardItemListGroupHeader::KStandardItemListGroupHeader(QGraphicsWidget *parent) + : KItemListGroupHeader(parent) + , m_dirtyCache(true) + , m_text() + , m_pixmap() { - } KStandardItemListGroupHeader::~KStandardItemListGroupHeader() { } -void KStandardItemListGroupHeader::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KStandardItemListGroupHeader::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if (m_dirtyCache) { updateCache(); @@ -32,7 +31,7 @@ void KStandardItemListGroupHeader::paint(QPainter* painter, const QStyleOptionGr KItemListGroupHeader::paint(painter, option, widget); } -void KStandardItemListGroupHeader::paintRole(QPainter* painter, const QRectF& roleBounds, const QColor& color) +void KStandardItemListGroupHeader::paintRole(QPainter *painter, const QRectF &roleBounds, const QColor &color) { if (m_pixmap.isNull()) { painter->setPen(color); @@ -42,7 +41,7 @@ void KStandardItemListGroupHeader::paintRole(QPainter* painter, const QRectF& ro } } -void KStandardItemListGroupHeader::paintSeparator(QPainter* painter, const QColor& color) +void KStandardItemListGroupHeader::paintSeparator(QPainter *painter, const QColor &color) { if (itemIndex() == 0) { // No top- or left-line should be drawn for the first group-header @@ -69,14 +68,14 @@ void KStandardItemListGroupHeader::roleChanged(const QByteArray ¤t, const m_dirtyCache = true; } -void KStandardItemListGroupHeader::dataChanged(const QVariant& current, const QVariant& previous) +void KStandardItemListGroupHeader::dataChanged(const QVariant ¤t, const QVariant &previous) { Q_UNUSED(current) Q_UNUSED(previous) m_dirtyCache = true; } -void KStandardItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent* event) +void KStandardItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent *event) { KItemListGroupHeader::resizeEvent(event); m_dirtyCache = true; @@ -110,4 +109,3 @@ void KStandardItemListGroupHeader::updateCache() m_text = text; } } - diff --git a/src/kitemviews/kstandarditemlistgroupheader.h b/src/kitemviews/kstandarditemlistgroupheader.h index adba009984..ee1df76fb9 100644 --- a/src/kitemviews/kstandarditemlistgroupheader.h +++ b/src/kitemviews/kstandarditemlistgroupheader.h @@ -17,17 +17,17 @@ class DOLPHIN_EXPORT KStandardItemListGroupHeader : public KItemListGroupHeader Q_OBJECT public: - explicit KStandardItemListGroupHeader(QGraphicsWidget* parent = nullptr); + explicit KStandardItemListGroupHeader(QGraphicsWidget *parent = nullptr); ~KStandardItemListGroupHeader() override; - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; protected: - void paintRole(QPainter* painter, const QRectF& roleBounds, const QColor& color) override; - void paintSeparator(QPainter* painter, const QColor& color) override; + void paintRole(QPainter *painter, const QRectF &roleBounds, const QColor &color) override; + void paintSeparator(QPainter *painter, const QColor &color) override; void roleChanged(const QByteArray ¤t, const QByteArray &previous) override; - void dataChanged(const QVariant& current, const QVariant& previous) override; - void resizeEvent(QGraphicsSceneResizeEvent* event) override; + void dataChanged(const QVariant ¤t, const QVariant &previous) override; + void resizeEvent(QGraphicsSceneResizeEvent *event) override; private: void updateCache(); @@ -38,5 +38,3 @@ private: QPixmap m_pixmap; }; #endif - - diff --git a/src/kitemviews/kstandarditemlistview.cpp b/src/kitemviews/kstandarditemlistview.cpp index 0ba23e654d..f94aed0b52 100644 --- a/src/kitemviews/kstandarditemlistview.cpp +++ b/src/kitemviews/kstandarditemlistview.cpp @@ -10,9 +10,9 @@ #include -KStandardItemListView::KStandardItemListView(QGraphicsWidget* parent) : - KItemListView(parent), - m_itemLayout(DetailsLayout) +KStandardItemListView::KStandardItemListView(QGraphicsWidget *parent) + : KItemListView(parent) + , m_itemLayout(DetailsLayout) { setAcceptDrops(true); setScrollOrientation(Qt::Vertical); @@ -50,34 +50,41 @@ KStandardItemListView::ItemLayout KStandardItemListView::itemLayout() const return m_itemLayout; } -KItemListWidgetCreatorBase* KStandardItemListView::defaultWidgetCreator() const +KItemListWidgetCreatorBase *KStandardItemListView::defaultWidgetCreator() const { return new KItemListWidgetCreator(); } -KItemListGroupHeaderCreatorBase* KStandardItemListView::defaultGroupHeaderCreator() const +KItemListGroupHeaderCreatorBase *KStandardItemListView::defaultGroupHeaderCreator() const { return new KItemListGroupHeaderCreator(); } -void KStandardItemListView::initializeItemListWidget(KItemListWidget* item) +void KStandardItemListView::initializeItemListWidget(KItemListWidget *item) { - KStandardItemListWidget* standardItemListWidget = qobject_cast(item); + KStandardItemListWidget *standardItemListWidget = qobject_cast(item); Q_ASSERT(standardItemListWidget); switch (itemLayout()) { - case IconsLayout: standardItemListWidget->setLayout(KStandardItemListWidget::IconsLayout); break; - case CompactLayout: standardItemListWidget->setLayout(KStandardItemListWidget::CompactLayout); break; - case DetailsLayout: standardItemListWidget->setLayout(KStandardItemListWidget::DetailsLayout); break; - default: Q_ASSERT(false); break; + case IconsLayout: + standardItemListWidget->setLayout(KStandardItemListWidget::IconsLayout); + break; + case CompactLayout: + standardItemListWidget->setLayout(KStandardItemListWidget::CompactLayout); + break; + case DetailsLayout: + standardItemListWidget->setLayout(KStandardItemListWidget::DetailsLayout); + break; + default: + Q_ASSERT(false); + break; } standardItemListWidget->setHighlightEntireRow(highlightEntireRow()); standardItemListWidget->setSupportsItemExpanding(supportsItemExpanding()); } - -bool KStandardItemListView::itemSizeHintUpdateRequired(const QSet& changedRoles) const +bool KStandardItemListView::itemSizeHintUpdateRequired(const QSet &changedRoles) const { // The only thing that can modify the item's size hint is the amount of space // needed to display the text for the visible roles. @@ -85,7 +92,7 @@ bool KStandardItemListView::itemSizeHintUpdateRequired(const QSet& c // the area defined by KItemStyleOption.iconSize and hence result in no // change of the item-size. const auto roles = visibleRoles(); - for (const QByteArray& role : roles) { + for (const QByteArray &role : roles) { if (changedRoles.contains(role)) { return true; } @@ -123,23 +130,27 @@ void KStandardItemListView::onSupportsItemExpandingChanged(bool supportsExpandin updateLayoutOfVisibleItems(); } - void KStandardItemListView::polishEvent() { switch (m_itemLayout) { - case IconsLayout: applyDefaultStyleOption(style()->pixelMetric(QStyle::PM_LargeIconSize), 2, 4, 8); break; - case CompactLayout: applyDefaultStyleOption(style()->pixelMetric(QStyle::PM_SmallIconSize), 2, 8, 0); break; - case DetailsLayout: applyDefaultStyleOption(style()->pixelMetric(QStyle::PM_SmallIconSize), 2, 0, 0); break; - default: Q_ASSERT(false); break; + case IconsLayout: + applyDefaultStyleOption(style()->pixelMetric(QStyle::PM_LargeIconSize), 2, 4, 8); + break; + case CompactLayout: + applyDefaultStyleOption(style()->pixelMetric(QStyle::PM_SmallIconSize), 2, 8, 0); + break; + case DetailsLayout: + applyDefaultStyleOption(style()->pixelMetric(QStyle::PM_SmallIconSize), 2, 0, 0); + break; + default: + Q_ASSERT(false); + break; } QGraphicsWidget::polishEvent(); } -void KStandardItemListView::applyDefaultStyleOption(int iconSize, - int padding, - int horizontalMargin, - int verticalMargin) +void KStandardItemListView::applyDefaultStyleOption(int iconSize, int padding, int horizontalMargin, int verticalMargin) { KItemListStyleOption option = styleOption(); @@ -163,9 +174,8 @@ void KStandardItemListView::updateLayoutOfVisibleItems() { if (model()) { const auto widgets = visibleItemListWidgets(); - for (KItemListWidget* widget : widgets) { + for (KItemListWidget *widget : widgets) { initializeItemListWidget(widget); } } } - diff --git a/src/kitemviews/kstandarditemlistview.h b/src/kitemviews/kstandarditemlistview.h index 527d14b9d1..3963837186 100644 --- a/src/kitemviews/kstandarditemlistview.h +++ b/src/kitemviews/kstandarditemlistview.h @@ -31,24 +31,19 @@ class DOLPHIN_EXPORT KStandardItemListView : public KItemListView Q_OBJECT public: - enum ItemLayout - { - IconsLayout, - CompactLayout, - DetailsLayout - }; + enum ItemLayout { IconsLayout, CompactLayout, DetailsLayout }; - explicit KStandardItemListView(QGraphicsWidget* parent = nullptr); + explicit KStandardItemListView(QGraphicsWidget *parent = nullptr); ~KStandardItemListView() override; void setItemLayout(ItemLayout layout); ItemLayout itemLayout() const; protected: - KItemListWidgetCreatorBase* defaultWidgetCreator() const override; - KItemListGroupHeaderCreatorBase* defaultGroupHeaderCreator() const override; - void initializeItemListWidget(KItemListWidget* item) override; - bool itemSizeHintUpdateRequired(const QSet& changedRoles) const override; + KItemListWidgetCreatorBase *defaultWidgetCreator() const override; + KItemListGroupHeaderCreatorBase *defaultGroupHeaderCreator() const override; + void initializeItemListWidget(KItemListWidget *item) override; + bool itemSizeHintUpdateRequired(const QSet &changedRoles) const override; virtual bool itemLayoutSupportsItemExpanding(ItemLayout layout) const; /** To be overriden by sub-classes to specify when full row highlighting should be enabled. */ virtual bool itemLayoutHighlightEntireRow(ItemLayout layout) const; @@ -66,5 +61,3 @@ private: }; #endif - - diff --git a/src/kitemviews/kstandarditemlistwidget.cpp b/src/kitemviews/kstandarditemlistwidget.cpp index ddc7c29881..afe6143634 100644 --- a/src/kitemviews/kstandarditemlistwidget.cpp +++ b/src/kitemviews/kstandarditemlistwidget.cpp @@ -26,8 +26,8 @@ // #define KSTANDARDITEMLISTWIDGET_DEBUG -KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() : - KItemListWidgetInformant() +KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() + : KItemListWidgetInformant() { } @@ -35,9 +35,11 @@ KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant() { } -void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const +void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector> &logicalHeightHints, + qreal &logicalWidthHint, + const KItemListView *view) const { - switch (static_cast(view)->itemLayout()) { + switch (static_cast(view)->itemLayout()) { case KStandardItemListView::IconsLayout: calculateIconsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view); break; @@ -56,24 +58,22 @@ void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector values = view->model()->data(index); - const KItemListStyleOption& option = view->styleOption(); + const KItemListStyleOption &option = view->styleOption(); const QString text = roleText(role, values); qreal width = KStandardItemListWidget::columnPadding(option); - const QFontMetrics& normalFontMetrics = option.fontMetrics; + const QFontMetrics &normalFontMetrics = option.fontMetrics; const QFontMetrics linkFontMetrics(customizedFontForLinks(option.font)); if (role == "rating") { width += KStandardItemListWidget::preferredRatingSize(option).width(); } else { // If current item is a link, we use the customized link font metrics instead of the normal font metrics. - const QFontMetrics& fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics; + const QFontMetrics &fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics; width += fontMetrics.horizontalAdvance(text); @@ -93,20 +93,19 @@ qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArra return width; } -QString KStandardItemListWidgetInformant::itemText(int index, const KItemListView* view) const +QString KStandardItemListWidgetInformant::itemText(int index, const KItemListView *view) const { return view->model()->data(index).value("text").toString(); } -bool KStandardItemListWidgetInformant::itemIsLink(int index, const KItemListView* view) const +bool KStandardItemListWidgetInformant::itemIsLink(int index, const KItemListView *view) const { Q_UNUSED(index) Q_UNUSED(view) return false; } -QString KStandardItemListWidgetInformant::roleText(const QByteArray& role, - const QHash& values) const +QString KStandardItemListWidgetInformant::roleText(const QByteArray &role, const QHash &values) const { if (role == "rating") { // Always use an empty text, as the rating is shown by the image m_rating. @@ -115,15 +114,17 @@ QString KStandardItemListWidgetInformant::roleText(const QByteArray& role, return values.value(role).toString(); } -QFont KStandardItemListWidgetInformant::customizedFontForLinks(const QFont& baseFont) const +QFont KStandardItemListWidgetInformant::customizedFontForLinks(const QFont &baseFont) const { return baseFont; } -void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const +void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector> &logicalHeightHints, + qreal &logicalWidthHint, + const KItemListView *view) const { - const KItemListStyleOption& option = view->styleOption(); - const QFont& normalFont = option.font; + const KItemListStyleOption &option = view->styleOption(); + const QFont &normalFont = option.font; const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0); const qreal itemWidth = view->itemSize().width(); @@ -142,10 +143,10 @@ void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector } // If the current item is a link, we use the customized link font instead of the normal font. - const QFont& font = itemIsLink(index, view) ? linkFont : normalFont; + const QFont &font = itemIsLink(index, view) ? linkFont : normalFont; + + const QString &text = KStringHandler::preProcessWrap(itemText(index, view)); - const QString& text = KStringHandler::preProcessWrap(itemText(index, view)); - // Calculate the number of lines required for wrapping the name qreal textHeight = 0; QTextLayout layout(text, font); @@ -177,13 +178,15 @@ void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector logicalWidthHint = itemWidth; } -void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const +void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector> &logicalHeightHints, + qreal &logicalWidthHint, + const KItemListView *view) const { - const KItemListStyleOption& option = view->styleOption(); - const QFontMetrics& normalFontMetrics = option.fontMetrics; + const KItemListStyleOption &option = view->styleOption(); + const QFontMetrics &normalFontMetrics = option.fontMetrics; const int additionalRolesCount = qMax(view->visibleRoles().count() - 1, 0); - const QList& visibleRoles = view->visibleRoles(); + const QList &visibleRoles = view->visibleRoles(); const bool showOnlyTextRole = (visibleRoles.count() == 1) && (visibleRoles.first() == "text"); const qreal maxWidth = option.maxTextWidth; const qreal paddingAndIconWidth = option.padding * 4 + option.iconSize; @@ -197,7 +200,7 @@ void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVect } // If the current item is a link, we use the customized link font metrics instead of the normal font metrics. - const QFontMetrics& fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics; + const QFontMetrics &fontMetrics = itemIsLink(index, view) ? linkFontMetrics : normalFontMetrics; // For each row exactly one role is shown. Calculate the maximum required width that is necessary // to show all roles without horizontal clipping. @@ -206,9 +209,9 @@ void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVect if (showOnlyTextRole) { maximumRequiredWidth = fontMetrics.horizontalAdvance(itemText(index, view)); } else { - const QHash& values = view->model()->data(index); - for (const QByteArray& role : visibleRoles) { - const QString& text = roleText(role, values); + const QHash &values = view->model()->data(index); + for (const QByteArray &role : visibleRoles) { + const QString &text = roleText(role, values); const qreal requiredWidth = fontMetrics.horizontalAdvance(text); maximumRequiredWidth = qMax(maximumRequiredWidth, requiredWidth); } @@ -225,43 +228,45 @@ void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVect logicalWidthHint = height; } -void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const +void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector> &logicalHeightHints, + qreal &logicalWidthHint, + const KItemListView *view) const { - const KItemListStyleOption& option = view->styleOption(); + const KItemListStyleOption &option = view->styleOption(); const qreal height = option.padding * 2 + qMax(option.iconSize, option.fontMetrics.height()); logicalHeightHints.fill(std::make_pair(height, false)); logicalWidthHint = -1.0; } -KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) : - KItemListWidget(informant, parent), - m_textInfo(), - m_isCut(false), - m_isHidden(false), - m_customizedFont(), - m_customizedFontMetrics(m_customizedFont), - m_isExpandable(false), - m_highlightEntireRow(false), - m_supportsItemExpanding(false), - m_dirtyLayout(true), - m_dirtyContent(true), - m_dirtyContentRoles(), - m_layout(IconsLayout), - m_pixmapPos(), - m_pixmap(), - m_scaledPixmapSize(), - m_columnWidthSum(), - m_iconRect(), - m_hoverPixmap(), - m_textRect(), - m_sortedVisibleRoles(), - m_expansionArea(), - m_customTextColor(), - m_additionalInfoTextColor(), - m_overlay(), - m_rating(), - m_roleEditor(nullptr), - m_oldRoleEditor(nullptr) +KStandardItemListWidget::KStandardItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent) + : KItemListWidget(informant, parent) + , m_textInfo() + , m_isCut(false) + , m_isHidden(false) + , m_customizedFont() + , m_customizedFontMetrics(m_customizedFont) + , m_isExpandable(false) + , m_highlightEntireRow(false) + , m_supportsItemExpanding(false) + , m_dirtyLayout(true) + , m_dirtyContent(true) + , m_dirtyContentRoles() + , m_layout(IconsLayout) + , m_pixmapPos() + , m_pixmap() + , m_scaledPixmapSize() + , m_columnWidthSum() + , m_iconRect() + , m_hoverPixmap() + , m_textRect() + , m_sortedVisibleRoles() + , m_expansionArea() + , m_customTextColor() + , m_additionalInfoTextColor() + , m_overlay() + , m_rating() + , m_roleEditor(nullptr) + , m_oldRoleEditor(nullptr) { } @@ -294,7 +299,8 @@ KStandardItemListWidget::Layout KStandardItemListWidget::layout() const return m_layout; } -void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow) { +void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow) +{ if (m_highlightEntireRow != highlightEntireRow) { m_highlightEntireRow = highlightEntireRow; m_dirtyLayout = true; @@ -302,7 +308,8 @@ void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow) { } } -bool KStandardItemListWidget::highlightEntireRow() const { +bool KStandardItemListWidget::highlightEntireRow() const +{ return m_highlightEntireRow; } @@ -320,9 +327,9 @@ bool KStandardItemListWidget::supportsItemExpanding() const return m_supportsItemExpanding; } -void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KStandardItemListWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); KItemListWidget::paint(painter, option, widget); @@ -330,7 +337,7 @@ void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphic drawSiblingsInformation(painter); } - const KItemListStyleOption& itemListStyleOption = styleOption(); + const KItemListStyleOption &itemListStyleOption = styleOption(); if (isHovered() && !m_pixmap.isNull()) { if (hoverOpacity() < 1.0) { /* @@ -380,7 +387,7 @@ void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphic painter->setFont(m_customizedFont); painter->setPen(textColor()); - const TextInfo* textInfo = m_textInfo.value("text"); + const TextInfo *textInfo = m_textInfo.value("text"); if (!textInfo) { // It seems that we can end up here even if m_textInfo does not contain @@ -410,12 +417,12 @@ void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphic painter->setFont(m_customizedFont); for (int i = 1; i < m_sortedVisibleRoles.count(); ++i) { - const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles[i]); + const TextInfo *textInfo = m_textInfo.value(m_sortedVisibleRoles[i]); painter->drawStaticText(textInfo->pos, textInfo->staticText); } if (!m_rating.isNull()) { - const TextInfo* ratingTextInfo = m_textInfo.value("rating"); + const TextInfo *ratingTextInfo = m_textInfo.value("rating"); QPointF pos = ratingTextInfo->pos; const Qt::Alignment align = ratingTextInfo->staticText.textOption().alignment(); if (align & Qt::AlignHCenter) { @@ -444,13 +451,13 @@ void KStandardItemListWidget::paint(QPainter* painter, const QStyleOptionGraphic QRectF KStandardItemListWidget::iconRect() const { - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); return m_iconRect; } QRectF KStandardItemListWidget::textRect() const { - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); return m_textRect; } @@ -461,13 +468,13 @@ QRectF KStandardItemListWidget::textFocusRect() const // when having a quite large icon size but only one line of text. Still the // focus rectangle should be shown as narrow as possible around the text. - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); switch (m_layout) { case CompactLayout: { QRectF rect = m_textRect; - const TextInfo* topText = m_textInfo.value(m_sortedVisibleRoles.first()); - const TextInfo* bottomText = m_textInfo.value(m_sortedVisibleRoles.last()); + const TextInfo *topText = m_textInfo.value(m_sortedVisibleRoles.first()); + const TextInfo *bottomText = m_textInfo.value(m_sortedVisibleRoles.last()); rect.setTop(topText->pos.y()); rect.setBottom(bottomText->pos.y() + bottomText->staticText.size().height()); return rect; @@ -475,11 +482,11 @@ QRectF KStandardItemListWidget::textFocusRect() const case DetailsLayout: { QRectF rect = m_textRect; - const TextInfo* textInfo = m_textInfo.value(m_sortedVisibleRoles.first()); + const TextInfo *textInfo = m_textInfo.value(m_sortedVisibleRoles.first()); rect.setTop(textInfo->pos.y()); rect.setBottom(textInfo->pos.y() + textInfo->staticText.size().height()); - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); if (option.extendedSelectionRegion) { const QString text = textInfo->staticText.text(); rect.setWidth(m_customizedFontMetrics.horizontalAdvance(text) + 2 * option.padding); @@ -497,7 +504,7 @@ QRectF KStandardItemListWidget::textFocusRect() const QRectF KStandardItemListWidget::selectionRect() const { - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); switch (m_layout) { case IconsLayout: @@ -524,13 +531,13 @@ QRectF KStandardItemListWidget::selectionRect() const QRectF KStandardItemListWidget::expansionToggleRect() const { - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); return m_isExpandable ? m_expansionArea : QRectF(); } QRectF KStandardItemListWidget::selectionToggleRect() const { - const_cast(this)->triggerCacheRefreshing(); + const_cast(this)->triggerCacheRefreshing(); const int widgetIconSize = iconSize(); int toggleSize = KIconLoader::SizeSmall; @@ -564,8 +571,7 @@ QRectF KStandardItemListWidget::selectionToggleRect() const return QRectF(pos, QSizeF(toggleSize, toggleSize)); } -QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem* option, - QWidget* widget) +QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem *option, QWidget *widget) { QPixmap pixmap = KItemListWidget::createDragPixmap(option, widget); if (m_layout != DetailsLayout) { @@ -575,10 +581,8 @@ QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem // Only return the content of the text-column as pixmap const int leftClip = m_pixmapPos.x(); - const TextInfo* textInfo = m_textInfo.value("text"); - const int rightClip = textInfo->pos.x() + - textInfo->staticText.size().width() + - 2 * styleOption().padding; + const TextInfo *textInfo = m_textInfo.value("text"); + const int rightClip = textInfo->pos.x() + textInfo->staticText.size().width() + 2 * styleOption().padding; QPixmap clippedPixmap(rightClip - leftClip + 1, pixmap.height()); clippedPixmap.fill(Qt::transparent); @@ -589,8 +593,7 @@ QPixmap KStandardItemListWidget::createDragPixmap(const QStyleOptionGraphicsItem return clippedPixmap; } - -KItemListWidgetInformant* KStandardItemListWidget::createInformant() +KItemListWidgetInformant *KStandardItemListWidget::createInformant() { return new KStandardItemListWidgetInformant(); } @@ -612,7 +615,7 @@ void KStandardItemListWidget::refreshCache() { } -bool KStandardItemListWidget::isRoleRightAligned(const QByteArray& role) const +bool KStandardItemListWidget::isRoleRightAligned(const QByteArray &role) const { Q_UNUSED(role) return false; @@ -623,7 +626,7 @@ bool KStandardItemListWidget::isHidden() const return false; } -QFont KStandardItemListWidget::customizedFont(const QFont& baseFont) const +QFont KStandardItemListWidget::customizedFont(const QFont &baseFont) const { return baseFont; } @@ -633,7 +636,7 @@ QPalette::ColorRole KStandardItemListWidget::normalTextColorRole() const return QPalette::Text; } -void KStandardItemListWidget::setTextColor(const QColor& color) +void KStandardItemListWidget::setTextColor(const QColor &color) { if (color != m_customTextColor) { m_customTextColor = color; @@ -657,7 +660,7 @@ QColor KStandardItemListWidget::textColor() const return styleOption().palette.color(group, role); } -void KStandardItemListWidget::setOverlay(const QPixmap& overlay) +void KStandardItemListWidget::setOverlay(const QPixmap &overlay) { m_overlay = overlay; m_dirtyContent = true; @@ -669,15 +672,12 @@ QPixmap KStandardItemListWidget::overlay() const return m_overlay; } - -QString KStandardItemListWidget::roleText(const QByteArray& role, - const QHash& values) const +QString KStandardItemListWidget::roleText(const QByteArray &role, const QHash &values) const { - return static_cast(informant())->roleText(role, values); + return static_cast(informant())->roleText(role, values); } -void KStandardItemListWidget::dataChanged(const QHash& current, - const QSet& roles) +void KStandardItemListWidget::dataChanged(const QHash ¤t, const QSet &roles) { Q_UNUSED(current) @@ -693,7 +693,7 @@ void KStandardItemListWidget::dataChanged(const QHash& cur // The URL might have changed (i.e., if the sort order of the items has // been changed). Therefore, the "is cut" state must be updated. - KFileItemClipboard* clipboard = KFileItemClipboard::instance(); + KFileItemClipboard *clipboard = KFileItemClipboard::instance(); const QUrl itemUrl = data().value("url").toUrl(); m_isCut = clipboard->isCut(itemUrl); @@ -704,22 +704,19 @@ void KStandardItemListWidget::dataChanged(const QHash& cur QSetIterator it(dirtyRoles); while (it.hasNext()) { - const QByteArray& role = it.next(); + const QByteArray &role = it.next(); m_dirtyContentRoles.insert(role); } } -void KStandardItemListWidget::visibleRolesChanged(const QList& current, - const QList& previous) +void KStandardItemListWidget::visibleRolesChanged(const QList ¤t, const QList &previous) { Q_UNUSED(previous) m_sortedVisibleRoles = current; m_dirtyLayout = true; } -void KStandardItemListWidget::columnWidthChanged(const QByteArray& role, - qreal current, - qreal previous) +void KStandardItemListWidget::columnWidthChanged(const QByteArray &role, qreal current, qreal previous) { Q_UNUSED(role) Q_UNUSED(current) @@ -727,13 +724,13 @@ void KStandardItemListWidget::columnWidthChanged(const QByteArray& role, m_dirtyLayout = true; } -void KStandardItemListWidget::sidePaddingChanged(qreal padding) { +void KStandardItemListWidget::sidePaddingChanged(qreal padding) +{ Q_UNUSED(padding) m_dirtyLayout = true; } -void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current, - const KItemListStyleOption& previous) +void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) { KItemListWidget::styleOptionChanged(current, previous); @@ -754,31 +751,29 @@ void KStandardItemListWidget::selectedChanged(bool selected) m_dirtyContent = true; } -void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous) +void KStandardItemListWidget::siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) m_dirtyLayout = true; } -int KStandardItemListWidget::selectionLength(const QString& text) const +int KStandardItemListWidget::selectionLength(const QString &text) const { return text.length(); } -void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous) +void KStandardItemListWidget::editedRoleChanged(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(previous) - QGraphicsView* parent = scene()->views()[0]; + QGraphicsView *parent = scene()->views()[0]; if (current.isEmpty() || !parent || current != "text") { if (m_roleEditor) { Q_EMIT roleEditingCanceled(index(), current, data().value(current)); - disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, - this, &KStandardItemListWidget::slotRoleEditingCanceled); - disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, - this, &KStandardItemListWidget::slotRoleEditingFinished); + disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled); + disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished); if (m_oldRoleEditor) { m_oldRoleEditor->deleteLater(); @@ -792,7 +787,7 @@ void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const Q_ASSERT(!m_roleEditor); - const TextInfo* textInfo = m_textInfo.value("text"); + const TextInfo *textInfo = m_textInfo.value("text"); m_roleEditor = new KItemListRoleEditor(parent); m_roleEditor->setRole(current); @@ -814,10 +809,8 @@ void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const m_roleEditor->setTextCursor(cursor); } - connect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, - this, &KStandardItemListWidget::slotRoleEditingCanceled); - connect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, - this, &KStandardItemListWidget::slotRoleEditingFinished); + connect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled); + connect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished); // Adjust the geometry of the editor QRectF rect = roleEditingRect(current); @@ -841,7 +834,7 @@ void KStandardItemListWidget::iconSizeChanged(int current, int previous) update(); } -void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event) +void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent *event) { if (m_roleEditor) { setEditedRole(QByteArray()); @@ -853,32 +846,29 @@ void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event) m_dirtyLayout = true; } -void KStandardItemListWidget::showEvent(QShowEvent* event) +void KStandardItemListWidget::showEvent(QShowEvent *event) { KItemListWidget::showEvent(event); // Listen to changes of the clipboard to mark the item as cut/uncut - KFileItemClipboard* clipboard = KFileItemClipboard::instance(); + KFileItemClipboard *clipboard = KFileItemClipboard::instance(); const QUrl itemUrl = data().value("url").toUrl(); m_isCut = clipboard->isCut(itemUrl); - connect(clipboard, &KFileItemClipboard::cutItemsChanged, - this, &KStandardItemListWidget::slotCutItemsChanged); + connect(clipboard, &KFileItemClipboard::cutItemsChanged, this, &KStandardItemListWidget::slotCutItemsChanged); } -void KStandardItemListWidget::hideEvent(QHideEvent* event) +void KStandardItemListWidget::hideEvent(QHideEvent *event) { - disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged, - this, &KStandardItemListWidget::slotCutItemsChanged); + disconnect(KFileItemClipboard::instance(), &KFileItemClipboard::cutItemsChanged, this, &KStandardItemListWidget::slotCutItemsChanged); KItemListWidget::hideEvent(event); } bool KStandardItemListWidget::event(QEvent *event) { - if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate - || event->type() == QEvent::PaletteChange) { + if (event->type() == QEvent::WindowDeactivate || event->type() == QEvent::WindowActivate || event->type() == QEvent::PaletteChange) { m_dirtyContent = true; } @@ -904,16 +894,14 @@ void KStandardItemListWidget::slotCutItemsChanged() } } -void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray& role, - const QVariant& value) +void KStandardItemListWidget::slotRoleEditingCanceled(const QByteArray &role, const QVariant &value) { closeRoleEditor(); Q_EMIT roleEditingCanceled(index(), role, value); setEditedRole(QByteArray()); } -void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray& role, - const QVariant& value) +void KStandardItemListWidget::slotRoleEditingFinished(const QByteArray &role, const QVariant &value) { closeRoleEditor(); Q_EMIT roleEditingFinished(index(), role, value); @@ -933,8 +921,9 @@ void KStandardItemListWidget::triggerCacheRefreshing() m_isHidden = isHidden(); m_customizedFont = customizedFont(styleOption().font); m_customizedFontMetrics = QFontMetrics(m_customizedFont); - m_columnWidthSum = std::accumulate(m_sortedVisibleRoles.begin(), m_sortedVisibleRoles.end(), - qreal(), [this](qreal sum, const auto &role){ return sum + columnWidth(role); }); + m_columnWidthSum = std::accumulate(m_sortedVisibleRoles.begin(), m_sortedVisibleRoles.end(), qreal(), [this](qreal sum, const auto &role) { + return sum + columnWidth(role); + }); updateExpansionArea(); updateTextsCache(); @@ -973,7 +962,7 @@ void KStandardItemListWidget::updatePixmapCache() const QSizeF widgetSize = size(); const bool iconOnTop = (m_layout == IconsLayout); - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); const qreal padding = option.padding; const int widgetIconSize = iconSize(); @@ -984,10 +973,8 @@ void KStandardItemListWidget::updatePixmapCache() bool updatePixmap = (m_pixmap.width() != maxIconWidth || m_pixmap.height() != maxIconHeight); if (!updatePixmap && m_dirtyContent) { - updatePixmap = m_dirtyContentRoles.isEmpty() - || m_dirtyContentRoles.contains("iconPixmap") - || m_dirtyContentRoles.contains("iconName") - || m_dirtyContentRoles.contains("iconOverlays"); + updatePixmap = m_dirtyContentRoles.isEmpty() || m_dirtyContentRoles.contains("iconPixmap") || m_dirtyContentRoles.contains("iconName") + || m_dirtyContentRoles.contains("iconOverlays"); } if (updatePixmap) { @@ -1008,7 +995,7 @@ void KStandardItemListWidget::updatePixmapCache() } } - const int loadedIndex = qMax(qMin(sequenceIndex, pixmaps.size()-1), 0); + const int loadedIndex = qMax(qMin(sequenceIndex, pixmaps.size() - 1), 0); if (loadedIndex != 0) { m_pixmap = pixmaps[loadedIndex]; @@ -1028,7 +1015,8 @@ void KStandardItemListWidget::updatePixmapCache() iconName = QStringLiteral("unknown"); } const QStringList overlays = values["iconOverlays"].toStringList(); - m_pixmap = pixmapForIcon(iconName, overlays, maxIconHeight, m_layout != IconsLayout && isActiveWindow() && isSelected() ? QIcon::Selected : QIcon::Normal); + m_pixmap = + pixmapForIcon(iconName, overlays, maxIconHeight, m_layout != IconsLayout && isActiveWindow() && isSelected() ? QIcon::Selected : QIcon::Normal); } else if (m_pixmap.width() / m_pixmap.devicePixelRatio() != maxIconWidth || m_pixmap.height() / m_pixmap.devicePixelRatio() != maxIconHeight) { // A custom pixmap has been applied. Assure that the pixmap @@ -1042,7 +1030,7 @@ void KStandardItemListWidget::updatePixmapCache() } if (m_isCut) { - KIconEffect* effect = KIconLoader::global()->iconEffect(); + KIconEffect *effect = KIconLoader::global()->iconEffect(); m_pixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::DisabledState); } @@ -1069,13 +1057,12 @@ void KStandardItemListWidget::updatePixmapCache() int scaledIconSize = 0; if (iconOnTop) { - const TextInfo* textInfo = m_textInfo.value("text"); + const TextInfo *textInfo = m_textInfo.value("text"); scaledIconSize = static_cast(textInfo->pos.y() - 2 * padding); } else { const int textRowsCount = (m_layout == CompactLayout) ? visibleRoles().count() : 1; const qreal requiredTextHeight = textRowsCount * m_customizedFontMetrics.height(); - scaledIconSize = (requiredTextHeight < maxIconHeight) ? - widgetSize.height() - 2 * padding : maxIconHeight; + scaledIconSize = (requiredTextHeight < maxIconHeight) ? widgetSize.height() - 2 * padding : maxIconHeight; } const int maxScaledIconWidth = iconOnTop ? widgetSize.width() - 2 * padding : scaledIconSize; @@ -1091,17 +1078,13 @@ void KStandardItemListWidget::updatePixmapCache() m_pixmapPos.setY(padding + scaledIconSize - m_scaledPixmapSize.height()); } else { // Center horizontally and vertically within the icon-area - const TextInfo* textInfo = m_textInfo.value("text"); - m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding - - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0); + const TextInfo *textInfo = m_textInfo.value("text"); + m_pixmapPos.setX(textInfo->pos.x() - 2.0 * padding - (scaledIconSize + m_scaledPixmapSize.width()) / 2.0); // Derive icon's vertical center from the center of the text frame, including // any necessary adjustment if the font's midline is offset from the frame center - const qreal midlineShift = m_customizedFontMetrics.height() / 2.0 - - m_customizedFontMetrics.descent() - - m_customizedFontMetrics.capHeight() / 2.0; + const qreal midlineShift = m_customizedFontMetrics.height() / 2.0 - m_customizedFontMetrics.descent() - m_customizedFontMetrics.capHeight() / 2.0; m_pixmapPos.setY(m_textRect.center().y() + midlineShift - m_scaledPixmapSize.height() / 2.0); - } if (m_layout == IconsLayout) { @@ -1109,8 +1092,7 @@ void KStandardItemListWidget::updatePixmapCache() } else { const qreal widthOffset = widgetIconSize - m_scaledPixmapSize.width(); const qreal heightOffset = widgetIconSize - m_scaledPixmapSize.height(); - const QPointF squareIconPos(m_pixmapPos.x() - 0.5 * widthOffset, - m_pixmapPos.y() - 0.5 * heightOffset); + const QPointF squareIconPos(m_pixmapPos.x() - 0.5 * widthOffset, m_pixmapPos.y() - 0.5 * heightOffset); const QSizeF squareIconSize(widgetIconSize, widgetIconSize); m_iconRect = QRectF(squareIconPos, squareIconSize); } @@ -1118,7 +1100,7 @@ void KStandardItemListWidget::updatePixmapCache() // Prepare the pixmap that is used when the item gets hovered if (isHovered()) { m_hoverPixmap = m_pixmap; - KIconEffect* effect = KIconLoader::global()->iconEffect(); + KIconEffect *effect = KIconLoader::global()->iconEffect(); // In the KIconLoader terminology, active = hover. if (effect->hasEffect(KIconLoader::Desktop, KIconLoader::ActiveState)) { m_hoverPixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::ActiveState); @@ -1152,7 +1134,7 @@ void KStandardItemListWidget::updateTextsCache() qDeleteAll(m_textInfo); m_textInfo.clear(); for (int i = 0; i < m_sortedVisibleRoles.count(); ++i) { - TextInfo* textInfo = new TextInfo(); + TextInfo *textInfo = new TextInfo(); textInfo->staticText.setTextFormat(Qt::PlainText); textInfo->staticText.setPerformanceHint(QStaticText::AggressiveCaching); textInfo->staticText.setTextOption(textOption); @@ -1160,22 +1142,28 @@ void KStandardItemListWidget::updateTextsCache() } switch (m_layout) { - case IconsLayout: updateIconsLayoutTextCache(); break; - case CompactLayout: updateCompactLayoutTextCache(); break; - case DetailsLayout: updateDetailsLayoutTextCache(); break; - default: Q_ASSERT(false); break; + case IconsLayout: + updateIconsLayoutTextCache(); + break; + case CompactLayout: + updateCompactLayoutTextCache(); + break; + case DetailsLayout: + updateDetailsLayoutTextCache(); + break; + default: + Q_ASSERT(false); + break; } - const TextInfo* ratingTextInfo = m_textInfo.value("rating"); + const TextInfo *ratingTextInfo = m_textInfo.value("rating"); if (ratingTextInfo) { // The text of the rating-role has been set to empty to get // replaced by a rating-image showing the rating as stars. - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); QSizeF ratingSize = preferredRatingSize(option); - const qreal availableWidth = (m_layout == DetailsLayout) - ? columnWidth("rating") - columnPadding(option) - : size().width(); + const qreal availableWidth = (m_layout == DetailsLayout) ? columnWidth("rating") - columnPadding(option) : size().width(); if (ratingSize.width() > availableWidth) { ratingSize.rwidth() = availableWidth; } @@ -1202,9 +1190,7 @@ QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, in const auto extensionWidth = m_customizedFontMetrics.horizontalAdvance(text.right(extensionLength)); if (elidingWidth > extensionWidth && extensionLength < 6 && (float(extensionWidth) / float(elidingWidth)) < 0.3) { // if we have room to display the file extension and the extension is not too long - QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength), - Qt::ElideRight, - elidingWidth - extensionWidth); + QString ret = m_customizedFontMetrics.elidedText(text.chopped(extensionLength), Qt::ElideRight, elidingWidth - extensionWidth); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) ret.append(text.rightRef(extensionLength)); #else @@ -1213,8 +1199,7 @@ QString KStandardItemListWidget::elideRightKeepExtension(const QString &text, in return ret; } } - return m_customizedFontMetrics.elidedText(text,Qt::ElideRight, - elidingWidth); + return m_customizedFontMetrics.elidedText(text, Qt::ElideRight, elidingWidth); } void KStandardItemListWidget::updateIconsLayoutTextCache() @@ -1231,14 +1216,14 @@ void KStandardItemListWidget::updateIconsLayoutTextCache() const QHash values = data(); - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); const qreal padding = option.padding; const qreal maxWidth = size().width() - 2 * padding; const qreal lineSpacing = m_customizedFontMetrics.lineSpacing(); // Initialize properties for the "text" role. It will be used as anchor // for initializing the position of the other roles. - TextInfo* nameTextInfo = m_textInfo.value("text"); + TextInfo *nameTextInfo = m_textInfo.value("text"); const QString nameText = KStringHandler::preProcessWrap(values["text"].toString()); nameTextInfo->staticText.setText(nameText); @@ -1289,20 +1274,17 @@ void KStandardItemListWidget::updateIconsLayoutTextCache() // Use one line for each additional information nameTextInfo->staticText.setTextWidth(maxWidth); nameTextInfo->pos = QPointF(padding, iconSize() + 2 * padding); - m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2, - nameTextInfo->pos.y(), - nameWidth, - nameHeight); + m_textRect = QRectF(padding + (maxWidth - nameWidth) / 2, nameTextInfo->pos.y(), nameWidth, nameHeight); // Calculate the position for each additional information qreal y = nameTextInfo->pos.y() + nameHeight; - for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) { + for (const QByteArray &role : qAsConst(m_sortedVisibleRoles)) { if (role == "text") { continue; } const QString text = roleText(role, values); - TextInfo* textInfo = m_textInfo.value(role); + TextInfo *textInfo = m_textInfo.value(role); textInfo->staticText.setText(text); qreal requiredWidth = 0; @@ -1353,7 +1335,7 @@ void KStandardItemListWidget::updateCompactLayoutTextCache() const QHash values = data(); - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); const qreal widgetHeight = size().height(); const qreal lineSpacing = m_customizedFontMetrics.lineSpacing(); const qreal textLinesHeight = qMax(visibleRoles().count(), 1) * lineSpacing; @@ -1362,9 +1344,9 @@ void KStandardItemListWidget::updateCompactLayoutTextCache() const qreal x = option.padding * 3 + iconSize(); qreal y = qRound((widgetHeight - textLinesHeight) / 2); const qreal maxWidth = size().width() - x - option.padding; - for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) { + for (const QByteArray &role : qAsConst(m_sortedVisibleRoles)) { const QString text = roleText(role, values); - TextInfo* textInfo = m_textInfo.value(role); + TextInfo *textInfo = m_textInfo.value(role); textInfo->staticText.setText(text); qreal requiredWidth = m_customizedFontMetrics.horizontalAdvance(text); @@ -1395,7 +1377,7 @@ void KStandardItemListWidget::updateDetailsLayoutTextCache() // +------+ m_textRect = QRectF(); - const KItemListStyleOption& option = styleOption(); + const KItemListStyleOption &option = styleOption(); const QHash values = data(); const qreal widgetHeight = size().height(); @@ -1412,7 +1394,7 @@ void KStandardItemListWidget::updateDetailsLayoutTextCache() qreal x = firstColumnInc; const qreal y = qMax(qreal(option.padding), (widgetHeight - fontHeight) / 2); - for (const QByteArray& role : qAsConst(m_sortedVisibleRoles)) { + for (const QByteArray &role : qAsConst(m_sortedVisibleRoles)) { QString text = roleText(role, values); // Elide the text in case it does not fit into the available column-width @@ -1430,17 +1412,14 @@ void KStandardItemListWidget::updateDetailsLayoutTextCache() requiredWidth = m_customizedFontMetrics.horizontalAdvance(text); } - TextInfo* textInfo = m_textInfo.value(role); + TextInfo *textInfo = m_textInfo.value(role); textInfo->staticText.setText(text); textInfo->pos = QPointF(x + columnWidthInc / 2, y); x += roleWidth; if (isTextRole) { - const qreal textWidth = option.extendedSelectionRegion - ? size().width() - textInfo->pos.x() - : requiredWidth + 2 * option.padding; - m_textRect = QRectF(textInfo->pos.x() - option.padding, 0, - textWidth, size().height()); + const qreal textWidth = option.extendedSelectionRegion ? size().width() - textInfo->pos.x() : requiredWidth + 2 * option.padding; + m_textRect = QRectF(textInfo->pos.x() - option.padding, 0, textWidth, size().height()); // The column after the name should always be aligned on the same x-position independent // from the expansion-level shown in the name column @@ -1471,12 +1450,11 @@ void KStandardItemListWidget::updateAdditionalInfoTextColor() const QColor c2 = styleOption().palette.base().color(); const int p1 = 70; const int p2 = 100 - p1; - m_additionalInfoTextColor = QColor((c1.red() * p1 + c2.red() * p2) / 100, - (c1.green() * p1 + c2.green() * p2) / 100, - (c1.blue() * p1 + c2.blue() * p2) / 100); + m_additionalInfoTextColor = + QColor((c1.red() * p1 + c2.red() * p2) / 100, (c1.green() * p1 + c2.green() * p2) / 100, (c1.blue() * p1 + c2.blue() * p2) / 100); } -void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixmap) +void KStandardItemListWidget::drawPixmap(QPainter *painter, const QPixmap &pixmap) { if (m_scaledPixmapSize != pixmap.size() / pixmap.devicePixelRatio()) { QPixmap scaledPixmap = pixmap; @@ -1493,7 +1471,7 @@ void KStandardItemListWidget::drawPixmap(QPainter* painter, const QPixmap& pixma } } -void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter) +void KStandardItemListWidget::drawSiblingsInformation(QPainter *painter) { const int siblingSize = size().height(); const int x = (m_expansionArea.left() + m_expansionArea.right() - siblingSize) / 2; @@ -1528,9 +1506,9 @@ void KStandardItemListWidget::drawSiblingsInformation(QPainter* painter) } } -QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const +QRectF KStandardItemListWidget::roleEditingRect(const QByteArray &role) const { - const TextInfo* textInfo = m_textInfo.value(role); + const TextInfo *textInfo = m_textInfo.value(role); if (!textInfo) { return QRectF(); } @@ -1545,10 +1523,8 @@ QRectF KStandardItemListWidget::roleEditingRect(const QByteArray& role) const void KStandardItemListWidget::closeRoleEditor() { - disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, - this, &KStandardItemListWidget::slotRoleEditingCanceled); - disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, - this, &KStandardItemListWidget::slotRoleEditingFinished); + disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled); + disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished); if (m_roleEditor->hasFocus()) { // If the editing was not ended by a FocusOut event, we have @@ -1564,7 +1540,7 @@ void KStandardItemListWidget::closeRoleEditor() m_roleEditor = nullptr; } -QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode) +QPixmap KStandardItemListWidget::pixmapForIcon(const QString &name, const QStringList &overlays, int size, QIcon::Mode mode) { static const QIcon fallbackIcon = QIcon::fromTheme(QStringLiteral("unknown")); @@ -1578,8 +1554,7 @@ QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStrin if (icon.isNull()) { icon = QIcon(name); } - if (icon.isNull() - || icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode).isNull()) { + if (icon.isNull() || icon.pixmap(size / qApp->devicePixelRatio(), size / qApp->devicePixelRatio(), mode).isNull()) { icon = fallbackIcon; } @@ -1593,7 +1568,7 @@ QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStrin // It is more efficient to do it here, as KIconLoader::drawOverlays() // assumes that an overlay will be drawn and has some additional // setup time. - for (const QString& overlay : overlays) { + for (const QString &overlay : overlays) { if (!overlay.isEmpty()) { int state = KIconLoader::DefaultState; @@ -1625,14 +1600,13 @@ QPixmap KStandardItemListWidget::pixmapForIcon(const QString& name, const QStrin return pixmap; } -QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption& option) +QSizeF KStandardItemListWidget::preferredRatingSize(const KItemListStyleOption &option) { const qreal height = option.fontMetrics.ascent(); return QSizeF(height * 5, height); } -qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption& option) +qreal KStandardItemListWidget::columnPadding(const KItemListStyleOption &option) { return option.padding * 6; } - diff --git a/src/kitemviews/kstandarditemlistwidget.h b/src/kitemviews/kstandarditemlistwidget.h index 35d4886b6b..5bfb7df296 100644 --- a/src/kitemviews/kstandarditemlistwidget.h +++ b/src/kitemviews/kstandarditemlistwidget.h @@ -23,12 +23,12 @@ class DOLPHIN_EXPORT KStandardItemListWidgetInformant : public KItemListWidgetIn public: KStandardItemListWidgetInformant(); ~KStandardItemListWidgetInformant() override; - - void calculateItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const override; - qreal preferredRoleColumnWidth(const QByteArray& role, - int index, - const KItemListView* view) const override; + void calculateItemSizeHints(QVector> &logicalHeightHints, + qreal &logicalWidthHint, + const KItemListView *view) const override; + + qreal preferredRoleColumnWidth(const QByteArray &role, int index, const KItemListView *view) const override; protected: /** @@ -38,31 +38,30 @@ protected: * QHash returned by KItemModelBase::data(int), * it can reimplement this function. */ - virtual QString itemText(int index, const KItemListView* view) const; + virtual QString itemText(int index, const KItemListView *view) const; /** * @return The value of the "isLink" role. The default implementation returns false. * The derived class should reimplement this function, when information about * links is available and in usage. */ - virtual bool itemIsLink(int index, const KItemListView* view) const; + virtual bool itemIsLink(int index, const KItemListView *view) const; /** * @return String representation of the role \a role. The representation of * a role might depend on other roles, so the values of all roles * are passed as parameter. */ - virtual QString roleText(const QByteArray& role, - const QHash& values) const; + virtual QString roleText(const QByteArray &role, const QHash &values) const; /** * @return A font based on baseFont which is customized for symlinks. */ - virtual QFont customizedFontForLinks(const QFont& baseFont) const; + virtual QFont customizedFontForLinks(const QFont &baseFont) const; - void calculateIconsLayoutItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const; - void calculateCompactLayoutItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const; - void calculateDetailsLayoutItemSizeHints(QVector>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const; + void calculateIconsLayoutItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const; + void calculateCompactLayoutItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const; + void calculateDetailsLayoutItemSizeHints(QVector> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const; friend class KStandardItemListWidget; // Accesses roleText() }; @@ -75,14 +74,9 @@ class DOLPHIN_EXPORT KStandardItemListWidget : public KItemListWidget Q_OBJECT public: - enum Layout - { - IconsLayout, - CompactLayout, - DetailsLayout - }; + enum Layout { IconsLayout, CompactLayout, DetailsLayout }; - KStandardItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent); + KStandardItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent); ~KStandardItemListWidget() override; void setLayout(Layout layout); @@ -94,7 +88,7 @@ public: void setSupportsItemExpanding(bool supportsItemExpanding); bool supportsItemExpanding() const; - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; QRectF iconRect() const override; QRectF textRect() const override; @@ -102,9 +96,9 @@ public: QRectF selectionRect() const override; QRectF expansionToggleRect() const override; QRectF selectionToggleRect() const override; - QPixmap createDragPixmap(const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + QPixmap createDragPixmap(const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; - static KItemListWidgetInformant* createInformant(); + static KItemListWidgetInformant *createInformant(); protected: /** @@ -129,7 +123,7 @@ protected: * @return True if the give role should be right aligned when showing it inside a column. * Per default false is returned. */ - virtual bool isRoleRightAligned(const QByteArray& role) const; + virtual bool isRoleRightAligned(const QByteArray &role) const; /** * @return True if the item should be visually marked as hidden item. Per default @@ -140,20 +134,20 @@ protected: /** * @return A font based on baseFont which is customized according to the data shown in the widget. */ - virtual QFont customizedFont(const QFont& baseFont) const; + virtual QFont customizedFont(const QFont &baseFont) const; virtual QPalette::ColorRole normalTextColorRole() const; - void setTextColor(const QColor& color); + void setTextColor(const QColor &color); QColor textColor() const; - void setOverlay(const QPixmap& overlay); + void setOverlay(const QPixmap &overlay); QPixmap overlay() const; /** * @see KStandardItemListWidgetInformant::roleText(). */ - QString roleText(const QByteArray& role, const QHash& values) const; + QString roleText(const QByteArray &role, const QHash &values) const; /** * Fixes: @@ -166,25 +160,24 @@ protected: * * @return Selection length (with or without MIME-type extension) */ - virtual int selectionLength(const QString& text) const; + virtual int selectionLength(const QString &text) const; - void dataChanged(const QHash& current, const QSet& roles = QSet()) override; - void visibleRolesChanged(const QList& current, const QList& previous) override; - void columnWidthChanged(const QByteArray& role, qreal current, qreal previous) override; + void dataChanged(const QHash ¤t, const QSet &roles = QSet()) override; + void visibleRolesChanged(const QList ¤t, const QList &previous) override; + void columnWidthChanged(const QByteArray &role, qreal current, qreal previous) override; void sidePaddingChanged(qreal width) override; - void styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) override; + void styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) override; void hoveredChanged(bool hovered) override; void selectedChanged(bool selected) override; - void siblingsInformationChanged(const QBitArray& current, const QBitArray& previous) override; - void editedRoleChanged(const QByteArray& current, const QByteArray& previous) override; + void siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous) override; + void editedRoleChanged(const QByteArray ¤t, const QByteArray &previous) override; void iconSizeChanged(int current, int previous) override; - void resizeEvent(QGraphicsSceneResizeEvent* event) override; - void showEvent(QShowEvent* event) override; - void hideEvent(QHideEvent* event) override; + void resizeEvent(QGraphicsSceneResizeEvent *event) override; + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; bool event(QEvent *event) override; - struct TextInfo - { + struct TextInfo { QPointF pos; QStaticText staticText; }; @@ -194,8 +187,8 @@ public Q_SLOTS: private Q_SLOTS: void slotCutItemsChanged(); - void slotRoleEditingCanceled(const QByteArray& role, const QVariant& value); - void slotRoleEditingFinished(const QByteArray& role, const QVariant& value); + void slotRoleEditingCanceled(const QByteArray &role, const QVariant &value); + void slotRoleEditingFinished(const QByteArray &role, const QVariant &value); private: void triggerCacheRefreshing(); @@ -209,8 +202,8 @@ private: void updateAdditionalInfoTextColor(); - void drawPixmap(QPainter* painter, const QPixmap& pixmap); - void drawSiblingsInformation(QPainter* painter); + void drawPixmap(QPainter *painter, const QPixmap &pixmap); + void drawSiblingsInformation(QPainter *painter); QRectF roleEditingRect(const QByteArray &role) const; @@ -222,23 +215,23 @@ private: */ void closeRoleEditor(); - static QPixmap pixmapForIcon(const QString& name, const QStringList& overlays, int size, QIcon::Mode mode); + static QPixmap pixmapForIcon(const QString &name, const QStringList &overlays, int size, QIcon::Mode mode); /** * @return Preferred size of the rating-image based on the given * style-option. The height of the font is taken as * reference. */ - static QSizeF preferredRatingSize(const KItemListStyleOption& option); + static QSizeF preferredRatingSize(const KItemListStyleOption &option); /** * @return Horizontal padding in pixels that is added to the required width of * a column to display the content. */ - static qreal columnPadding(const KItemListStyleOption& option); + static qreal columnPadding(const KItemListStyleOption &option); protected: - QHash m_textInfo; // PlacesItemListWidget needs to access this + QHash m_textInfo; // PlacesItemListWidget needs to access this private: bool m_isCut; @@ -259,8 +252,8 @@ private: QSize m_scaledPixmapSize; //Size of the pixmap in device independent pixels qreal m_columnWidthSum; - QRectF m_iconRect; // Cache for KItemListWidget::iconRect() - QPixmap m_hoverPixmap; // Cache for modified m_pixmap when hovering the item + QRectF m_iconRect; // Cache for KItemListWidget::iconRect() + QPixmap m_hoverPixmap; // Cache for modified m_pixmap when hovering the item QRectF m_textRect; @@ -274,8 +267,8 @@ private: QPixmap m_overlay; QPixmap m_rating; - KItemListRoleEditor* m_roleEditor; - KItemListRoleEditor* m_oldRoleEditor; + KItemListRoleEditor *m_roleEditor; + KItemListRoleEditor *m_oldRoleEditor; friend class KStandardItemListWidgetInformant; // Accesses private static methods to be able to // share a common layout calculation diff --git a/src/kitemviews/private/kbaloorolesprovider.cpp b/src/kitemviews/private/kbaloorolesprovider.cpp index f6d4dddb72..4cf36eb2da 100644 --- a/src/kitemviews/private/kbaloorolesprovider.cpp +++ b/src/kitemviews/private/kbaloorolesprovider.cpp @@ -14,20 +14,23 @@ #include #include -namespace { - QString tagsFromValues(const QStringList& values) - { - if (values.size() == 1) { - return values.at(0); - } - - QStringList alphabeticalOrderTags = values; - QCollator coll; - coll.setNumericMode(true); - std::sort(alphabeticalOrderTags.begin(), alphabeticalOrderTags.end(), [&](const QString& s1, const QString& s2){ return coll.compare(s1, s2) < 0; }); - return alphabeticalOrderTags.join(QLatin1String(", ")); +namespace +{ +QString tagsFromValues(const QStringList &values) +{ + if (values.size() == 1) { + return values.at(0); } + QStringList alphabeticalOrderTags = values; + QCollator coll; + coll.setNumericMode(true); + std::sort(alphabeticalOrderTags.begin(), alphabeticalOrderTags.end(), [&](const QString &s1, const QString &s2) { + return coll.compare(s1, s2) < 0; + }); + return alphabeticalOrderTags.join(QLatin1String(", ")); +} + using Property = KFileMetaData::Property::Property; // Mapping from the KFM::Property to the KFileItemModel roles. const QHash propertyRoleMap() { @@ -58,14 +61,12 @@ namespace { } } -struct KBalooRolesProviderSingleton -{ +struct KBalooRolesProviderSingleton { KBalooRolesProvider instance; }; Q_GLOBAL_STATIC(KBalooRolesProviderSingleton, s_balooRolesProvider) - -KBalooRolesProvider& KBalooRolesProvider::instance() +KBalooRolesProvider &KBalooRolesProvider::instance() { return s_balooRolesProvider->instance; } @@ -79,21 +80,21 @@ QSet KBalooRolesProvider::roles() const return m_roles; } -QHash KBalooRolesProvider::roleValues(const Baloo::File& file, - const QSet& roles) const +QHash KBalooRolesProvider::roleValues(const Baloo::File &file, const QSet &roles) const { QHash values; - using entry = std::pair; + using entry = std::pair; - const auto& propMap = file.properties(); + const auto &propMap = file.properties(); auto rangeBegin = propMap.constKeyValueBegin(); while (rangeBegin != propMap.constKeyValueEnd()) { auto key = (*rangeBegin).first; - auto rangeEnd = std::find_if(rangeBegin, propMap.constKeyValueEnd(), - [key](const entry& e) { return e.first != key; }); + auto rangeEnd = std::find_if(rangeBegin, propMap.constKeyValueEnd(), [key](const entry &e) { + return e.first != key; + }); const QByteArray role = propertyRoleMap().value(key); if (role.isEmpty() || !roles.contains(role)) { @@ -106,7 +107,9 @@ QHash KBalooRolesProvider::roleValues(const Baloo::File& f if (distance > 1) { QVariantList list; list.reserve(static_cast(distance)); - std::for_each(rangeBegin, rangeEnd, [&list](const entry& s) { list.append(s.second); }); + std::for_each(rangeBegin, rangeEnd, [&list](const entry &s) { + list.append(s.second); + }); values.insert(role, propertyInfo.formatAsDisplayString(list)); } else { if (propertyInfo.valueType() == QVariant::DateTime) { @@ -171,7 +174,7 @@ QHash KBalooRolesProvider::roleValues(const Baloo::File& f KBalooRolesProvider::KBalooRolesProvider() { // Display roles filled from Baloo property cache - for (const auto& role : propertyRoleMap()) { + for (const auto &role : propertyRoleMap()) { m_roles.insert(role); } m_roles.insert("dimensions"); @@ -182,4 +185,3 @@ KBalooRolesProvider::KBalooRolesProvider() m_roles.insert(QByteArrayLiteral("comment")); m_roles.insert(QByteArrayLiteral("originUrl")); } - diff --git a/src/kitemviews/private/kbaloorolesprovider.h b/src/kitemviews/private/kbaloorolesprovider.h index 97ed58f2b1..5ff33e1c61 100644 --- a/src/kitemviews/private/kbaloorolesprovider.h +++ b/src/kitemviews/private/kbaloorolesprovider.h @@ -14,8 +14,9 @@ #include #include -namespace Baloo { - class File; +namespace Baloo +{ +class File; } /** @@ -27,7 +28,7 @@ namespace Baloo { class DOLPHIN_EXPORT KBalooRolesProvider { public: - static KBalooRolesProvider& instance(); + static KBalooRolesProvider &instance(); virtual ~KBalooRolesProvider(); /** @@ -39,8 +40,7 @@ public: * @return Values for the roles \a roles that can be determined from the file * with the URL \a url. */ - QHash roleValues(const Baloo::File& file, - const QSet& roles) const; + QHash roleValues(const Baloo::File &file, const QSet &roles) const; protected: KBalooRolesProvider(); @@ -52,4 +52,3 @@ private: }; #endif - diff --git a/src/kitemviews/private/kdirectorycontentscounter.cpp b/src/kitemviews/private/kdirectorycontentscounter.cpp index a2a27ad287..039b79b6e6 100644 --- a/src/kitemviews/private/kdirectorycontentscounter.cpp +++ b/src/kitemviews/private/kdirectorycontentscounter.cpp @@ -10,26 +10,26 @@ #include -#include #include +#include #include -namespace { - /// cache of directory counting result - static QHash> *s_cache; +namespace +{ +/// cache of directory counting result +static QHash> *s_cache; } -KDirectoryContentsCounter::KDirectoryContentsCounter(KFileItemModel* model, QObject* parent) : - QObject(parent), - m_model(model), - m_queue(), - m_worker(nullptr), - m_workerIsBusy(false), - m_dirWatcher(nullptr), - m_watchedDirs() +KDirectoryContentsCounter::KDirectoryContentsCounter(KFileItemModel *model, QObject *parent) + : QObject(parent) + , m_model(model) + , m_queue() + , m_worker(nullptr) + , m_workerIsBusy(false) + , m_dirWatcher(nullptr) + , m_watchedDirs() { - connect(m_model, &KFileItemModel::itemsRemoved, - this, &KDirectoryContentsCounter::slotItemsRemoved); + connect(m_model, &KFileItemModel::itemsRemoved, this, &KDirectoryContentsCounter::slotItemsRemoved); if (!m_workerThread) { m_workerThread = new QThread(); @@ -43,10 +43,8 @@ KDirectoryContentsCounter::KDirectoryContentsCounter(KFileItemModel* model, QObj m_worker = new KDirectoryContentsCounterWorker(); m_worker->moveToThread(m_workerThread); - connect(this, &KDirectoryContentsCounter::requestDirectoryContentsCount, - m_worker, &KDirectoryContentsCounterWorker::countDirectoryContents); - connect(m_worker, &KDirectoryContentsCounterWorker::result, - this, &KDirectoryContentsCounter::slotResult); + connect(this, &KDirectoryContentsCounter::requestDirectoryContentsCount, m_worker, &KDirectoryContentsCounterWorker::countDirectoryContents); + connect(m_worker, &KDirectoryContentsCounterWorker::result, this, &KDirectoryContentsCounter::slotResult); m_dirWatcher = new KDirWatch(this); connect(m_dirWatcher, &KDirWatch::dirty, this, &KDirectoryContentsCounter::slotDirWatchDirty); @@ -73,12 +71,12 @@ KDirectoryContentsCounter::~KDirectoryContentsCounter() } } -void KDirectoryContentsCounter::scanDirectory(const QString& path) +void KDirectoryContentsCounter::scanDirectory(const QString &path) { startWorker(path); } -void KDirectoryContentsCounter::slotResult(const QString& path, int count, long size) +void KDirectoryContentsCounter::slotResult(const QString &path, int count, long size) { m_workerIsBusy = false; @@ -118,7 +116,7 @@ void KDirectoryContentsCounter::slotResult(const QString& path, int count, long Q_EMIT result(path, count, size); } -void KDirectoryContentsCounter::slotDirWatchDirty(const QString& path) +void KDirectoryContentsCounter::slotDirWatchDirty(const QString &path) { const int index = m_model->index(QUrl::fromLocalFile(path)); if (index >= 0) { @@ -140,7 +138,7 @@ void KDirectoryContentsCounter::slotItemsRemoved() if (!m_watchedDirs.isEmpty()) { // Don't let KDirWatch watch for removed items if (allItemsRemoved) { - for (const QString& path : qAsConst(m_watchedDirs)) { + for (const QString &path : qAsConst(m_watchedDirs)) { m_dirWatcher->removeDir(path); } m_watchedDirs.clear(); @@ -148,7 +146,7 @@ void KDirectoryContentsCounter::slotItemsRemoved() } else { QMutableSetIterator it(m_watchedDirs); while (it.hasNext()) { - const QString& path = it.next(); + const QString &path = it.next(); if (m_model->index(QUrl::fromLocalFile(path)) < 0) { m_dirWatcher->removeDir(path); it.remove(); @@ -158,7 +156,7 @@ void KDirectoryContentsCounter::slotItemsRemoved() } } -void KDirectoryContentsCounter::startWorker(const QString& path) +void KDirectoryContentsCounter::startWorker(const QString &path) { const QString resolvedPath = QFileInfo(path).canonicalFilePath(); const bool alreadyInCache = s_cache->contains(resolvedPath); @@ -170,8 +168,8 @@ void KDirectoryContentsCounter::startWorker(const QString& path) } if (m_workerIsBusy) { - if (std::find(m_queue.begin(), m_queue.end(), path) == m_queue.end() && - std::find(m_priorityQueue.begin(), m_priorityQueue.end(), path) == m_priorityQueue.end()) { + if (std::find(m_queue.begin(), m_queue.end(), path) == m_queue.end() + && std::find(m_priorityQueue.begin(), m_priorityQueue.end(), path) == m_priorityQueue.end()) { if (alreadyInCache) { m_queue.push_back(path); } else { @@ -195,4 +193,4 @@ void KDirectoryContentsCounter::startWorker(const QString& path) } } -QThread* KDirectoryContentsCounter::m_workerThread = nullptr; +QThread *KDirectoryContentsCounter::m_workerThread = nullptr; diff --git a/src/kitemviews/private/kdirectorycontentscounter.h b/src/kitemviews/private/kdirectorycontentscounter.h index 6d3d1f3c1d..f74565b73a 100644 --- a/src/kitemviews/private/kdirectorycontentscounter.h +++ b/src/kitemviews/private/kdirectorycontentscounter.h @@ -21,7 +21,7 @@ class KDirectoryContentsCounter : public QObject Q_OBJECT public: - explicit KDirectoryContentsCounter(KFileItemModel* model, QObject* parent = nullptr); + explicit KDirectoryContentsCounter(KFileItemModel *model, QObject *parent = nullptr); ~KDirectoryContentsCounter() override; /** @@ -35,40 +35,40 @@ public: * Uses a cache internally to speed up first result, * but emit again result when the cache was updated */ - void scanDirectory(const QString& path); + void scanDirectory(const QString &path); Q_SIGNALS: /** * Signals that the directory \a path contains \a count items of size \a * Size calculation depends on parameter DetailsModeSettings::recursiveDirectorySizeLimit */ - void result(const QString& path, int count, long size); + void result(const QString &path, int count, long size); - void requestDirectoryContentsCount(const QString& path, KDirectoryContentsCounterWorker::Options options); + void requestDirectoryContentsCount(const QString &path, KDirectoryContentsCounterWorker::Options options); private Q_SLOTS: - void slotResult(const QString& path, int count, long size); - void slotDirWatchDirty(const QString& path); + void slotResult(const QString &path, int count, long size); + void slotDirWatchDirty(const QString &path); void slotItemsRemoved(); private: - void startWorker(const QString& path); + void startWorker(const QString &path); private: - KFileItemModel* m_model; + KFileItemModel *m_model; // Used as FIFO queues. std::list m_priorityQueue; std::list m_queue; - static QThread* m_workerThread; + static QThread *m_workerThread; - KDirectoryContentsCounterWorker* m_worker; + KDirectoryContentsCounterWorker *m_worker; bool m_workerIsBusy; - KDirWatch* m_dirWatcher; - QSet m_watchedDirs; // Required as sadly KDirWatch does not offer a getter method - // to get all watched directories. + KDirWatch *m_dirWatcher; + QSet m_watchedDirs; // Required as sadly KDirWatch does not offer a getter method + // to get all watched directories. }; #endif diff --git a/src/kitemviews/private/kdirectorycontentscounterworker.cpp b/src/kitemviews/private/kdirectorycontentscounterworker.cpp index 2a683cdbc7..e227c1bc68 100644 --- a/src/kitemviews/private/kdirectorycontentscounterworker.cpp +++ b/src/kitemviews/private/kdirectorycontentscounterworker.cpp @@ -17,17 +17,15 @@ #include "dolphin_detailsmodesettings.h" -KDirectoryContentsCounterWorker::KDirectoryContentsCounterWorker(QObject* parent) : - QObject(parent) +KDirectoryContentsCounterWorker::KDirectoryContentsCounterWorker(QObject *parent) + : QObject(parent) { qRegisterMetaType(); } #ifndef Q_OS_WIN -KDirectoryContentsCounterWorker::CountResult walkDir(const QString &dirPath, - const bool countHiddenFiles, - const bool countDirectoriesOnly, - const uint allowedRecursiveLevel) +KDirectoryContentsCounterWorker::CountResult +walkDir(const QString &dirPath, const bool countHiddenFiles, const bool countDirectoriesOnly, const uint allowedRecursiveLevel) { int count = -1; long size = -1; @@ -53,10 +51,7 @@ KDirectoryContentsCounterWorker::CountResult walkDir(const QString &dirPath, // If only directories are counted, consider an unknown file type and links also // as directory instead of trying to do an expensive stat() // (see bugs 292642 and 299997). - const bool countEntry = !countDirectoriesOnly || - dirEntry->d_type == DT_DIR || - dirEntry->d_type == DT_LNK || - dirEntry->d_type == DT_UNKNOWN; + const bool countEntry = !countDirectoriesOnly || dirEntry->d_type == DT_DIR || dirEntry->d_type == DT_LNK || dirEntry->d_type == DT_UNKNOWN; if (countEntry) { ++count; } @@ -84,7 +79,7 @@ KDirectoryContentsCounterWorker::CountResult walkDir(const QString &dirPath, } #endif -KDirectoryContentsCounterWorker::CountResult KDirectoryContentsCounterWorker::subItemsCount(const QString& path, Options options) +KDirectoryContentsCounterWorker::CountResult KDirectoryContentsCounterWorker::subItemsCount(const QString &path, Options options) { const bool countHiddenFiles = options & CountHiddenFiles; const bool countDirectoriesOnly = options & CountDirectoriesOnly; @@ -111,7 +106,7 @@ KDirectoryContentsCounterWorker::CountResult KDirectoryContentsCounterWorker::su #endif } -void KDirectoryContentsCounterWorker::countDirectoryContents(const QString& path, Options options) +void KDirectoryContentsCounterWorker::countDirectoryContents(const QString &path, Options options) { auto res = subItemsCount(path, options); Q_EMIT result(path, res.count, res.size); diff --git a/src/kitemviews/private/kdirectorycontentscounterworker.h b/src/kitemviews/private/kdirectorycontentscounterworker.h index 48a2d1ff9b..6bbe099a56 100644 --- a/src/kitemviews/private/kdirectorycontentscounterworker.h +++ b/src/kitemviews/private/kdirectorycontentscounterworker.h @@ -17,11 +17,7 @@ class KDirectoryContentsCounterWorker : public QObject Q_OBJECT public: - enum Option { - NoOptions = 0x0, - CountHiddenFiles = 0x1, - CountDirectoriesOnly = 0x2 - }; + enum Option { NoOptions = 0x0, CountHiddenFiles = 0x1, CountDirectoriesOnly = 0x2 }; Q_DECLARE_FLAGS(Options, Option) struct CountResult { @@ -32,7 +28,7 @@ public: long size; }; - explicit KDirectoryContentsCounterWorker(QObject* parent = nullptr); + explicit KDirectoryContentsCounterWorker(QObject *parent = nullptr); /** * Counts the items inside the directory \a path using the options @@ -40,13 +36,13 @@ public: * * @return The number of items. */ - static CountResult subItemsCount(const QString& path, Options options); + static CountResult subItemsCount(const QString &path, Options options); Q_SIGNALS: /** * Signals that the directory \a path contains \a count items and optionally the size of its content. */ - void result(const QString& path, int count, long size); + void result(const QString &path, int count, long size); public Q_SLOTS: /** @@ -56,7 +52,7 @@ public Q_SLOTS: // Note that the full type name KDirectoryContentsCounterWorker::Options // is needed here. Just using 'Options' is OK for the compiler, but // confuses moc. - void countDirectoryContents(const QString& path, KDirectoryContentsCounterWorker::Options options); + void countDirectoryContents(const QString &path, KDirectoryContentsCounterWorker::Options options); }; Q_DECLARE_METATYPE(KDirectoryContentsCounterWorker::Options) diff --git a/src/kitemviews/private/kfileitemclipboard.cpp b/src/kitemviews/private/kfileitemclipboard.cpp index ec31068e7d..33bf298ed5 100644 --- a/src/kitemviews/private/kfileitemclipboard.cpp +++ b/src/kitemviews/private/kfileitemclipboard.cpp @@ -19,14 +19,12 @@ public: }; Q_GLOBAL_STATIC(KFileItemClipboardSingleton, s_KFileItemClipboard) - - -KFileItemClipboard* KFileItemClipboard::instance() +KFileItemClipboard *KFileItemClipboard::instance() { return &s_KFileItemClipboard->instance; } -bool KFileItemClipboard::isCut(const QUrl& url) const +bool KFileItemClipboard::isCut(const QUrl &url) const { return m_cutItems.contains(url); } @@ -42,7 +40,7 @@ KFileItemClipboard::~KFileItemClipboard() void KFileItemClipboard::updateCutItems() { - const QMimeData* mimeData = QApplication::clipboard()->mimeData(); + const QMimeData *mimeData = QApplication::clipboard()->mimeData(); // mimeData can be 0 according to https://bugs.kde.org/show_bug.cgi?id=335053 if (!mimeData) { @@ -62,12 +60,11 @@ void KFileItemClipboard::updateCutItems() Q_EMIT cutItemsChanged(); } -KFileItemClipboard::KFileItemClipboard() : - QObject(nullptr), - m_cutItems() +KFileItemClipboard::KFileItemClipboard() + : QObject(nullptr) + , m_cutItems() { updateCutItems(); - connect(QApplication::clipboard(), &QClipboard::dataChanged, - this, &KFileItemClipboard::updateCutItems); + connect(QApplication::clipboard(), &QClipboard::dataChanged, this, &KFileItemClipboard::updateCutItems); } diff --git a/src/kitemviews/private/kfileitemclipboard.h b/src/kitemviews/private/kfileitemclipboard.h index 8182013087..1d3e2dedf5 100644 --- a/src/kitemviews/private/kfileitemclipboard.h +++ b/src/kitemviews/private/kfileitemclipboard.h @@ -23,9 +23,9 @@ class DOLPHIN_EXPORT KFileItemClipboard : public QObject Q_OBJECT public: - static KFileItemClipboard* instance(); + static KFileItemClipboard *instance(); - bool isCut(const QUrl& url) const; + bool isCut(const QUrl &url) const; QList cutItems() const; diff --git a/src/kitemviews/private/kfileitemmodelfilter.cpp b/src/kitemviews/private/kfileitemmodelfilter.cpp index 6a2a4177fd..f199c314fa 100644 --- a/src/kitemviews/private/kfileitemmodelfilter.cpp +++ b/src/kitemviews/private/kfileitemmodelfilter.cpp @@ -10,11 +10,11 @@ #include -KFileItemModelFilter::KFileItemModelFilter() : - m_useRegExp(false), - m_regExp(nullptr), - m_lowerCasePattern(), - m_pattern() +KFileItemModelFilter::KFileItemModelFilter() + : m_useRegExp(false) + , m_regExp(nullptr) + , m_lowerCasePattern() + , m_pattern() { } @@ -24,7 +24,7 @@ KFileItemModelFilter::~KFileItemModelFilter() m_regExp = nullptr; } -void KFileItemModelFilter::setPattern(const QString& filter) +void KFileItemModelFilter::setPattern(const QString &filter) { m_pattern = filter; m_lowerCasePattern = filter.toLower(); @@ -46,7 +46,7 @@ QString KFileItemModelFilter::pattern() const return m_pattern; } -void KFileItemModelFilter::setMimeTypes(const QStringList& types) +void KFileItemModelFilter::setMimeTypes(const QStringList &types) { m_mimeTypes = types; } @@ -61,8 +61,7 @@ bool KFileItemModelFilter::hasSetFilters() const return (!m_pattern.isEmpty() || !m_mimeTypes.isEmpty()); } - -bool KFileItemModelFilter::matches(const KFileItem& item) const +bool KFileItemModelFilter::matches(const KFileItem &item) const { const bool hasPatternFilter = !m_pattern.isEmpty(); const bool hasMimeTypesFilter = !m_mimeTypes.isEmpty(); @@ -85,7 +84,7 @@ bool KFileItemModelFilter::matches(const KFileItem& item) const return matchesType(item); } -bool KFileItemModelFilter::matchesPattern(const KFileItem& item) const +bool KFileItemModelFilter::matchesPattern(const KFileItem &item) const { if (m_useRegExp) { return m_regExp->match(item.text()).hasMatch(); @@ -94,9 +93,9 @@ bool KFileItemModelFilter::matchesPattern(const KFileItem& item) const } } -bool KFileItemModelFilter::matchesType(const KFileItem& item) const +bool KFileItemModelFilter::matchesType(const KFileItem &item) const { - for (const QString& mimeType : qAsConst(m_mimeTypes)) { + for (const QString &mimeType : qAsConst(m_mimeTypes)) { if (item.mimetype() == mimeType) { return true; } diff --git a/src/kitemviews/private/kfileitemmodelfilter.h b/src/kitemviews/private/kfileitemmodelfilter.h index f55a8097d5..959590da8d 100644 --- a/src/kitemviews/private/kfileitemmodelfilter.h +++ b/src/kitemviews/private/kfileitemmodelfilter.h @@ -24,7 +24,6 @@ class QRegularExpression; */ class DOLPHIN_EXPORT KFileItemModelFilter { - public: KFileItemModelFilter(); virtual ~KFileItemModelFilter(); @@ -35,14 +34,14 @@ public: * defines a sub-string. As soon as the pattern contains at least * a '*', '?' or '[' the pattern represents a regular expression. */ - void setPattern(const QString& pattern); + void setPattern(const QString &pattern); QString pattern() const; /** * Set the list of mimetypes that are used for comparison with the * item in KFileItemModelFilter::matchesMimeType. */ - void setMimeTypes(const QStringList& types); + void setMimeTypes(const QStringList &types); QStringList mimeTypes() const; /** @@ -54,27 +53,25 @@ public: * @return True if the item matches with the pattern defined by * @ref setPattern() or @ref setMimeTypes */ - bool matches(const KFileItem& item) const; + bool matches(const KFileItem &item) const; private: /** * @return True if item matches pattern set by @ref setPattern. */ - bool matchesPattern(const KFileItem& item) const; + bool matchesPattern(const KFileItem &item) const; /** * @return True if item matches mimetypes set by @ref setMimeTypes. */ - bool matchesType(const KFileItem& item) const; + bool matchesType(const KFileItem &item) const; - bool m_useRegExp; // If true, m_regExp is used for filtering, - // otherwise m_lowerCaseFilter is used. + bool m_useRegExp; // If true, m_regExp is used for filtering, + // otherwise m_lowerCaseFilter is used. QRegularExpression *m_regExp; QString m_lowerCasePattern; // Lowercase version of m_filter for // faster comparison in matches(). - QString m_pattern; // Property set by setPattern(). - QStringList m_mimeTypes; // Property set by setMimeTypes() + QString m_pattern; // Property set by setPattern(). + QStringList m_mimeTypes; // Property set by setMimeTypes() }; #endif - - diff --git a/src/kitemviews/private/kfileitemmodelsortalgorithm.h b/src/kitemviews/private/kfileitemmodelsortalgorithm.h index 4fe6aa66a2..29c1fe5ac7 100644 --- a/src/kitemviews/private/kfileitemmodelsortalgorithm.h +++ b/src/kitemviews/private/kfileitemmodelsortalgorithm.h @@ -21,10 +21,8 @@ * SPDX-FileCopyrightText: 2011 Nokia Corporation and/or its subsidiary(-ies). */ -template -static void mergeSort(RandomAccessIterator begin, - RandomAccessIterator end, - const LessThan& lessThan) +template +static void mergeSort(RandomAccessIterator begin, RandomAccessIterator end, const LessThan &lessThan) { // The implementation is based on qStableSortHelper() from qalgorithms.h // SPDX-FileCopyrightText: 2011 Nokia Corporation and/or its subsidiary(-ies). @@ -49,12 +47,9 @@ static void mergeSort(RandomAccessIterator begin, * The comparison function \a lessThan must be reentrant. */ -template -static void parallelMergeSort(RandomAccessIterator begin, - RandomAccessIterator end, - LessThan lessThan, - int numberOfThreads, - int parallelMergeSortingThreshold = 100) +template +static void +parallelMergeSort(RandomAccessIterator begin, RandomAccessIterator end, LessThan lessThan, int numberOfThreads, int parallelMergeSortingThreshold = 100) { const int span = end - begin; @@ -62,7 +57,8 @@ static void parallelMergeSort(RandomAccessIterator begin, const int newNumberOfThreads = numberOfThreads / 2; const RandomAccessIterator middle = begin + span / 2; - QFuture future = QtConcurrent::run(parallelMergeSort, begin, middle, lessThan, newNumberOfThreads, parallelMergeSortingThreshold); + QFuture future = + QtConcurrent::run(parallelMergeSort, begin, middle, lessThan, newNumberOfThreads, parallelMergeSortingThreshold); parallelMergeSort(middle, end, lessThan, newNumberOfThreads, parallelMergeSortingThreshold); future.waitForFinished(); @@ -82,11 +78,8 @@ static void parallelMergeSort(RandomAccessIterator begin, * SPDX-FileCopyrightText: 2011 Nokia Corporation and/or its subsidiary(-ies). */ -template -static void merge(RandomAccessIterator begin, - RandomAccessIterator pivot, - RandomAccessIterator end, - const LessThan& lessThan) +template +static void merge(RandomAccessIterator begin, RandomAccessIterator pivot, RandomAccessIterator end, const LessThan &lessThan) { // The implementation is based on qMerge() from qalgorithms.h // SPDX-FileCopyrightText: 2011 Nokia Corporation and/or its subsidiary(-ies). @@ -111,14 +104,12 @@ static void merge(RandomAccessIterator begin, if (len1 > len2) { const int len1Half = len1 / 2; firstCut = begin + len1Half; - secondCut = std::lower_bound(pivot, end, *firstCut, lessThan); + secondCut = std::lower_bound(pivot, end, *firstCut, lessThan); len2Half = secondCut - pivot; } else { len2Half = len2 / 2; secondCut = pivot + len2Half; - firstCut = std::upper_bound(begin, pivot, *secondCut, lessThan); + firstCut = std::upper_bound(begin, pivot, *secondCut, lessThan); } std::rotate(firstCut, pivot, secondCut); @@ -129,4 +120,3 @@ static void merge(RandomAccessIterator begin, } #endif - diff --git a/src/kitemviews/private/kitemlistheaderwidget.cpp b/src/kitemviews/private/kitemlistheaderwidget.cpp index 9f4f868d0d..ac25d189c1 100644 --- a/src/kitemviews/private/kitemlistheaderwidget.cpp +++ b/src/kitemviews/private/kitemlistheaderwidget.cpp @@ -12,21 +12,20 @@ #include #include - -KItemListHeaderWidget::KItemListHeaderWidget(QGraphicsWidget* parent) : - QGraphicsWidget(parent), - m_automaticColumnResizing(true), - m_model(nullptr), - m_offset(0), - m_sidePadding(0), - m_columns(), - m_columnWidths(), - m_preferredColumnWidths(), - m_hoveredRoleIndex(-1), - m_pressedRoleIndex(-1), - m_roleOperation(NoRoleOperation), - m_pressedMousePos(), - m_movingRole() +KItemListHeaderWidget::KItemListHeaderWidget(QGraphicsWidget *parent) + : QGraphicsWidget(parent) + , m_automaticColumnResizing(true) + , m_model(nullptr) + , m_offset(0) + , m_sidePadding(0) + , m_columns() + , m_columnWidths() + , m_preferredColumnWidths() + , m_hoveredRoleIndex(-1) + , m_pressedRoleIndex(-1) + , m_roleOperation(NoRoleOperation) + , m_pressedMousePos() + , m_movingRole() { m_movingRole.x = 0; m_movingRole.xDec = 0; @@ -41,30 +40,26 @@ KItemListHeaderWidget::~KItemListHeaderWidget() { } -void KItemListHeaderWidget::setModel(KItemModelBase* model) +void KItemListHeaderWidget::setModel(KItemModelBase *model) { if (m_model == model) { return; } if (m_model) { - disconnect(m_model, &KItemModelBase::sortRoleChanged, - this, &KItemListHeaderWidget::slotSortRoleChanged); - disconnect(m_model, &KItemModelBase::sortOrderChanged, - this, &KItemListHeaderWidget::slotSortOrderChanged); + disconnect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListHeaderWidget::slotSortRoleChanged); + disconnect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListHeaderWidget::slotSortOrderChanged); } m_model = model; if (m_model) { - connect(m_model, &KItemModelBase::sortRoleChanged, - this, &KItemListHeaderWidget::slotSortRoleChanged); - connect(m_model, &KItemModelBase::sortOrderChanged, - this, &KItemListHeaderWidget::slotSortOrderChanged); + connect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListHeaderWidget::slotSortRoleChanged); + connect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListHeaderWidget::slotSortOrderChanged); } } -KItemModelBase* KItemListHeaderWidget::model() const +KItemModelBase *KItemListHeaderWidget::model() const { return m_model; } @@ -79,9 +74,9 @@ bool KItemListHeaderWidget::automaticColumnResizing() const return m_automaticColumnResizing; } -void KItemListHeaderWidget::setColumns(const QList& roles) +void KItemListHeaderWidget::setColumns(const QList &roles) { - for (const QByteArray& role : roles) { + for (const QByteArray &role : roles) { if (!m_columnWidths.contains(role)) { m_preferredColumnWidths.remove(role); } @@ -96,7 +91,7 @@ QList KItemListHeaderWidget::columns() const return m_columns; } -void KItemListHeaderWidget::setColumnWidth(const QByteArray& role, qreal width) +void KItemListHeaderWidget::setColumnWidth(const QByteArray &role, qreal width) { const qreal minWidth = minimumColumnWidth(); if (width < minWidth) { @@ -109,17 +104,17 @@ void KItemListHeaderWidget::setColumnWidth(const QByteArray& role, qreal width) } } -qreal KItemListHeaderWidget::columnWidth(const QByteArray& role) const +qreal KItemListHeaderWidget::columnWidth(const QByteArray &role) const { return m_columnWidths.value(role); } -void KItemListHeaderWidget::setPreferredColumnWidth(const QByteArray& role, qreal width) +void KItemListHeaderWidget::setPreferredColumnWidth(const QByteArray &role, qreal width) { m_preferredColumnWidths.insert(role, width); } -qreal KItemListHeaderWidget::preferredColumnWidth(const QByteArray& role) const +qreal KItemListHeaderWidget::preferredColumnWidth(const QByteArray &role) const { return m_preferredColumnWidths.value(role); } @@ -157,7 +152,7 @@ qreal KItemListHeaderWidget::minimumColumnWidth() const return fontMetrics.height() * 4; } -void KItemListHeaderWidget::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KItemListHeaderWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) @@ -172,7 +167,7 @@ void KItemListHeaderWidget::paint(QPainter* painter, const QStyleOptionGraphicsI qreal x = -m_offset + m_sidePadding; int orderIndex = 0; - for (const QByteArray& role : qAsConst(m_columns)) { + for (const QByteArray &role : qAsConst(m_columns)) { const qreal roleWidth = m_columnWidths.value(role); const QRectF rect(x, 0, roleWidth, size().height()); paintRole(painter, role, rect, orderIndex, widget); @@ -186,7 +181,7 @@ void KItemListHeaderWidget::paint(QPainter* painter, const QStyleOptionGraphicsI } } -void KItemListHeaderWidget::mousePressEvent(QGraphicsSceneMouseEvent* event) +void KItemListHeaderWidget::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() & Qt::LeftButton) { m_pressedMousePos = event->pos(); @@ -194,8 +189,7 @@ void KItemListHeaderWidget::mousePressEvent(QGraphicsSceneMouseEvent* event) m_roleOperation = ResizePaddingColumnOperation; } else { updatePressedRoleIndex(event->pos()); - m_roleOperation = isAboveRoleGrip(m_pressedMousePos, m_pressedRoleIndex) ? - ResizeRoleOperation : NoRoleOperation; + m_roleOperation = isAboveRoleGrip(m_pressedMousePos, m_pressedRoleIndex) ? ResizeRoleOperation : NoRoleOperation; } event->accept(); } else { @@ -203,7 +197,7 @@ void KItemListHeaderWidget::mousePressEvent(QGraphicsSceneMouseEvent* event) } } -void KItemListHeaderWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) +void KItemListHeaderWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { QGraphicsWidget::mouseReleaseEvent(event); @@ -219,8 +213,7 @@ void KItemListHeaderWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) if (m_pressedRoleIndex == sortRoleIndex) { // Toggle the sort order const Qt::SortOrder previous = m_model->sortOrder(); - const Qt::SortOrder current = (m_model->sortOrder() == Qt::AscendingOrder) ? - Qt::DescendingOrder : Qt::AscendingOrder; + const Qt::SortOrder current = (m_model->sortOrder() == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder; m_model->setSortOrder(current); Q_EMIT sortOrderChanged(current, previous); } else { @@ -264,7 +257,7 @@ void KItemListHeaderWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) QApplication::restoreOverrideCursor(); } -void KItemListHeaderWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event) +void KItemListHeaderWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { QGraphicsWidget::mouseMoveEvent(event); @@ -352,7 +345,7 @@ void KItemListHeaderWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event) } } -void KItemListHeaderWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) +void KItemListHeaderWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { QGraphicsItem::mouseDoubleClickEvent(event); @@ -369,13 +362,13 @@ void KItemListHeaderWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* even } } -void KItemListHeaderWidget::hoverEnterEvent(QGraphicsSceneHoverEvent* event) +void KItemListHeaderWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsWidget::hoverEnterEvent(event); updateHoveredRoleIndex(event->pos()); } -void KItemListHeaderWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) +void KItemListHeaderWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsWidget::hoverLeaveEvent(event); if (m_hoveredRoleIndex != -1) { @@ -384,22 +377,21 @@ void KItemListHeaderWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) } } -void KItemListHeaderWidget::hoverMoveEvent(QGraphicsSceneHoverEvent* event) +void KItemListHeaderWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsWidget::hoverMoveEvent(event); - const QPointF& pos = event->pos(); + const QPointF &pos = event->pos(); updateHoveredRoleIndex(pos); - if ((m_hoveredRoleIndex >= 0 && isAboveRoleGrip(pos, m_hoveredRoleIndex)) || - isAbovePaddingGrip(pos, PaddingGrip::Leading) || - isAbovePaddingGrip(pos, PaddingGrip::Trailing)) { + if ((m_hoveredRoleIndex >= 0 && isAboveRoleGrip(pos, m_hoveredRoleIndex)) || isAbovePaddingGrip(pos, PaddingGrip::Leading) + || isAbovePaddingGrip(pos, PaddingGrip::Trailing)) { setCursor(Qt::SplitHCursor); } else { unsetCursor(); } } -void KItemListHeaderWidget::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous) +void KItemListHeaderWidget::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(current) Q_UNUSED(previous) @@ -413,11 +405,7 @@ void KItemListHeaderWidget::slotSortOrderChanged(Qt::SortOrder current, Qt::Sort update(); } -void KItemListHeaderWidget::paintRole(QPainter* painter, - const QByteArray& role, - const QRectF& rect, - int orderIndex, - QWidget* widget) const +void KItemListHeaderWidget::paintRole(QPainter *painter, const QByteArray &role, const QRectF &rect, int orderIndex, QWidget *widget) const { const auto direction = widget ? widget->layoutDirection() : qApp->layoutDirection(); @@ -425,10 +413,7 @@ void KItemListHeaderWidget::paintRole(QPainter* painter, // SPDX-FileCopyrightText: 2011 Nokia Corporation and/or its subsidiary(-ies). QStyleOptionHeader option; option.direction = direction; - option.textAlignment = - direction == Qt::LeftToRight - ? Qt::AlignLeft - : Qt::AlignRight; + option.textAlignment = direction == Qt::LeftToRight ? Qt::AlignLeft : Qt::AlignRight; option.section = orderIndex; option.state = QStyle::State_None | QStyle::State_Raised | QStyle::State_Horizontal; @@ -445,8 +430,7 @@ void KItemListHeaderWidget::paintRole(QPainter* painter, option.state |= QStyle::State_Sunken; } if (m_model->sortRole() == role) { - option.sortIndicator = (m_model->sortOrder() == Qt::AscendingOrder) ? - QStyleOptionHeader::SortDown : QStyleOptionHeader::SortUp; + option.sortIndicator = (m_model->sortOrder() == Qt::AscendingOrder) ? QStyleOptionHeader::SortDown : QStyleOptionHeader::SortUp; } option.rect = rect.toRect(); option.orientation = Qt::Horizontal; @@ -454,7 +438,7 @@ void KItemListHeaderWidget::paintRole(QPainter* painter, option.text = m_model->roleDescription(role); // First we paint any potential empty (padding) space on left and/or right of this role's column. - const auto paintPadding = [&](int section, const QRectF &rect, const QStyleOptionHeader::SectionPosition &pos){ + const auto paintPadding = [&](int section, const QRectF &rect, const QStyleOptionHeader::SectionPosition &pos) { QStyleOptionHeader padding; padding.state = QStyle::State_None | QStyle::State_Raised | QStyle::State_Horizontal; padding.section = section; @@ -473,7 +457,7 @@ void KItemListHeaderWidget::paintRole(QPainter* painter, // Paint the header for the first column; check if there is some empty space to the left which needs to be filled. if (rect.left() > 0) { option.position = QStyleOptionHeader::Middle; - paintPadding(0,QRectF(0.0, 0.0, rect.left(), rect.height()), QStyleOptionHeader::Beginning); + paintPadding(0, QRectF(0.0, 0.0, rect.left(), rect.height()), QStyleOptionHeader::Beginning); } else { option.position = QStyleOptionHeader::Beginning; } @@ -492,7 +476,7 @@ void KItemListHeaderWidget::paintRole(QPainter* painter, style()->drawControl(QStyle::CE_Header, &option, painter, widget); } -void KItemListHeaderWidget::updatePressedRoleIndex(const QPointF& pos) +void KItemListHeaderWidget::updatePressedRoleIndex(const QPointF &pos) { const int pressedIndex = roleIndexAt(pos); if (m_pressedRoleIndex != pressedIndex) { @@ -501,7 +485,7 @@ void KItemListHeaderWidget::updatePressedRoleIndex(const QPointF& pos) } } -void KItemListHeaderWidget::updateHoveredRoleIndex(const QPointF& pos) +void KItemListHeaderWidget::updateHoveredRoleIndex(const QPointF &pos) { const int hoverIndex = roleIndexAt(pos); if (m_hoveredRoleIndex != hoverIndex) { @@ -510,12 +494,12 @@ void KItemListHeaderWidget::updateHoveredRoleIndex(const QPointF& pos) } } -int KItemListHeaderWidget::roleIndexAt(const QPointF& pos) const +int KItemListHeaderWidget::roleIndexAt(const QPointF &pos) const { int index = -1; qreal x = -m_offset + m_sidePadding; - for (const QByteArray& role : qAsConst(m_columns)) { + for (const QByteArray &role : qAsConst(m_columns)) { ++index; x += m_columnWidths.value(role); if (pos.x() <= x) { @@ -526,7 +510,7 @@ int KItemListHeaderWidget::roleIndexAt(const QPointF& pos) const return index; } -bool KItemListHeaderWidget::isAboveRoleGrip(const QPointF& pos, int roleIndex) const +bool KItemListHeaderWidget::isAboveRoleGrip(const QPointF &pos, int roleIndex) const { qreal x = -m_offset + m_sidePadding; for (int i = 0; i <= roleIndex; ++i) { @@ -538,7 +522,7 @@ bool KItemListHeaderWidget::isAboveRoleGrip(const QPointF& pos, int roleIndex) c return pos.x() >= (x - grip) && pos.x() <= x; } -bool KItemListHeaderWidget::isAbovePaddingGrip(const QPointF& pos, PaddingGrip paddingGrip) const +bool KItemListHeaderWidget::isAbovePaddingGrip(const QPointF &pos, PaddingGrip paddingGrip) const { const qreal lx = -m_offset + m_sidePadding; const int grip = style()->pixelMetric(QStyle::PM_HeaderGripMargin); @@ -546,10 +530,9 @@ bool KItemListHeaderWidget::isAbovePaddingGrip(const QPointF& pos, PaddingGrip p switch (paddingGrip) { case Leading: return pos.x() >= (lx - grip) && pos.x() <= lx; - case Trailing: - { + case Trailing: { qreal rx = lx; - for (const QByteArray& role : qAsConst(m_columns)) { + for (const QByteArray &role : qAsConst(m_columns)) { rx += m_columnWidths.value(role); } return pos.x() >= (rx - grip) && pos.x() <= rx; @@ -596,12 +579,8 @@ int KItemListHeaderWidget::targetOfMovingRole() const const qreal targetWidth = m_columnWidths.value(role); const qreal targetRight = targetLeft + targetWidth - 1; - const bool isInTarget = (targetWidth >= movingWidth && - movingLeft >= targetLeft && - movingRight <= targetRight) || - (targetWidth < movingWidth && - movingLeft <= targetLeft && - movingRight >= targetRight); + const bool isInTarget = (targetWidth >= movingWidth && movingLeft >= targetLeft && movingRight <= targetRight) + || (targetWidth < movingWidth && movingLeft <= targetLeft && movingRight >= targetRight); if (isInTarget) { return targetIndex; @@ -614,10 +593,10 @@ int KItemListHeaderWidget::targetOfMovingRole() const return m_movingRole.index; } -qreal KItemListHeaderWidget::roleXPosition(const QByteArray& role) const +qreal KItemListHeaderWidget::roleXPosition(const QByteArray &role) const { qreal x = -m_offset + m_sidePadding; - for (const QByteArray& visibleRole : qAsConst(m_columns)) { + for (const QByteArray &visibleRole : qAsConst(m_columns)) { if (visibleRole == role) { return x; } @@ -627,4 +606,3 @@ qreal KItemListHeaderWidget::roleXPosition(const QByteArray& role) const return -1; } - diff --git a/src/kitemviews/private/kitemlistheaderwidget.h b/src/kitemviews/private/kitemlistheaderwidget.h index f99d64c81f..58c27b43ae 100644 --- a/src/kitemviews/private/kitemlistheaderwidget.h +++ b/src/kitemviews/private/kitemlistheaderwidget.h @@ -26,26 +26,26 @@ class DOLPHIN_EXPORT KItemListHeaderWidget : public QGraphicsWidget Q_OBJECT public: - explicit KItemListHeaderWidget(QGraphicsWidget* parent = nullptr); + explicit KItemListHeaderWidget(QGraphicsWidget *parent = nullptr); ~KItemListHeaderWidget() override; - void setModel(KItemModelBase* model); - KItemModelBase* model() const; + void setModel(KItemModelBase *model); + KItemModelBase *model() const; void setAutomaticColumnResizing(bool automatic); bool automaticColumnResizing() const; - void setColumns(const QList& roles); + void setColumns(const QList &roles); QList columns() const; - void setColumnWidth(const QByteArray& role, qreal width); - qreal columnWidth(const QByteArray& role) const; + void setColumnWidth(const QByteArray &role, qreal width); + qreal columnWidth(const QByteArray &role) const; /** * Sets the column-width that is required to show the role unclipped. */ - void setPreferredColumnWidth(const QByteArray& role, qreal width); - qreal preferredColumnWidth(const QByteArray& role) const; + void setPreferredColumnWidth(const QByteArray &role, qreal width); + qreal preferredColumnWidth(const QByteArray &role) const; void setOffset(qreal offset); qreal offset() const; @@ -55,16 +55,14 @@ public: qreal minimumColumnWidth() const; - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; Q_SIGNALS: /** * Is emitted if the width of a visible role has been adjusted by the user with the mouse * (no signal is emitted if KItemListHeader::setVisibleRoleWidth() is invoked). */ - void columnWidthChanged(const QByteArray& role, - qreal currentWidth, - qreal previousWidth); + void columnWidthChanged(const QByteArray &role, qreal currentWidth, qreal previousWidth); void sidePaddingChanged(qreal width); @@ -72,13 +70,12 @@ Q_SIGNALS: * Is emitted if the user has released the mouse button after adjusting the * width of a visible role. */ - void columnWidthChangeFinished(const QByteArray& role, - qreal currentWidth); + void columnWidthChangeFinished(const QByteArray &role, qreal currentWidth); /** * Is emitted if the position of the column has been changed. */ - void columnMoved(const QByteArray& role, int currentIndex, int previousIndex); + void columnMoved(const QByteArray &role, int currentIndex, int previousIndex); /** * Is emitted if the user has changed the sort order by clicking on a @@ -94,40 +91,34 @@ Q_SIGNALS: * the current sort role. Note that no signal will be emitted if the * sort role of the model has been changed without user interaction. */ - void sortRoleChanged(const QByteArray& current, const QByteArray& previous); + void sortRoleChanged(const QByteArray ¤t, const QByteArray &previous); protected: - void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override; - void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; - void hoverMoveEvent(QGraphicsSceneHoverEvent* event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override; private Q_SLOTS: - void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous); + void slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous); void slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous); private: - - enum PaddingGrip - { + enum PaddingGrip { Leading, Trailing, }; - void paintRole(QPainter* painter, - const QByteArray& role, - const QRectF& rect, - int orderIndex, - QWidget* widget = nullptr) const; + void paintRole(QPainter *painter, const QByteArray &role, const QRectF &rect, int orderIndex, QWidget *widget = nullptr) const; - void updatePressedRoleIndex(const QPointF& pos); - void updateHoveredRoleIndex(const QPointF& pos); - int roleIndexAt(const QPointF& pos) const; - bool isAboveRoleGrip(const QPointF& pos, int roleIndex) const; - bool isAbovePaddingGrip(const QPointF& pos, PaddingGrip paddingGrip) const; + void updatePressedRoleIndex(const QPointF &pos); + void updateHoveredRoleIndex(const QPointF &pos); + int roleIndexAt(const QPointF &pos) const; + bool isAboveRoleGrip(const QPointF &pos, int roleIndex) const; + bool isAbovePaddingGrip(const QPointF &pos, PaddingGrip paddingGrip) const; /** * Creates a pixmap of the role with the index \a roleIndex that is shown @@ -144,19 +135,13 @@ private: /** * @return x-position of the left border of the role \a role. */ - qreal roleXPosition(const QByteArray& role) const; + qreal roleXPosition(const QByteArray &role) const; private: - enum RoleOperation - { - NoRoleOperation, - ResizeRoleOperation, - ResizePaddingColumnOperation, - MoveRoleOperation - }; + enum RoleOperation { NoRoleOperation, ResizeRoleOperation, ResizePaddingColumnOperation, MoveRoleOperation }; bool m_automaticColumnResizing; - KItemModelBase* m_model; + KItemModelBase *m_model; qreal m_offset; qreal m_sidePadding; QList m_columns; @@ -168,8 +153,7 @@ private: RoleOperation m_roleOperation; QPointF m_pressedMousePos; - struct MovingRole - { + struct MovingRole { QPixmap pixmap; int x; int xDec; @@ -178,5 +162,3 @@ private: }; #endif - - diff --git a/src/kitemviews/private/kitemlistkeyboardsearchmanager.cpp b/src/kitemviews/private/kitemlistkeyboardsearchmanager.cpp index e646a6249d..b7318b3440 100644 --- a/src/kitemviews/private/kitemlistkeyboardsearchmanager.cpp +++ b/src/kitemviews/private/kitemlistkeyboardsearchmanager.cpp @@ -8,10 +8,10 @@ #include "kitemlistkeyboardsearchmanager.h" -KItemListKeyboardSearchManager::KItemListKeyboardSearchManager(QObject* parent) : - QObject(parent), - m_isSearchRestarted(false), - m_timeout(1000) +KItemListKeyboardSearchManager::KItemListKeyboardSearchManager(QObject *parent) + : QObject(parent) + , m_isSearchRestarted(false) + , m_timeout(1000) { m_keyboardInputTime.invalidate(); } @@ -27,7 +27,7 @@ bool KItemListKeyboardSearchManager::shouldClearSearchIfInputTimeReached() return (keyboardInputTimeElapsed > m_timeout) || !keyboardTimeWasValid; } -void KItemListKeyboardSearchManager::addKeys(const QString& keys) +void KItemListKeyboardSearchManager::addKeys(const QString &keys) { if (shouldClearSearchIfInputTimeReached()) { m_searchedString.clear(); @@ -94,7 +94,7 @@ void KItemListKeyboardSearchManager::slotCurrentChanged(int current, int previou } } -void KItemListKeyboardSearchManager::slotSelectionChanged(const KItemSet& current, const KItemSet& previous) +void KItemListKeyboardSearchManager::slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous) { if (!previous.isEmpty() && current.isEmpty() && previous.count() > 0 && current.count() == 0) { // The selection has been emptied. We should cancel the search. diff --git a/src/kitemviews/private/kitemlistkeyboardsearchmanager.h b/src/kitemviews/private/kitemlistkeyboardsearchmanager.h index 80caea2ed2..d370bc9ba5 100644 --- a/src/kitemviews/private/kitemlistkeyboardsearchmanager.h +++ b/src/kitemviews/private/kitemlistkeyboardsearchmanager.h @@ -27,14 +27,13 @@ class DOLPHIN_EXPORT KItemListKeyboardSearchManager : public QObject Q_OBJECT public: - - explicit KItemListKeyboardSearchManager(QObject* parent = nullptr); + explicit KItemListKeyboardSearchManager(QObject *parent = nullptr); ~KItemListKeyboardSearchManager() override; /** * Add \a keys to the text buffer used for searching. */ - void addKeys(const QString& keys); + void addKeys(const QString &keys); /** * @returns true if the next call to addKeys() will trigger a new search. * Returns false if the next added key char will be added to the search string that was used previously. @@ -55,7 +54,7 @@ public: public Q_SLOTS: void slotCurrentChanged(int current, int previous); - void slotSelectionChanged(const KItemSet& current, const KItemSet& previous); + void slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous); Q_SIGNALS: /** @@ -67,7 +66,7 @@ Q_SIGNALS: */ // TODO: Think about getting rid of the bool parameter // (see https://doc.qt.io/archives/qq/qq13-apis.html#thebooleanparametertrap) - void changeCurrentItem(const QString& string, bool searchFromNextItem); + void changeCurrentItem(const QString &string, bool searchFromNextItem); private: bool shouldClearSearchIfInputTimeReached(); @@ -82,5 +81,3 @@ private: }; #endif - - diff --git a/src/kitemviews/private/kitemlistroleeditor.cpp b/src/kitemviews/private/kitemlistroleeditor.cpp index 993c6893a9..d3389832bf 100644 --- a/src/kitemviews/private/kitemlistroleeditor.cpp +++ b/src/kitemviews/private/kitemlistroleeditor.cpp @@ -8,10 +8,10 @@ #include -KItemListRoleEditor::KItemListRoleEditor(QWidget *parent) : - KTextEdit(parent), - m_role(), - m_blockFinishedSignal(false) +KItemListRoleEditor::KItemListRoleEditor(QWidget *parent) + : KTextEdit(parent) + , m_role() + , m_blockFinishedSignal(false) { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -30,7 +30,7 @@ KItemListRoleEditor::~KItemListRoleEditor() { } -void KItemListRoleEditor::setRole(const QByteArray& role) +void KItemListRoleEditor::setRole(const QByteArray &role) { m_role = role; } @@ -45,7 +45,7 @@ void KItemListRoleEditor::setAllowUpDownKeyChainEdit(bool allowChainEdit) m_allowUpDownKeyChainEdit = allowChainEdit; } -bool KItemListRoleEditor::eventFilter(QObject* watched, QEvent* event) +bool KItemListRoleEditor::eventFilter(QObject *watched, QEvent *event) { if (watched == parentWidget() && event->type() == QEvent::Resize) { emitRoleEditingFinished(); @@ -54,10 +54,10 @@ bool KItemListRoleEditor::eventFilter(QObject* watched, QEvent* event) return KTextEdit::eventFilter(watched, event); } -bool KItemListRoleEditor::event(QEvent* event) +bool KItemListRoleEditor::event(QEvent *event) { if (event->type() == QEvent::FocusOut) { - QFocusEvent* focusEvent = static_cast(event); + QFocusEvent *focusEvent = static_cast(event); if (focusEvent->reason() != Qt::PopupFocusReason) { emitRoleEditingFinished(); } @@ -65,7 +65,7 @@ bool KItemListRoleEditor::event(QEvent* event) return KTextEdit::event(event); } -void KItemListRoleEditor::keyPressEvent(QKeyEvent* event) +void KItemListRoleEditor::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Escape: @@ -118,12 +118,8 @@ void KItemListRoleEditor::keyPressEvent(QKeyEvent* event) case Qt::Key_Home: case Qt::Key_End: { if (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier) { - const QTextCursor::MoveOperation op = event->key() == Qt::Key_Home - ? QTextCursor::Start - : QTextCursor::End; - const QTextCursor::MoveMode mode = event->modifiers() == Qt::NoModifier - ? QTextCursor::MoveAnchor - : QTextCursor::KeepAnchor; + const QTextCursor::MoveOperation op = event->key() == Qt::Key_Home ? QTextCursor::Start : QTextCursor::End; + const QTextCursor::MoveMode mode = event->modifiers() == Qt::NoModifier ? QTextCursor::MoveAnchor : QTextCursor::KeepAnchor; QTextCursor cursor = textCursor(); cursor.movePosition(op, mode); setTextCursor(cursor); @@ -167,10 +163,9 @@ void KItemListRoleEditor::autoAdjustSize() void KItemListRoleEditor::emitRoleEditingFinished(EditResultDirection direction) { QVariant ret; - ret.setValue(EditResult {KIO::encodeFileName(toPlainText()), direction}); + ret.setValue(EditResult{KIO::encodeFileName(toPlainText()), direction}); if (!m_blockFinishedSignal) { Q_EMIT roleEditingFinished(m_role, ret); } } - diff --git a/src/kitemviews/private/kitemlistroleeditor.h b/src/kitemviews/private/kitemlistroleeditor.h index a0f55df51f..18304374d4 100644 --- a/src/kitemviews/private/kitemlistroleeditor.h +++ b/src/kitemviews/private/kitemlistroleeditor.h @@ -11,15 +11,14 @@ #include -enum EditResultDirection{ +enum EditResultDirection { EditDone, EditNext, EditPrevious, }; Q_DECLARE_METATYPE(EditResultDirection) -struct EditResult -{ +struct EditResult { QString newName; EditResultDirection direction; }; @@ -39,22 +38,22 @@ class DOLPHIN_EXPORT KItemListRoleEditor : public KTextEdit Q_OBJECT public: - explicit KItemListRoleEditor(QWidget* parent); + explicit KItemListRoleEditor(QWidget *parent); ~KItemListRoleEditor() override; - void setRole(const QByteArray& role); + void setRole(const QByteArray &role); QByteArray role() const; void setAllowUpDownKeyChainEdit(bool allowChainEdit); - bool eventFilter(QObject* watched, QEvent* event) override; + bool eventFilter(QObject *watched, QEvent *event) override; Q_SIGNALS: - void roleEditingFinished(const QByteArray& role, const QVariant& value); - void roleEditingCanceled(const QByteArray& role, const QVariant& value); + void roleEditingFinished(const QByteArray &role, const QVariant &value); + void roleEditingCanceled(const QByteArray &role, const QVariant &value); protected: - bool event(QEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; + bool event(QEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; private Q_SLOTS: /** diff --git a/src/kitemviews/private/kitemlistrubberband.cpp b/src/kitemviews/private/kitemlistrubberband.cpp index 646139a330..e572780e72 100644 --- a/src/kitemviews/private/kitemlistrubberband.cpp +++ b/src/kitemviews/private/kitemlistrubberband.cpp @@ -6,11 +6,11 @@ #include "kitemlistrubberband.h" -KItemListRubberBand::KItemListRubberBand(QObject* parent) : - QObject(parent), - m_active(false), - m_startPos(), - m_endPos() +KItemListRubberBand::KItemListRubberBand(QObject *parent) + : QObject(parent) + , m_active(false) + , m_startPos() + , m_endPos() { } @@ -18,7 +18,7 @@ KItemListRubberBand::~KItemListRubberBand() { } -void KItemListRubberBand::setStartPosition(const QPointF& pos) +void KItemListRubberBand::setStartPosition(const QPointF &pos) { if (m_startPos != pos) { const QPointF previous = m_startPos; @@ -32,7 +32,7 @@ QPointF KItemListRubberBand::startPosition() const return m_startPos; } -void KItemListRubberBand::setEndPosition(const QPointF& pos) +void KItemListRubberBand::setEndPosition(const QPointF &pos) { if (m_endPos != pos) { const QPointF previous = m_endPos; @@ -74,4 +74,3 @@ bool KItemListRubberBand::isActive() const { return m_active; } - diff --git a/src/kitemviews/private/kitemlistrubberband.h b/src/kitemviews/private/kitemlistrubberband.h index 11febcf7eb..fd1416b565 100644 --- a/src/kitemviews/private/kitemlistrubberband.h +++ b/src/kitemviews/private/kitemlistrubberband.h @@ -21,13 +21,13 @@ class DOLPHIN_EXPORT KItemListRubberBand : public QObject Q_PROPERTY(QPointF endPosition MEMBER m_endPos READ endPosition WRITE setEndPosition) public: - explicit KItemListRubberBand(QObject* parent = nullptr); + explicit KItemListRubberBand(QObject *parent = nullptr); ~KItemListRubberBand() override; - void setStartPosition(const QPointF& pos); + void setStartPosition(const QPointF &pos); QPointF startPosition() const; - void setEndPosition(const QPointF& pos); + void setEndPosition(const QPointF &pos); QPointF endPosition() const; void setActive(bool active); @@ -35,8 +35,8 @@ public: Q_SIGNALS: void activationChanged(bool active); - void startPositionChanged(const QPointF& current, const QPointF& previous); - void endPositionChanged(const QPointF& current, const QPointF& previous); + void startPositionChanged(const QPointF ¤t, const QPointF &previous); + void endPositionChanged(const QPointF ¤t, const QPointF &previous); private: bool m_active; @@ -45,5 +45,3 @@ private: }; #endif - - diff --git a/src/kitemviews/private/kitemlistselectiontoggle.cpp b/src/kitemviews/private/kitemlistselectiontoggle.cpp index 2905e29257..bec32b3d35 100644 --- a/src/kitemviews/private/kitemlistselectiontoggle.cpp +++ b/src/kitemviews/private/kitemlistselectiontoggle.cpp @@ -11,10 +11,10 @@ #include #include -KItemListSelectionToggle::KItemListSelectionToggle(QGraphicsItem* parent) : - QGraphicsWidget(parent), - m_checked(false), - m_hovered(false) +KItemListSelectionToggle::KItemListSelectionToggle(QGraphicsItem *parent) + : QGraphicsWidget(parent) + , m_checked(false) + , m_hovered(false) { } @@ -45,7 +45,7 @@ void KItemListSelectionToggle::setHovered(bool hovered) } } -void KItemListSelectionToggle::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void KItemListSelectionToggle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option) Q_UNUSED(widget) @@ -54,12 +54,12 @@ void KItemListSelectionToggle::paint(QPainter* painter, const QStyleOptionGraphi updatePixmap(); } - const qreal x = (size().width() - qreal(m_pixmap.width() / m_pixmap.devicePixelRatioF())) / 2; + const qreal x = (size().width() - qreal(m_pixmap.width() / m_pixmap.devicePixelRatioF())) / 2; const qreal y = (size().height() - qreal(m_pixmap.height() / m_pixmap.devicePixelRatioF())) / 2; painter->drawPixmap(x, y, m_pixmap); } -void KItemListSelectionToggle::resizeEvent(QGraphicsSceneResizeEvent* event) +void KItemListSelectionToggle::resizeEvent(QGraphicsSceneResizeEvent *event) { QGraphicsWidget::resizeEvent(event); @@ -99,4 +99,3 @@ int KItemListSelectionToggle::iconSize() const return iconSize; } - diff --git a/src/kitemviews/private/kitemlistselectiontoggle.h b/src/kitemviews/private/kitemlistselectiontoggle.h index 0a592653ed..2f3969c298 100644 --- a/src/kitemviews/private/kitemlistselectiontoggle.h +++ b/src/kitemviews/private/kitemlistselectiontoggle.h @@ -11,7 +11,6 @@ #include #include - /** * @brief Allows to toggle between the selected and unselected state of an item. */ @@ -20,7 +19,7 @@ class DOLPHIN_EXPORT KItemListSelectionToggle : public QGraphicsWidget Q_OBJECT public: - explicit KItemListSelectionToggle(QGraphicsItem* parent); + explicit KItemListSelectionToggle(QGraphicsItem *parent); ~KItemListSelectionToggle() override; void setChecked(bool checked); @@ -28,10 +27,10 @@ public: void setHovered(bool hovered); - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; protected: - void resizeEvent(QGraphicsSceneResizeEvent* event) override; + void resizeEvent(QGraphicsSceneResizeEvent *event) override; private: void updatePixmap(); @@ -44,5 +43,3 @@ private: }; #endif - - diff --git a/src/kitemviews/private/kitemlistsizehintresolver.cpp b/src/kitemviews/private/kitemlistsizehintresolver.cpp index 0c2dd0b807..b7165e8c30 100644 --- a/src/kitemviews/private/kitemlistsizehintresolver.cpp +++ b/src/kitemviews/private/kitemlistsizehintresolver.cpp @@ -7,12 +7,12 @@ #include "kitemlistsizehintresolver.h" #include "kitemviews/kitemlistview.h" -KItemListSizeHintResolver::KItemListSizeHintResolver(const KItemListView* itemListView) : - m_itemListView(itemListView), - m_logicalHeightHintCache(), - m_logicalWidthHint(0.0), - m_minHeightHint(0.0), - m_needsResolving(false) +KItemListSizeHintResolver::KItemListSizeHintResolver(const KItemListView *itemListView) + : m_itemListView(itemListView) + , m_logicalHeightHintCache() + , m_logicalWidthHint(0.0) + , m_minHeightHint(0.0) + , m_needsResolving(false) { } @@ -37,10 +37,10 @@ bool KItemListSizeHintResolver::isElided(int index) return m_logicalHeightHintCache.at(index).second; } -void KItemListSizeHintResolver::itemsInserted(const KItemRangeList& itemRanges) +void KItemListSizeHintResolver::itemsInserted(const KItemRangeList &itemRanges) { int insertedCount = 0; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { insertedCount += range.count; } @@ -56,7 +56,7 @@ void KItemListSizeHintResolver::itemsInserted(const KItemRangeList& itemRanges) int itemsToInsertBeforeCurrentRange = insertedCount; for (int rangeIndex = itemRanges.count() - 1; rangeIndex >= 0; --rangeIndex) { - const KItemRange& range = itemRanges.at(rangeIndex); + const KItemRange &range = itemRanges.at(rangeIndex); itemsToInsertBeforeCurrentRange -= range.count; // First: move all existing items that must be put behind 'range'. @@ -78,7 +78,7 @@ void KItemListSizeHintResolver::itemsInserted(const KItemRangeList& itemRanges) Q_ASSERT(m_logicalHeightHintCache.count() == m_itemListView->model()->count()); } -void KItemListSizeHintResolver::itemsRemoved(const KItemRangeList& itemRanges) +void KItemListSizeHintResolver::itemsRemoved(const KItemRangeList &itemRanges) { const QVector>::iterator begin = m_logicalHeightHintCache.begin(); const QVector>::iterator end = m_logicalHeightHintCache.end(); @@ -112,7 +112,7 @@ void KItemListSizeHintResolver::itemsRemoved(const KItemRangeList& itemRanges) } } -void KItemListSizeHintResolver::itemsMoved(const KItemRange& range, const QList& movedToIndexes) +void KItemListSizeHintResolver::itemsMoved(const KItemRange &range, const QList &movedToIndexes) { QVector> newLogicalHeightHintCache(m_logicalHeightHintCache); @@ -125,7 +125,7 @@ void KItemListSizeHintResolver::itemsMoved(const KItemRange& range, const QList< m_logicalHeightHintCache = newLogicalHeightHintCache; } -void KItemListSizeHintResolver::itemsChanged(int index, int count, const QSet& roles) +void KItemListSizeHintResolver::itemsChanged(int index, int count, const QSet &roles) { Q_UNUSED(roles) while (count) { diff --git a/src/kitemviews/private/kitemlistsizehintresolver.h b/src/kitemviews/private/kitemlistsizehintresolver.h index a6cc56614e..c5a47f130e 100644 --- a/src/kitemviews/private/kitemlistsizehintresolver.h +++ b/src/kitemviews/private/kitemlistsizehintresolver.h @@ -21,22 +21,22 @@ class KItemListView; class DOLPHIN_EXPORT KItemListSizeHintResolver { public: - explicit KItemListSizeHintResolver(const KItemListView* itemListView); + explicit KItemListSizeHintResolver(const KItemListView *itemListView); virtual ~KItemListSizeHintResolver(); QSizeF minSizeHint(); QSizeF sizeHint(int index); bool isElided(int index); - void itemsInserted(const KItemRangeList& itemRanges); - void itemsRemoved(const KItemRangeList& itemRanges); - void itemsMoved(const KItemRange& range, const QList& movedToIndexes); - void itemsChanged(int index, int count, const QSet& roles); + void itemsInserted(const KItemRangeList &itemRanges); + void itemsRemoved(const KItemRangeList &itemRanges); + void itemsMoved(const KItemRange &range, const QList &movedToIndexes); + void itemsChanged(int index, int count, const QSet &roles); void clearCache(); void updateCache(); private: - const KItemListView* m_itemListView; + const KItemListView *m_itemListView; mutable QVector> m_logicalHeightHintCache; mutable qreal m_logicalWidthHint; mutable qreal m_minHeightHint; diff --git a/src/kitemviews/private/kitemlistsmoothscroller.cpp b/src/kitemviews/private/kitemlistsmoothscroller.cpp index 343399179b..19d47aac84 100644 --- a/src/kitemviews/private/kitemlistsmoothscroller.cpp +++ b/src/kitemviews/private/kitemlistsmoothscroller.cpp @@ -12,20 +12,18 @@ #include #include -KItemListSmoothScroller::KItemListSmoothScroller(QScrollBar* scrollBar, - QObject* parent) : - QObject(parent), - m_scrollBarPressed(false), - m_smoothScrolling(true), - m_scrollBar(scrollBar), - m_animation(nullptr) +KItemListSmoothScroller::KItemListSmoothScroller(QScrollBar *scrollBar, QObject *parent) + : QObject(parent) + , m_scrollBarPressed(false) + , m_smoothScrolling(true) + , m_scrollBar(scrollBar) + , m_animation(nullptr) { m_animation = new QPropertyAnimation(this); const int animationDuration = m_scrollBar->style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, m_scrollBar); const bool animationEnabled = (animationDuration > 0); m_animation->setDuration(animationEnabled ? animationDuration : 1); - connect(m_animation, &QPropertyAnimation::stateChanged, - this, &KItemListSmoothScroller::slotAnimationStateChanged); + connect(m_animation, &QPropertyAnimation::stateChanged, this, &KItemListSmoothScroller::slotAnimationStateChanged); m_scrollBar->installEventFilter(this); } @@ -39,22 +37,22 @@ void KItemListSmoothScroller::setScrollBar(QScrollBar *scrollBar) m_scrollBar = scrollBar; } -QScrollBar* KItemListSmoothScroller::scrollBar() const +QScrollBar *KItemListSmoothScroller::scrollBar() const { return m_scrollBar; } -void KItemListSmoothScroller::setTargetObject(QObject* target) +void KItemListSmoothScroller::setTargetObject(QObject *target) { m_animation->setTargetObject(target); } -QObject* KItemListSmoothScroller::targetObject() const +QObject *KItemListSmoothScroller::targetObject() const { return m_animation->targetObject(); } -void KItemListSmoothScroller::setPropertyName(const QByteArray& propertyName) +void KItemListSmoothScroller::setPropertyName(const QByteArray &propertyName) { m_animation->setPropertyName(propertyName); } @@ -66,7 +64,7 @@ QByteArray KItemListSmoothScroller::propertyName() const void KItemListSmoothScroller::scrollContentsBy(qreal distance) { - QObject* target = targetObject(); + QObject *target = targetObject(); if (!target) { return; } @@ -143,7 +141,7 @@ bool KItemListSmoothScroller::requestScrollBarUpdate(int newMaximum) return true; } -bool KItemListSmoothScroller::eventFilter(QObject* obj, QEvent* event) +bool KItemListSmoothScroller::eventFilter(QObject *obj, QEvent *event) { Q_ASSERT(obj == m_scrollBar); @@ -168,8 +166,7 @@ bool KItemListSmoothScroller::eventFilter(QObject* obj, QEvent* event) return QObject::eventFilter(obj, event); } -void KItemListSmoothScroller::slotAnimationStateChanged(QAbstractAnimation::State newState, - QAbstractAnimation::State oldState) +void KItemListSmoothScroller::slotAnimationStateChanged(QAbstractAnimation::State newState, QAbstractAnimation::State oldState) { Q_UNUSED(oldState) if (newState == QAbstractAnimation::Stopped && m_smoothScrolling && !m_scrollBarPressed) { @@ -180,7 +177,7 @@ void KItemListSmoothScroller::slotAnimationStateChanged(QAbstractAnimation::Stat } } -void KItemListSmoothScroller::handleWheelEvent(QWheelEvent* event) +void KItemListSmoothScroller::handleWheelEvent(QWheelEvent *event) { const bool previous = m_smoothScrolling; @@ -198,4 +195,3 @@ void KItemListSmoothScroller::handleWheelEvent(QWheelEvent* event) m_smoothScrolling = previous; } - diff --git a/src/kitemviews/private/kitemlistsmoothscroller.h b/src/kitemviews/private/kitemlistsmoothscroller.h index 7b2839884f..d1cfcf9d99 100644 --- a/src/kitemviews/private/kitemlistsmoothscroller.h +++ b/src/kitemviews/private/kitemlistsmoothscroller.h @@ -25,17 +25,16 @@ class DOLPHIN_EXPORT KItemListSmoothScroller : public QObject Q_OBJECT public: - explicit KItemListSmoothScroller(QScrollBar* scrollBar, - QObject* parent = nullptr); + explicit KItemListSmoothScroller(QScrollBar *scrollBar, QObject *parent = nullptr); ~KItemListSmoothScroller() override; - void setScrollBar(QScrollBar* scrollBar); - QScrollBar* scrollBar() const; + void setScrollBar(QScrollBar *scrollBar); + QScrollBar *scrollBar() const; - void setTargetObject(QObject* target); - QObject* targetObject() const; + void setTargetObject(QObject *target); + QObject *targetObject() const; - void setPropertyName(const QByteArray& propertyName); + void setPropertyName(const QByteArray &propertyName); QByteArray propertyName() const; /** @@ -67,27 +66,25 @@ public: /** * Forwards wheel events to the scrollbar, ensuring smooth and proper scrolling */ - void handleWheelEvent(QWheelEvent* event); + void handleWheelEvent(QWheelEvent *event); Q_SIGNALS: /** * Emitted when the scrolling animation has finished */ void scrollingStopped(); + protected: - bool eventFilter(QObject* obj, QEvent* event) override; + bool eventFilter(QObject *obj, QEvent *event) override; private Q_SLOTS: - void slotAnimationStateChanged(QAbstractAnimation::State newState, - QAbstractAnimation::State oldState); + void slotAnimationStateChanged(QAbstractAnimation::State newState, QAbstractAnimation::State oldState); private: bool m_scrollBarPressed; bool m_smoothScrolling; - QScrollBar* m_scrollBar; - QPropertyAnimation* m_animation; + QScrollBar *m_scrollBar; + QPropertyAnimation *m_animation; }; #endif - - diff --git a/src/kitemviews/private/kitemlistviewanimation.cpp b/src/kitemviews/private/kitemlistviewanimation.cpp index 0c16c8b0a0..83a7a2ec6f 100644 --- a/src/kitemviews/private/kitemlistviewanimation.cpp +++ b/src/kitemviews/private/kitemlistviewanimation.cpp @@ -9,11 +9,11 @@ #include -KItemListViewAnimation::KItemListViewAnimation(QObject* parent) : - QObject(parent), - m_scrollOrientation(Qt::Vertical), - m_scrollOffset(0), - m_animation() +KItemListViewAnimation::KItemListViewAnimation(QObject *parent) + : QObject(parent) + , m_scrollOrientation(Qt::Vertical) + , m_scrollOffset(0) + , m_animation() { } @@ -48,12 +48,12 @@ void KItemListViewAnimation::setScrollOffset(qreal offset) continue; } - QHashIterator it(m_animation[type]); + QHashIterator it(m_animation[type]); while (it.hasNext()) { it.next(); - QGraphicsWidget* widget = it.key(); - QPropertyAnimation* propertyAnim = it.value(); + QGraphicsWidget *widget = it.key(); + QPropertyAnimation *propertyAnim = it.value(); QPointF currentPos = widget->pos(); if (m_scrollOrientation == Qt::Vertical) { @@ -65,8 +65,7 @@ void KItemListViewAnimation::setScrollOffset(qreal offset) if (type == MovingAnimation) { // Stop the animation, calculate the moved start- and end-value // and restart the animation for the remaining duration. - const int remainingDuration = propertyAnim->duration() - - propertyAnim->currentTime(); + const int remainingDuration = propertyAnim->duration() - propertyAnim->currentTime(); const bool block = propertyAnim->signalsBlocked(); propertyAnim->blockSignals(true); @@ -96,11 +95,11 @@ qreal KItemListViewAnimation::scrollOffset() const return m_scrollOffset; } -void KItemListViewAnimation::start(QGraphicsWidget* widget, AnimationType type, const QVariant& endValue) +void KItemListViewAnimation::start(QGraphicsWidget *widget, AnimationType type, const QVariant &endValue) { stop(widget, type); - QPropertyAnimation* propertyAnim = nullptr; + QPropertyAnimation *propertyAnim = nullptr; const int animationDuration = widget->style()->styleHint(QStyle::SH_Widget_Animate) ? 200 : 1; switch (type) { @@ -165,18 +164,25 @@ void KItemListViewAnimation::start(QGraphicsWidget* widget, AnimationType type, propertyAnim->start(); } -void KItemListViewAnimation::stop(QGraphicsWidget* widget, AnimationType type) +void KItemListViewAnimation::stop(QGraphicsWidget *widget, AnimationType type) { - QPropertyAnimation* propertyAnim = m_animation[type].value(widget); + QPropertyAnimation *propertyAnim = m_animation[type].value(widget); if (propertyAnim) { propertyAnim->stop(); switch (type) { - case MovingAnimation: break; - case CreateAnimation: widget->setOpacity(1.0); break; - case DeleteAnimation: widget->setOpacity(0.0); break; - case ResizeAnimation: break; - default: break; + case MovingAnimation: + break; + case CreateAnimation: + widget->setOpacity(1.0); + break; + case DeleteAnimation: + widget->setOpacity(0.0); + break; + case ResizeAnimation: + break; + default: + break; } m_animation[type].remove(widget); @@ -186,7 +192,7 @@ void KItemListViewAnimation::stop(QGraphicsWidget* widget, AnimationType type) } } -void KItemListViewAnimation::stop(QGraphicsWidget* widget) +void KItemListViewAnimation::stop(QGraphicsWidget *widget) { for (int type = 0; type < AnimationTypeCount; ++type) { stop(widget, static_cast(type)); @@ -198,7 +204,7 @@ bool KItemListViewAnimation::isStarted(QGraphicsWidget *widget, AnimationType ty return m_animation[type].value(widget); } -bool KItemListViewAnimation::isStarted(QGraphicsWidget* widget) const +bool KItemListViewAnimation::isStarted(QGraphicsWidget *widget) const { for (int type = 0; type < AnimationTypeCount; ++type) { if (isStarted(widget, static_cast(type))) { @@ -210,14 +216,14 @@ bool KItemListViewAnimation::isStarted(QGraphicsWidget* widget) const void KItemListViewAnimation::slotFinished() { - QPropertyAnimation* finishedAnim = qobject_cast(sender()); + QPropertyAnimation *finishedAnim = qobject_cast(sender()); for (int type = 0; type < AnimationTypeCount; ++type) { - QMutableHashIterator it(m_animation[type]); + QMutableHashIterator it(m_animation[type]); while (it.hasNext()) { it.next(); - QPropertyAnimation* propertyAnim = it.value(); + QPropertyAnimation *propertyAnim = it.value(); if (propertyAnim == finishedAnim) { - QGraphicsWidget* widget = it.key(); + QGraphicsWidget *widget = it.key(); it.remove(); finishedAnim->deleteLater(); @@ -228,4 +234,3 @@ void KItemListViewAnimation::slotFinished() } Q_ASSERT(false); } - diff --git a/src/kitemviews/private/kitemlistviewanimation.h b/src/kitemviews/private/kitemlistviewanimation.h index 5e0ebf9824..c052d5dff4 100644 --- a/src/kitemviews/private/kitemlistviewanimation.h +++ b/src/kitemviews/private/kitemlistviewanimation.h @@ -28,16 +28,9 @@ class DOLPHIN_EXPORT KItemListViewAnimation : public QObject Q_OBJECT public: - enum AnimationType { - MovingAnimation, - CreateAnimation, - DeleteAnimation, - ResizeAnimation, - IconResizeAnimation, - AnimationTypeCount - }; + enum AnimationType { MovingAnimation, CreateAnimation, DeleteAnimation, ResizeAnimation, IconResizeAnimation, AnimationTypeCount }; - explicit KItemListViewAnimation(QObject* parent = nullptr); + explicit KItemListViewAnimation(QObject *parent = nullptr); ~KItemListViewAnimation() override; void setScrollOrientation(Qt::Orientation orientation); @@ -51,17 +44,17 @@ public: * of the type is already running, this animation will be stopped before starting * the new animation. */ - void start(QGraphicsWidget* widget, AnimationType type, const QVariant& endValue = QVariant()); + void start(QGraphicsWidget *widget, AnimationType type, const QVariant &endValue = QVariant()); /** * Stops the animation of the type \a type for the widget \a widget. */ - void stop(QGraphicsWidget* widget, AnimationType type); + void stop(QGraphicsWidget *widget, AnimationType type); /** * Stops all animations that have been applied to the widget \a widget. */ - void stop(QGraphicsWidget* widget); + void stop(QGraphicsWidget *widget); /** * @return True if the animation of the type \a type has been started @@ -72,10 +65,10 @@ public: /** * @return True if any animation has been started for the widget. */ - bool isStarted(QGraphicsWidget* widget) const; + bool isStarted(QGraphicsWidget *widget) const; Q_SIGNALS: - void finished(QGraphicsWidget* widget, KItemListViewAnimation::AnimationType type); + void finished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type); private Q_SLOTS: void slotFinished(); @@ -83,9 +76,7 @@ private Q_SLOTS: private: Qt::Orientation m_scrollOrientation; qreal m_scrollOffset; - QHash m_animation[AnimationTypeCount]; + QHash m_animation[AnimationTypeCount]; }; #endif - - diff --git a/src/kitemviews/private/kitemlistviewlayouter.cpp b/src/kitemviews/private/kitemlistviewlayouter.cpp index 4c22b4dbcb..027943683f 100644 --- a/src/kitemviews/private/kitemlistviewlayouter.cpp +++ b/src/kitemviews/private/kitemlistviewlayouter.cpp @@ -14,32 +14,32 @@ // #define KITEMLISTVIEWLAYOUTER_DEBUG -KItemListViewLayouter::KItemListViewLayouter(KItemListSizeHintResolver* sizeHintResolver, QObject* parent) : - QObject(parent), - m_dirty(true), - m_visibleIndexesDirty(true), - m_scrollOrientation(Qt::Vertical), - m_size(), - m_itemSize(128, 128), - m_itemMargin(), - m_headerHeight(0), - m_model(nullptr), - m_sizeHintResolver(sizeHintResolver), - m_scrollOffset(0), - m_maximumScrollOffset(0), - m_itemOffset(0), - m_maximumItemOffset(0), - m_firstVisibleIndex(-1), - m_lastVisibleIndex(-1), - m_columnWidth(0), - m_xPosInc(0), - m_columnCount(0), - m_rowOffsets(), - m_columnOffsets(), - m_groupItemIndexes(), - m_groupHeaderHeight(0), - m_groupHeaderMargin(0), - m_itemInfos() +KItemListViewLayouter::KItemListViewLayouter(KItemListSizeHintResolver *sizeHintResolver, QObject *parent) + : QObject(parent) + , m_dirty(true) + , m_visibleIndexesDirty(true) + , m_scrollOrientation(Qt::Vertical) + , m_size() + , m_itemSize(128, 128) + , m_itemMargin() + , m_headerHeight(0) + , m_model(nullptr) + , m_sizeHintResolver(sizeHintResolver) + , m_scrollOffset(0) + , m_maximumScrollOffset(0) + , m_itemOffset(0) + , m_maximumItemOffset(0) + , m_firstVisibleIndex(-1) + , m_lastVisibleIndex(-1) + , m_columnWidth(0) + , m_xPosInc(0) + , m_columnCount(0) + , m_rowOffsets() + , m_columnOffsets() + , m_groupItemIndexes() + , m_groupHeaderHeight(0) + , m_groupHeaderMargin(0) + , m_itemInfos() { Q_ASSERT(m_sizeHintResolver); } @@ -61,7 +61,7 @@ Qt::Orientation KItemListViewLayouter::scrollOrientation() const return m_scrollOrientation; } -void KItemListViewLayouter::setSize(const QSizeF& size) +void KItemListViewLayouter::setSize(const QSizeF &size) { if (m_size != size) { if (m_scrollOrientation == Qt::Vertical) { @@ -82,7 +82,7 @@ QSizeF KItemListViewLayouter::size() const return m_size; } -void KItemListViewLayouter::setItemSize(const QSizeF& size) +void KItemListViewLayouter::setItemSize(const QSizeF &size) { if (m_itemSize != size) { m_itemSize = size; @@ -95,7 +95,7 @@ QSizeF KItemListViewLayouter::itemSize() const return m_itemSize; } -void KItemListViewLayouter::setItemMargin(const QSizeF& margin) +void KItemListViewLayouter::setItemMargin(const QSizeF &margin) { if (m_itemMargin != margin) { m_itemMargin = margin; @@ -162,7 +162,7 @@ qreal KItemListViewLayouter::scrollOffset() const qreal KItemListViewLayouter::maximumScrollOffset() const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); return m_maximumScrollOffset; } @@ -181,11 +181,11 @@ qreal KItemListViewLayouter::itemOffset() const qreal KItemListViewLayouter::maximumItemOffset() const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); return m_maximumItemOffset; } -void KItemListViewLayouter::setModel(const KItemModelBase* model) +void KItemListViewLayouter::setModel(const KItemModelBase *model) { if (m_model != model) { m_model = model; @@ -193,26 +193,26 @@ void KItemListViewLayouter::setModel(const KItemModelBase* model) } } -const KItemModelBase* KItemListViewLayouter::model() const +const KItemModelBase *KItemListViewLayouter::model() const { return m_model; } int KItemListViewLayouter::firstVisibleIndex() const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); return m_firstVisibleIndex; } int KItemListViewLayouter::lastVisibleIndex() const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); return m_lastVisibleIndex; } QRectF KItemListViewLayouter::itemRect(int index) const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); if (index < 0 || index >= m_itemInfos.count()) { return QRectF(); } @@ -242,7 +242,7 @@ QRectF KItemListViewLayouter::itemRect(int index) const QRectF KItemListViewLayouter::groupHeaderRect(int index) const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); const QRectF firstItemRect = itemRect(index); QPointF pos = firstItemRect.topLeft(); @@ -271,9 +271,8 @@ QRectF KItemListViewLayouter::groupHeaderRect(int index) const break; } - const qreal itemWidth = (m_scrollOrientation == Qt::Vertical) - ? m_sizeHintResolver->sizeHint(index).width() - : m_sizeHintResolver->sizeHint(index).height(); + const qreal itemWidth = + (m_scrollOrientation == Qt::Vertical) ? m_sizeHintResolver->sizeHint(index).width() : m_sizeHintResolver->sizeHint(index).height(); if (itemWidth > headerWidth) { headerWidth = itemWidth; @@ -289,31 +288,27 @@ QRectF KItemListViewLayouter::groupHeaderRect(int index) const int KItemListViewLayouter::itemColumn(int index) const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); if (index < 0 || index >= m_itemInfos.count()) { return -1; } - return (m_scrollOrientation == Qt::Vertical) - ? m_itemInfos[index].column - : m_itemInfos[index].row; + return (m_scrollOrientation == Qt::Vertical) ? m_itemInfos[index].column : m_itemInfos[index].row; } int KItemListViewLayouter::itemRow(int index) const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); if (index < 0 || index >= m_itemInfos.count()) { return -1; } - return (m_scrollOrientation == Qt::Vertical) - ? m_itemInfos[index].row - : m_itemInfos[index].column; + return (m_scrollOrientation == Qt::Vertical) ? m_itemInfos[index].row : m_itemInfos[index].column; } int KItemListViewLayouter::maximumVisibleItems() const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); const int height = static_cast(m_size.height()); const int rowHeight = static_cast(m_itemSize.height()); @@ -327,7 +322,7 @@ int KItemListViewLayouter::maximumVisibleItems() const bool KItemListViewLayouter::isFirstGroupItem(int itemIndex) const { - const_cast(this)->doLayout(); + const_cast(this)->doLayout(); return m_groupItemIndexes.contains(itemIndex); } @@ -336,18 +331,19 @@ void KItemListViewLayouter::markAsDirty() m_dirty = true; } - #ifndef QT_NO_DEBUG - bool KItemListViewLayouter::isDirty() - { - return m_dirty; - } +bool KItemListViewLayouter::isDirty() +{ + return m_dirty; +} #endif void KItemListViewLayouter::doLayout() { // we always want to update visible indexes after performing a layout - auto qsg = qScopeGuard([this] { updateVisibleIndexes(); }); + auto qsg = qScopeGuard([this] { + updateVisibleIndexes(); + }); if (!m_dirty) { return; @@ -409,14 +405,16 @@ void KItemListViewLayouter::doLayout() currentOffset += m_groupHeaderHeight; } - if (QGuiApplication::isLeftToRight()) for (int column = 0; column < m_columnCount; ++column) { - m_columnOffsets[column] = currentOffset; - currentOffset += m_columnWidth; - } - else for (int column = 0; column < m_columnCount; ++column) { - m_columnOffsets[column] = currentOffset - m_columnWidth; - currentOffset -= m_columnWidth; - } + if (QGuiApplication::isLeftToRight()) + for (int column = 0; column < m_columnCount; ++column) { + m_columnOffsets[column] = currentOffset; + currentOffset += m_columnWidth; + } + else + for (int column = 0; column < m_columnCount; ++column) { + m_columnOffsets[column] = currentOffset - m_columnWidth; + currentOffset -= m_columnWidth; + } // Prepare the QVector which stores the y-coordinate for each new row. int numberOfRows = (itemCount + m_columnCount - 1) / m_columnCount; @@ -467,7 +465,7 @@ void KItemListViewLayouter::doLayout() requiredItemHeight = sizeHintHeight; } - ItemInfo& itemInfo = m_itemInfos[index]; + ItemInfo &itemInfo = m_itemInfos[index]; itemInfo.column = column; itemInfo.row = row; @@ -598,7 +596,7 @@ bool KItemListViewLayouter::createGroupHeaders() m_groupItemIndexes.clear(); - const QList > groups = m_model->groups(); + const QList> groups = m_model->groups(); if (groups.isEmpty()) { return false; } @@ -615,4 +613,3 @@ qreal KItemListViewLayouter::minimumGroupHeaderWidth() const { return 100; } - diff --git a/src/kitemviews/private/kitemlistviewlayouter.h b/src/kitemviews/private/kitemlistviewlayouter.h index d5dc6dae1c..77d59c947e 100644 --- a/src/kitemviews/private/kitemlistviewlayouter.h +++ b/src/kitemviews/private/kitemlistviewlayouter.h @@ -37,22 +37,22 @@ class DOLPHIN_EXPORT KItemListViewLayouter : public QObject Q_OBJECT public: - explicit KItemListViewLayouter(KItemListSizeHintResolver* sizeHintResolver, QObject* parent = nullptr); + explicit KItemListViewLayouter(KItemListSizeHintResolver *sizeHintResolver, QObject *parent = nullptr); ~KItemListViewLayouter() override; void setScrollOrientation(Qt::Orientation orientation); Qt::Orientation scrollOrientation() const; - void setSize(const QSizeF& size); + void setSize(const QSizeF &size); QSizeF size() const; - void setItemSize(const QSizeF& size); + void setItemSize(const QSizeF &size); QSizeF itemSize() const; /** * Margin between the rows and columns of items. */ - void setItemMargin(const QSizeF& margin); + void setItemMargin(const QSizeF &margin); QSizeF itemMargin() const; /** @@ -87,8 +87,8 @@ public: qreal maximumItemOffset() const; - void setModel(const KItemModelBase* model); - const KItemModelBase* model() const; + void setModel(const KItemModelBase *model); + const KItemModelBase *model() const; /** * @return The first (at least partly) visible index. -1 is returned @@ -188,8 +188,8 @@ private: QSizeF m_itemSize; QSizeF m_itemMargin; qreal m_headerHeight; - const KItemModelBase* m_model; - KItemListSizeHintResolver* m_sizeHintResolver; + const KItemModelBase *m_model; + KItemListSizeHintResolver *m_sizeHintResolver; qreal m_scrollOffset; qreal m_maximumScrollOffset; @@ -223,5 +223,3 @@ private: }; #endif - - diff --git a/src/kitemviews/private/kpixmapmodifier.cpp b/src/kitemviews/private/kpixmapmodifier.cpp index 9f7f2edc82..bf316b880d 100644 --- a/src/kitemviews/private/kpixmapmodifier.cpp +++ b/src/kitemviews/private/kpixmapmodifier.cpp @@ -19,52 +19,32 @@ #include #include -static const quint32 stackBlur8Mul[255] = -{ - 512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512, - 454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512, - 482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456, - 437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512, - 497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328, - 320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456, - 446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335, - 329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512, - 505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405, - 399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328, - 324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271, - 268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456, - 451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388, - 385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335, - 332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292, - 289,287,285,282,280,278,275,273,271,269,267,265,263,261,259 -}; +static const quint32 stackBlur8Mul[255] = { + 512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312, + 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312, + 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278, + 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312, + 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399, + 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278, + 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408, + 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312, + 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259}; -static const quint32 stackBlur8Shr[255] = -{ - 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, - 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, - 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, - 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, - 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, - 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, - 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, - 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, - 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, - 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, - 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, - 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, - 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 -}; +static const quint32 stackBlur8Shr[255] = { + 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, + 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, + 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, + 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, + 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24}; -static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radius) +static void blurHorizontal(QImage &image, unsigned int *stack, int div, int radius) { int stackindex; int stackstart; - quint32 * const pixels = reinterpret_cast(image.bits()); + quint32 *const pixels = reinterpret_cast(image.bits()); quint32 pixel; int w = image.width(); @@ -77,8 +57,8 @@ static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radi unsigned int sum, sumIn, sumOut; for (int y = 0; y < h; y++) { - sum = 0; - sumIn = 0; + sum = 0; + sumIn = 0; sumOut = 0; const int yw = y * w; @@ -93,10 +73,10 @@ static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radi for (int i = 1; i <= radius; i++) { pixel = pixels[yw + qMin(i, wm)]; - unsigned int* stackpix = &stack[i + radius]; + unsigned int *stackpix = &stack[i + radius]; *stackpix = qAlpha(pixel); - sum += *stackpix * (radius + 1 - i); + sum += *stackpix * (radius + 1 - i); sumIn += *stackpix; } @@ -111,7 +91,7 @@ static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radi stackstart -= div; } - unsigned int* stackpix = &stack[stackstart]; + unsigned int *stackpix = &stack[stackstart]; sumOut -= *stackpix; @@ -120,7 +100,7 @@ static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radi *stackpix = qAlpha(pixel); sumIn += *stackpix; - sum += sumIn; + sum += sumIn; if (++stackindex >= div) { stackindex = 0; @@ -129,17 +109,17 @@ static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radi stackpix = &stack[stackindex]; sumOut += *stackpix; - sumIn -= *stackpix; + sumIn -= *stackpix; } } } -static void blurVertical(QImage& image, unsigned int* stack, int div, int radius) +static void blurVertical(QImage &image, unsigned int *stack, int div, int radius) { int stackindex; int stackstart; - quint32 * const pixels = reinterpret_cast(image.bits()); + quint32 *const pixels = reinterpret_cast(image.bits()); quint32 pixel; int w = image.width(); @@ -152,8 +132,8 @@ static void blurVertical(QImage& image, unsigned int* stack, int div, int radius unsigned int sum, sumIn, sumOut; for (int x = 0; x < w; x++) { - sum = 0; - sumIn = 0; + sum = 0; + sumIn = 0; sumOut = 0; pixel = pixels[x]; @@ -167,10 +147,10 @@ static void blurVertical(QImage& image, unsigned int* stack, int div, int radius for (int i = 1; i <= radius; i++) { pixel = pixels[qMin(i, hm) * w + x]; - unsigned int* stackpix = &stack[i + radius]; + unsigned int *stackpix = &stack[i + radius]; *stackpix = qAlpha(pixel); - sum += *stackpix * (radius + 1 - i); + sum += *stackpix * (radius + 1 - i); sumIn += *stackpix; } @@ -184,7 +164,7 @@ static void blurVertical(QImage& image, unsigned int* stack, int div, int radius if (stackstart >= div) stackstart -= div; - unsigned int* stackpix = &stack[stackstart]; + unsigned int *stackpix = &stack[stackstart]; sumOut -= *stackpix; @@ -193,7 +173,7 @@ static void blurVertical(QImage& image, unsigned int* stack, int div, int radius *stackpix = qAlpha(pixel); sumIn += *stackpix; - sum += sumIn; + sum += sumIn; if (++stackindex >= div) { stackindex = 0; @@ -202,25 +182,25 @@ static void blurVertical(QImage& image, unsigned int* stack, int div, int radius stackpix = &stack[stackindex]; sumOut += *stackpix; - sumIn -= *stackpix; + sumIn -= *stackpix; } } } -static void stackBlur(QImage& image, float radius) +static void stackBlur(QImage &image, float radius) { radius = qRound(radius); int div = int(radius * 2) + 1; - unsigned int* stack = new unsigned int[div]; + unsigned int *stack = new unsigned int[div]; blurHorizontal(image, stack, div, radius); blurVertical(image, stack, div, radius); - delete [] stack; + delete[] stack; } -static void shadowBlur(QImage& image, float radius, const QColor& color) +static void shadowBlur(QImage &image, float radius, const QColor &color) { if (radius < 0) { return; @@ -236,67 +216,65 @@ static void shadowBlur(QImage& image, float radius, const QColor& color) p.fillRect(image.rect(), color); } -namespace { - /** Helper class for drawing frames for KPixmapModifier::applyFrame(). */ - class TileSet +namespace +{ +/** Helper class for drawing frames for KPixmapModifier::applyFrame(). */ +class TileSet +{ +public: + enum { LeftMargin = 3, TopMargin = 2, RightMargin = 3, BottomMargin = 4 }; + + enum Tile { TopLeftCorner = 0, TopSide, TopRightCorner, LeftSide, RightSide, BottomLeftCorner, BottomSide, BottomRightCorner, NumTiles }; + + TileSet() { - public: - enum { LeftMargin = 3, TopMargin = 2, RightMargin = 3, BottomMargin = 4 }; + QImage image(8 * 3, 8 * 3, QImage::Format_ARGB32_Premultiplied); - enum Tile { TopLeftCorner = 0, TopSide, TopRightCorner, LeftSide, - RightSide, BottomLeftCorner, BottomSide, BottomRightCorner, - NumTiles }; + QPainter p(&image); + p.setCompositionMode(QPainter::CompositionMode_Source); + p.fillRect(image.rect(), Qt::transparent); + p.fillRect(image.rect().adjusted(3, 3, -3, -3), Qt::black); + p.end(); - TileSet() - { - QImage image(8 * 3, 8 * 3, QImage::Format_ARGB32_Premultiplied); + shadowBlur(image, 3, Qt::black); - QPainter p(&image); - p.setCompositionMode(QPainter::CompositionMode_Source); - p.fillRect(image.rect(), Qt::transparent); - p.fillRect(image.rect().adjusted(3, 3, -3, -3), Qt::black); - p.end(); + QPixmap pixmap = QPixmap::fromImage(image); + m_tiles[TopLeftCorner] = pixmap.copy(0, 0, 8, 8); + m_tiles[TopSide] = pixmap.copy(8, 0, 8, 8); + m_tiles[TopRightCorner] = pixmap.copy(16, 0, 8, 8); + m_tiles[LeftSide] = pixmap.copy(0, 8, 8, 8); + m_tiles[RightSide] = pixmap.copy(16, 8, 8, 8); + m_tiles[BottomLeftCorner] = pixmap.copy(0, 16, 8, 8); + m_tiles[BottomSide] = pixmap.copy(8, 16, 8, 8); + m_tiles[BottomRightCorner] = pixmap.copy(16, 16, 8, 8); + } - shadowBlur(image, 3, Qt::black); - - QPixmap pixmap = QPixmap::fromImage(image); - m_tiles[TopLeftCorner] = pixmap.copy(0, 0, 8, 8); - m_tiles[TopSide] = pixmap.copy(8, 0, 8, 8); - m_tiles[TopRightCorner] = pixmap.copy(16, 0, 8, 8); - m_tiles[LeftSide] = pixmap.copy(0, 8, 8, 8); - m_tiles[RightSide] = pixmap.copy(16, 8, 8, 8); - m_tiles[BottomLeftCorner] = pixmap.copy(0, 16, 8, 8); - m_tiles[BottomSide] = pixmap.copy(8, 16, 8, 8); - m_tiles[BottomRightCorner] = pixmap.copy(16, 16, 8, 8); + void paint(QPainter *p, const QRect &r) + { + p->drawPixmap(r.topLeft(), m_tiles[TopLeftCorner]); + if (r.width() - 16 > 0) { + p->drawTiledPixmap(r.x() + 8, r.y(), r.width() - 16, 8, m_tiles[TopSide]); } - - void paint(QPainter* p, const QRect& r) - { - p->drawPixmap(r.topLeft(), m_tiles[TopLeftCorner]); - if (r.width() - 16 > 0) { - p->drawTiledPixmap(r.x() + 8, r.y(), r.width() - 16, 8, m_tiles[TopSide]); - } - p->drawPixmap(r.right() - 8 + 1, r.y(), m_tiles[TopRightCorner]); - if (r.height() - 16 > 0) { - p->drawTiledPixmap(r.x(), r.y() + 8, 8, r.height() - 16, m_tiles[LeftSide]); - p->drawTiledPixmap(r.right() - 8 + 1, r.y() + 8, 8, r.height() - 16, m_tiles[RightSide]); - } - p->drawPixmap(r.x(), r.bottom() - 8 + 1, m_tiles[BottomLeftCorner]); - if (r.width() - 16 > 0) { - p->drawTiledPixmap(r.x() + 8, r.bottom() - 8 + 1, r.width() - 16, 8, m_tiles[BottomSide]); - } - p->drawPixmap(r.right() - 8 + 1, r.bottom() - 8 + 1, m_tiles[BottomRightCorner]); - - const QRect contentRect = r.adjusted(LeftMargin + 1, TopMargin + 1, - -(RightMargin + 1), -(BottomMargin + 1)); - p->fillRect(contentRect, Qt::transparent); + p->drawPixmap(r.right() - 8 + 1, r.y(), m_tiles[TopRightCorner]); + if (r.height() - 16 > 0) { + p->drawTiledPixmap(r.x(), r.y() + 8, 8, r.height() - 16, m_tiles[LeftSide]); + p->drawTiledPixmap(r.right() - 8 + 1, r.y() + 8, 8, r.height() - 16, m_tiles[RightSide]); } + p->drawPixmap(r.x(), r.bottom() - 8 + 1, m_tiles[BottomLeftCorner]); + if (r.width() - 16 > 0) { + p->drawTiledPixmap(r.x() + 8, r.bottom() - 8 + 1, r.width() - 16, 8, m_tiles[BottomSide]); + } + p->drawPixmap(r.right() - 8 + 1, r.bottom() - 8 + 1, m_tiles[BottomRightCorner]); - QPixmap m_tiles[NumTiles]; - }; + const QRect contentRect = r.adjusted(LeftMargin + 1, TopMargin + 1, -(RightMargin + 1), -(BottomMargin + 1)); + p->fillRect(contentRect, Qt::transparent); + } + + QPixmap m_tiles[NumTiles]; +}; } -void KPixmapModifier::scale(QPixmap& pixmap, const QSize& scaledSize) +void KPixmapModifier::scale(QPixmap &pixmap, const QSize &scaledSize) { if (scaledSize.isEmpty() || pixmap.isNull()) { pixmap = QPixmap(); @@ -307,7 +285,7 @@ void KPixmapModifier::scale(QPixmap& pixmap, const QSize& scaledSize) pixmap.setDevicePixelRatio(dpr); } -void KPixmapModifier::applyFrame(QPixmap& icon, const QSize& scaledSize) +void KPixmapModifier::applyFrame(QPixmap &icon, const QSize &scaledSize) { if (icon.isNull()) { icon = QPixmap(scaledSize); @@ -319,8 +297,7 @@ void KPixmapModifier::applyFrame(QPixmap& icon, const QSize& scaledSize) qreal dpr = qApp->devicePixelRatio(); // Resize the icon to the maximum size minus the space required for the frame - const QSize size(scaledSize.width() - TileSet::LeftMargin - TileSet::RightMargin, - scaledSize.height() - TileSet::TopMargin - TileSet::BottomMargin); + const QSize size(scaledSize.width() - TileSet::LeftMargin - TileSet::RightMargin, scaledSize.height() - TileSet::TopMargin - TileSet::BottomMargin); scale(icon, size * dpr); icon.setDevicePixelRatio(dpr); @@ -332,16 +309,14 @@ void KPixmapModifier::applyFrame(QPixmap& icon, const QSize& scaledSize) QPainter painter; painter.begin(&framedIcon); painter.setCompositionMode(QPainter::CompositionMode_Source); - tileSet.paint(&painter, QRect(QPoint(0,0), framedIcon.size() / dpr)); + tileSet.paint(&painter, QRect(QPoint(0, 0), framedIcon.size() / dpr)); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawPixmap(TileSet::LeftMargin, TileSet::TopMargin, icon); icon = framedIcon; } -QSize KPixmapModifier::sizeInsideFrame(const QSize& frameSize) +QSize KPixmapModifier::sizeInsideFrame(const QSize &frameSize) { - return QSize(frameSize.width() - TileSet::LeftMargin - TileSet::RightMargin, - frameSize.height() - TileSet::TopMargin - TileSet::BottomMargin); + return QSize(frameSize.width() - TileSet::LeftMargin - TileSet::RightMargin, frameSize.height() - TileSet::TopMargin - TileSet::BottomMargin); } - diff --git a/src/kitemviews/private/kpixmapmodifier.h b/src/kitemviews/private/kpixmapmodifier.h index d8d7f23941..0d86b01571 100644 --- a/src/kitemviews/private/kpixmapmodifier.h +++ b/src/kitemviews/private/kpixmapmodifier.h @@ -20,14 +20,14 @@ public: * @arg scaledSize is assumed to be the scaled to the same device pixel ratio as the source pixmap * @arg scaledSize is in device pixels */ - static void scale(QPixmap& pixmap, const QSize& scaledSize); + static void scale(QPixmap &pixmap, const QSize &scaledSize); /** * Resize and paint a frame round an icon * @arg scaledSize is in device-independent pixels * The returned image will be scaled by the application devicePixelRatio */ - static void applyFrame(QPixmap& icon, const QSize& scaledSize); + static void applyFrame(QPixmap &icon, const QSize &scaledSize); /** * return and paint a frame round an icon @@ -35,9 +35,7 @@ public: * @return is in device-independent pixels */ - static QSize sizeInsideFrame(const QSize& frameSize); + static QSize sizeInsideFrame(const QSize &frameSize); }; #endif - - diff --git a/src/main.cpp b/src/main.cpp index 611e3631cc..e1e559f976 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,23 +6,23 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ +#include "config-dolphin.h" #include "dbusinterface.h" #include "dolphin_generalsettings.h" #include "dolphin_version.h" #include "dolphindebug.h" #include "dolphinmainwindow.h" #include "global.h" -#include "config-dolphin.h" #if HAVE_KUSERFEEDBACK #include "userfeedback/dolphinfeedbackprovider.h" #endif #include +#include #include #include -#include -#include #include +#include #include #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) @@ -54,12 +54,10 @@ int main(int argc, char **argv) // Prohibit using sudo or kdesu (but allow using the root user directly) if (getuid() == 0) { if (!qEnvironmentVariableIsEmpty("SUDO_USER")) { - std::cout << "Running Dolphin with sudo can cause bugs and expose you to security vulnerabilities." - << std::endl; + std::cout << "Running Dolphin with sudo can cause bugs and expose you to security vulnerabilities." << std::endl; return EXIT_FAILURE; } else if (!qEnvironmentVariableIsEmpty("KDESU_USER")) { - std::cout << "Running Dolphin with kdesu can cause bugs and expose you to security vulnerabilities." - << std::endl; + std::cout << "Running Dolphin with kdesu can cause bugs and expose you to security vulnerabilities." << std::endl; return EXIT_FAILURE; } } @@ -88,7 +86,9 @@ int main(int argc, char **argv) KLocalizedString::setApplicationDomain("dolphin"); - KAboutData aboutData(QStringLiteral("dolphin"), i18n("Dolphin"), QStringLiteral(DOLPHIN_VERSION_STRING), + KAboutData aboutData(QStringLiteral("dolphin"), + i18n("Dolphin"), + QStringLiteral(DOLPHIN_VERSION_STRING), i18nc("@title", "File Manager"), KAboutLicense::GPL, i18nc("@info:credit", "(C) 2006-2022 The Dolphin Developers")); @@ -111,30 +111,14 @@ int main(int argc, char **argv) aboutData.addAuthor(i18nc("@info:credit", "Peter Penz"), i18nc("@info:credit", "Maintainer and developer (2006-2012)"), QStringLiteral("peter.penz19@gmail.com")); - aboutData.addAuthor(i18nc("@info:credit", "Sebastian Trüg"), - i18nc("@info:credit", "Developer"), - QStringLiteral("trueg@kde.org")); - aboutData.addAuthor(i18nc("@info:credit", "David Faure"), - i18nc("@info:credit", "Developer"), - QStringLiteral("faure@kde.org")); - aboutData.addAuthor(i18nc("@info:credit", "Aaron J. Seigo"), - i18nc("@info:credit", "Developer"), - QStringLiteral("aseigo@kde.org")); - aboutData.addAuthor(i18nc("@info:credit", "Rafael Fernández López"), - i18nc("@info:credit", "Developer"), - QStringLiteral("ereslibre@kde.org")); - aboutData.addAuthor(i18nc("@info:credit", "Kevin Ottens"), - i18nc("@info:credit", "Developer"), - QStringLiteral("ervin@kde.org")); - aboutData.addAuthor(i18nc("@info:credit", "Holger Freyther"), - i18nc("@info:credit", "Developer"), - QStringLiteral("freyther@gmx.net")); - aboutData.addAuthor(i18nc("@info:credit", "Max Blazejak"), - i18nc("@info:credit", "Developer"), - QStringLiteral("m43ksrocks@gmail.com")); - aboutData.addAuthor(i18nc("@info:credit", "Michael Austin"), - i18nc("@info:credit", "Documentation"), - QStringLiteral("tuxedup@users.sourceforge.net")); + aboutData.addAuthor(i18nc("@info:credit", "Sebastian Trüg"), i18nc("@info:credit", "Developer"), QStringLiteral("trueg@kde.org")); + aboutData.addAuthor(i18nc("@info:credit", "David Faure"), i18nc("@info:credit", "Developer"), QStringLiteral("faure@kde.org")); + aboutData.addAuthor(i18nc("@info:credit", "Aaron J. Seigo"), i18nc("@info:credit", "Developer"), QStringLiteral("aseigo@kde.org")); + aboutData.addAuthor(i18nc("@info:credit", "Rafael Fernández López"), i18nc("@info:credit", "Developer"), QStringLiteral("ereslibre@kde.org")); + aboutData.addAuthor(i18nc("@info:credit", "Kevin Ottens"), i18nc("@info:credit", "Developer"), QStringLiteral("ervin@kde.org")); + aboutData.addAuthor(i18nc("@info:credit", "Holger Freyther"), i18nc("@info:credit", "Developer"), QStringLiteral("freyther@gmx.net")); + aboutData.addAuthor(i18nc("@info:credit", "Max Blazejak"), i18nc("@info:credit", "Developer"), QStringLiteral("m43ksrocks@gmail.com")); + aboutData.addAuthor(i18nc("@info:credit", "Michael Austin"), i18nc("@info:credit", "Documentation"), QStringLiteral("tuxedup@users.sourceforge.net")); KAboutData::setApplicationData(aboutData); @@ -142,11 +126,14 @@ int main(int argc, char **argv) aboutData.setupCommandLine(&parser); // command line options - parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("select"), i18nc("@info:shell", "The files and folders passed as arguments " - "will be selected."))); + parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("select"), + i18nc("@info:shell", + "The files and folders passed as arguments " + "will be selected."))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("split"), i18nc("@info:shell", "Dolphin will get started with a split view."))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("new-window"), i18nc("@info:shell", "Dolphin will explicitly open in a new window."))); - parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("daemon"), i18nc("@info:shell", "Start Dolphin Daemon (only required for DBus Interface)."))); + parser.addOption( + QCommandLineOption(QStringList() << QStringLiteral("daemon"), i18nc("@info:shell", "Start Dolphin Daemon (only required for DBus Interface)."))); parser.addPositionalArgument(QStringLiteral("+[Url]"), i18nc("@info:shell", "Document to open")); parser.process(app); @@ -159,7 +146,6 @@ int main(int argc, char **argv) // We later mutate urls, so we need to store if it was empty originally const bool startedWithURLs = !urls.isEmpty(); - if (parser.isSet(QStringLiteral("daemon"))) { // Disable session management for the daemonized version // See https://bugs.kde.org/show_bug.cgi?id=417219 @@ -180,7 +166,6 @@ int main(int argc, char **argv) } if (!parser.isSet(QStringLiteral("new-window"))) { - QString token; if (KWindowSystem::isPlatformWayland()) { token = qEnvironmentVariable("XDG_ACTIVATION_TOKEN"); @@ -207,7 +192,7 @@ int main(int argc, char **argv) urls.append(urls.last()); } - DolphinMainWindow* mainWindow = new DolphinMainWindow(); + DolphinMainWindow *mainWindow = new DolphinMainWindow(); if (openFiles) { mainWindow->openFiles(urls, splitView); @@ -234,9 +219,7 @@ int main(int argc, char **argv) // 2. The "remember state" setting is enabled or session restoration after // reboot is in use // 3. There is a session available to restore - if (!parser.isSet(QStringLiteral("new-window")) - && (app.isSessionRestored() || GeneralSettings::rememberOpenedTabs()) - ) { + if (!parser.isSet(QStringLiteral("new-window")) && (app.isSessionRestored() || GeneralSettings::rememberOpenedTabs())) { // Get saved state data for the last-closed Dolphin instance const QString serviceName = QStringLiteral("org.kde.dolphin-%1").arg(QCoreApplication::applicationPid()); if (Dolphin::dolphinGuiInstances(serviceName).size() > 0) { diff --git a/src/middleclickactioneventfilter.cpp b/src/middleclickactioneventfilter.cpp index 6bb7020277..67bbd20f16 100644 --- a/src/middleclickactioneventfilter.cpp +++ b/src/middleclickactioneventfilter.cpp @@ -12,17 +12,16 @@ #include #include -MiddleClickActionEventFilter::MiddleClickActionEventFilter(QObject *parent) : QObject(parent) +MiddleClickActionEventFilter::MiddleClickActionEventFilter(QObject *parent) + : QObject(parent) { - } MiddleClickActionEventFilter::~MiddleClickActionEventFilter() = default; bool MiddleClickActionEventFilter::eventFilter(QObject *watched, QEvent *event) { - if (event->type() == QEvent::MouseButtonPress - || event->type() == QEvent::MouseButtonRelease) { + if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { QMouseEvent *me = static_cast(event); if (me->button() == Qt::MiddleButton) { diff --git a/src/middleclickactioneventfilter.h b/src/middleclickactioneventfilter.h index d5765a346f..6b873452e7 100644 --- a/src/middleclickactioneventfilter.h +++ b/src/middleclickactioneventfilter.h @@ -33,5 +33,4 @@ protected: private: QPointer m_lastMiddlePressedAction; - }; diff --git a/src/panels/folders/foldersitemlistwidget.cpp b/src/panels/folders/foldersitemlistwidget.cpp index 5d5fcbff68..1a3ba50efe 100644 --- a/src/panels/folders/foldersitemlistwidget.cpp +++ b/src/panels/folders/foldersitemlistwidget.cpp @@ -6,8 +6,8 @@ #include "foldersitemlistwidget.h" -FoldersItemListWidget::FoldersItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) : - KFileItemListWidget(informant, parent) +FoldersItemListWidget::FoldersItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent) + : KFileItemListWidget(informant, parent) { } @@ -19,4 +19,3 @@ QPalette::ColorRole FoldersItemListWidget::normalTextColorRole() const { return QPalette::WindowText; } - diff --git a/src/panels/folders/foldersitemlistwidget.h b/src/panels/folders/foldersitemlistwidget.h index 5e437cd95d..7c8eabf44a 100644 --- a/src/panels/folders/foldersitemlistwidget.h +++ b/src/panels/folders/foldersitemlistwidget.h @@ -17,7 +17,7 @@ class FoldersItemListWidget : public KFileItemListWidget Q_OBJECT public: - FoldersItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent); + FoldersItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent); ~FoldersItemListWidget() override; protected: @@ -25,5 +25,3 @@ protected: }; #endif - - diff --git a/src/panels/folders/folderspanel.cpp b/src/panels/folders/folderspanel.cpp index d9cc6128c4..9146920000 100644 --- a/src/panels/folders/folderspanel.cpp +++ b/src/panels/folders/folderspanel.cpp @@ -19,12 +19,12 @@ #include "treeviewcontextmenu.h" #include "views/draganddrophelper.h" -#include -#include #include #include #include #include +#include +#include #include #include @@ -33,11 +33,11 @@ #include #include -FoldersPanel::FoldersPanel(QWidget* parent) : - Panel(parent), - m_updateCurrentItem(false), - m_controller(nullptr), - m_model(nullptr) +FoldersPanel::FoldersPanel(QWidget *parent) + : Panel(parent) + , m_updateCurrentItem(false) + , m_controller(nullptr) + , m_model(nullptr) { setLayoutDirection(Qt::LeftToRight); } @@ -47,7 +47,7 @@ FoldersPanel::~FoldersPanel() FoldersPanelSettings::self()->save(); if (m_controller) { - KItemListView* view = m_controller->view(); + KItemListView *view = m_controller->view(); m_controller->setView(nullptr); delete view; } @@ -86,13 +86,13 @@ bool FoldersPanel::autoScrolling() const return FoldersPanelSettings::autoScrolling(); } -void FoldersPanel::rename(const KFileItem& item) +void FoldersPanel::rename(const KFileItem &item) { if (GeneralSettings::renameInline()) { const int index = m_model->index(item); m_controller->view()->editRole(index, "text"); } else { - KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(KFileItemList({item}), this); + KIO::RenameFileDialog *dialog = new KIO::RenameFileDialog(KFileItemList({item}), this); dialog->open(); } } @@ -119,8 +119,7 @@ void FoldersPanel::reloadTree() } } - -void FoldersPanel::showEvent(QShowEvent* event) +void FoldersPanel::showEvent(QShowEvent *event) { if (event->spontaneous()) { Panel::showEvent(event); @@ -131,7 +130,7 @@ void FoldersPanel::showEvent(QShowEvent* event) // Postpone the creating of the controller to the first show event. // This assures that no performance and memory overhead is given when the folders panel is not // used at all and stays invisible. - KFileItemListView* view = new KFileItemListView(); + KFileItemListView *view = new KFileItemListView(); view->setScanDirectories(false); view->setWidgetCreator(new KItemListWidgetCreator()); view->setSupportsItemExpanding(true); @@ -140,8 +139,7 @@ void FoldersPanel::showEvent(QShowEvent* event) // opening the folders panel. view->setOpacity(0); - connect(view, &KFileItemListView::roleEditingFinished, - this, &FoldersPanel::slotRoleEditingFinished); + connect(view, &KFileItemListView::roleEditingFinished, this, &FoldersPanel::slotRoleEditingFinished); m_model = new KFileItemModel(this); m_model->setShowDirectoriesOnly(true); @@ -163,10 +161,10 @@ void FoldersPanel::showEvent(QShowEvent* event) connect(m_controller, &KItemListController::viewContextMenuRequested, this, &FoldersPanel::slotViewContextMenuRequested); connect(m_controller, &KItemListController::itemDropEvent, this, &FoldersPanel::slotItemDropEvent); - KItemListContainer* container = new KItemListContainer(m_controller, this); + KItemListContainer *container = new KItemListContainer(m_controller, this); container->setEnabledFrame(false); - QVBoxLayout* layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(container); } @@ -175,7 +173,7 @@ void FoldersPanel::showEvent(QShowEvent* event) Panel::showEvent(event); } -void FoldersPanel::keyPressEvent(QKeyEvent* event) +void FoldersPanel::keyPressEvent(QKeyEvent *event) { const int key = event->key(); if ((key == Qt::Key_Enter) || (key == Qt::Key_Return)) { @@ -219,7 +217,7 @@ void FoldersPanel::slotItemMiddleClicked(int index) } } -void FoldersPanel::slotItemContextMenuRequested(int index, const QPointF& pos) +void FoldersPanel::slotItemContextMenuRequested(int index, const QPointF &pos) { const KFileItem fileItem = m_model->fileItem(index); @@ -230,7 +228,7 @@ void FoldersPanel::slotItemContextMenuRequested(int index, const QPointF& pos) } } -void FoldersPanel::slotViewContextMenuRequested(const QPointF& pos) +void FoldersPanel::slotViewContextMenuRequested(const QPointF &pos) { QPointer contextMenu = new TreeViewContextMenu(this, KFileItem()); contextMenu.data()->open(pos.toPoint()); @@ -239,7 +237,7 @@ void FoldersPanel::slotViewContextMenuRequested(const QPointF& pos) } } -void FoldersPanel::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event) +void FoldersPanel::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event) { if (index >= 0) { KFileItem destItem = m_model->fileItem(index); @@ -247,11 +245,7 @@ void FoldersPanel::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* eve return; } - QDropEvent dropEvent(event->pos().toPoint(), - event->possibleActions(), - event->mimeData(), - event->buttons(), - event->modifiers()); + QDropEvent dropEvent(event->pos().toPoint(), event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers()); KIO::DropJob *job = DragAndDropHelper::dropUrls(destItem.mostLocalUrl(), &dropEvent, this); if (job) { @@ -264,7 +258,7 @@ void FoldersPanel::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* eve } } -void FoldersPanel::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value) +void FoldersPanel::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value) { if (role == "text") { const KFileItem item = m_model->fileItem(index); @@ -275,7 +269,7 @@ void FoldersPanel::slotRoleEditingFinished(int index, const QByteArray& role, co QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename); newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName)); - KIO::Job* job = KIO::moveAs(oldUrl, newUrl); + KIO::Job *job = KIO::moveAs(oldUrl, newUrl); KJobWidgets::setWindow(job, this); KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job); job->uiDelegate()->setAutoErrorHandlingEnabled(true); @@ -306,7 +300,7 @@ void FoldersPanel::slotLoadingCompleted() void FoldersPanel::startFadeInAnimation() { - QPropertyAnimation* anim = new QPropertyAnimation(m_controller->view(), "opacity", this); + QPropertyAnimation *anim = new QPropertyAnimation(m_controller->view(), "opacity", this); anim->setStartValue(0); anim->setEndValue(1); anim->setEasingCurve(QEasingCurve::InOutQuad); @@ -314,7 +308,7 @@ void FoldersPanel::startFadeInAnimation() anim->setDuration(200); } -void FoldersPanel::loadTree(const QUrl& url, FoldersPanel::NavigationBehaviour navigationBehaviour) +void FoldersPanel::loadTree(const QUrl &url, FoldersPanel::NavigationBehaviour navigationBehaviour) { Q_ASSERT(m_controller); @@ -327,7 +321,7 @@ void FoldersPanel::loadTree(const QUrl& url, FoldersPanel::NavigationBehaviour n baseUrl = url; baseUrl.setPath(QStringLiteral("/")); } else if (Dolphin::homeUrl().isParentOf(url) || (Dolphin::homeUrl() == url)) { - if (FoldersPanelSettings::limitFoldersPanelToHome() ) { + if (FoldersPanelSettings::limitFoldersPanelToHome()) { baseUrl = Dolphin::homeUrl(); } else { // Use the root directory as base for local URLs (#150941) @@ -348,7 +342,7 @@ void FoldersPanel::loadTree(const QUrl& url, FoldersPanel::NavigationBehaviour n const int index = m_model->index(url); if (jumpHome) { - Q_EMIT folderActivated(baseUrl); + Q_EMIT folderActivated(baseUrl); } else if (index >= 0) { updateCurrentItem(index); } else if (url == baseUrl) { @@ -365,11 +359,10 @@ void FoldersPanel::loadTree(const QUrl& url, FoldersPanel::NavigationBehaviour n void FoldersPanel::updateCurrentItem(int index) { - KItemListSelectionManager* selectionManager = m_controller->selectionManager(); + KItemListSelectionManager *selectionManager = m_controller->selectionManager(); selectionManager->setCurrentItem(index); selectionManager->clearSelection(); selectionManager->setSelected(index); m_controller->view()->scrollToItem(index); } - diff --git a/src/panels/folders/folderspanel.h b/src/panels/folders/folderspanel.h index 3ce7870ffe..1a482436a8 100644 --- a/src/panels/folders/folderspanel.h +++ b/src/panels/folders/folderspanel.h @@ -27,7 +27,7 @@ class FoldersPanel : public Panel Q_OBJECT public: - explicit FoldersPanel(QWidget* parent = nullptr); + explicit FoldersPanel(QWidget *parent = nullptr); ~FoldersPanel() override; void setShowHiddenFiles(bool show); @@ -38,31 +38,31 @@ public: void setAutoScrolling(bool enable); bool autoScrolling() const; - void rename(const KFileItem& item); + void rename(const KFileItem &item); Q_SIGNALS: - void folderActivated(const QUrl& url); + void folderActivated(const QUrl &url); void folderInNewTab(const QUrl &url); void folderInNewActiveTab(const QUrl &url); - void errorMessage(const QString& error); + void errorMessage(const QString &error); protected: /** @see Panel::urlChanged() */ bool urlChanged() override; /** @see QWidget::showEvent() */ - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; /** @see QWidget::keyPressEvent() */ - void keyPressEvent(QKeyEvent* event) override; + void keyPressEvent(QKeyEvent *event) override; private Q_SLOTS: void slotItemActivated(int index); void slotItemMiddleClicked(int index); - void slotItemContextMenuRequested(int index, const QPointF& pos); - void slotViewContextMenuRequested(const QPointF& pos); - void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event); - void slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value); + void slotItemContextMenuRequested(int index, const QPointF &pos); + void slotViewContextMenuRequested(const QPointF &pos); + void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event); + void slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value); void slotLoadingCompleted(); @@ -72,14 +72,13 @@ private Q_SLOTS: */ void startFadeInAnimation(); - private: /** * Indicate if it is allowed to leave current location. */ enum NavigationBehaviour { - StayWhereYouAre, ///< Don't leave current location. - AllowJumpHome ///< Go Home only when context menu option got checked. + StayWhereYouAre, ///< Don't leave current location. + AllowJumpHome ///< Go Home only when context menu option got checked. }; /** * Initializes the base URL of the tree and expands all @@ -87,7 +86,7 @@ private: * @param url URL of the leaf directory that should get expanded. * @param navigationBehaviour Navigation behaviour \see NavigationBehaviour */ - void loadTree(const QUrl& url, NavigationBehaviour navigationBehaviour = StayWhereYouAre); + void loadTree(const QUrl &url, NavigationBehaviour navigationBehaviour = StayWhereYouAre); void reloadTree(); @@ -99,8 +98,8 @@ private: private: bool m_updateCurrentItem; - KItemListController* m_controller; - KFileItemModel* m_model; + KItemListController *m_controller; + KFileItemModel *m_model; }; #endif // FOLDERSPANEL_H diff --git a/src/panels/folders/treeviewcontextmenu.cpp b/src/panels/folders/treeviewcontextmenu.cpp index 893a494fb8..f6cafcac51 100644 --- a/src/panels/folders/treeviewcontextmenu.cpp +++ b/src/panels/folders/treeviewcontextmenu.cpp @@ -36,11 +36,10 @@ #include #include -TreeViewContextMenu::TreeViewContextMenu(FoldersPanel* parent, - const KFileItem& fileInfo) : - QObject(parent), - m_parent(parent), - m_fileItem(fileInfo) +TreeViewContextMenu::TreeViewContextMenu(FoldersPanel *parent, const KFileItem &fileInfo) + : QObject(parent) + , m_parent(parent) + , m_fileItem(fileInfo) { } @@ -48,25 +47,25 @@ TreeViewContextMenu::~TreeViewContextMenu() { } -void TreeViewContextMenu::open(const QPoint& pos) +void TreeViewContextMenu::open(const QPoint &pos) { - QMenu* popup = new QMenu(m_parent); + QMenu *popup = new QMenu(m_parent); if (!m_fileItem.isNull()) { KFileItemListProperties capabilities(KFileItemList() << m_fileItem); // insert 'Cut', 'Copy' and 'Paste' - QAction* cutAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-cut")), i18nc("@action:inmenu", "Cut"), this); + QAction *cutAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-cut")), i18nc("@action:inmenu", "Cut"), this); cutAction->setEnabled(capabilities.supportsMoving()); connect(cutAction, &QAction::triggered, this, &TreeViewContextMenu::cut); - QAction* copyAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18nc("@action:inmenu", "Copy"), this); + QAction *copyAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18nc("@action:inmenu", "Copy"), this); connect(copyAction, &QAction::triggered, this, &TreeViewContextMenu::copy); const QMimeData *mimeData = QApplication::clipboard()->mimeData(); bool canPaste; const QString text = KIO::pasteActionText(mimeData, &canPaste, m_fileItem); - QAction* pasteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this); + QAction *pasteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this); connect(pasteAction, &QAction::triggered, this, &TreeViewContextMenu::paste); pasteAction->setEnabled(canPaste); @@ -76,7 +75,7 @@ void TreeViewContextMenu::open(const QPoint& pos) popup->addSeparator(); // insert 'Rename' - QAction* renameAction = new QAction(i18nc("@action:inmenu", "Rename..."), this); + QAction *renameAction = new QAction(i18nc("@action:inmenu", "Rename..."), this); renameAction->setEnabled(capabilities.supportsMoving()); renameAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename"))); connect(renameAction, &QAction::triggered, this, &TreeViewContextMenu::rename); @@ -89,8 +88,7 @@ void TreeViewContextMenu::open(const QPoint& pos) const QUrl url = m_fileItem.url(); if (url.isLocalFile()) { - QAction* moveToTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("user-trash")), - i18nc("@action:inmenu", "Move to Trash"), this); + QAction *moveToTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("user-trash")), i18nc("@action:inmenu", "Move to Trash"), this); const bool enableMoveToTrash = capabilities.isLocal() && capabilities.supportsMoving(); moveToTrashAction->setEnabled(enableMoveToTrash); connect(moveToTrashAction, &QAction::triggered, this, &TreeViewContextMenu::moveToTrash); @@ -100,7 +98,7 @@ void TreeViewContextMenu::open(const QPoint& pos) } if (showDeleteCommand) { - QAction* deleteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18nc("@action:inmenu", "Delete"), this); + QAction *deleteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18nc("@action:inmenu", "Delete"), this); deleteAction->setEnabled(capabilities.supportsDeleting()); connect(deleteAction, &QAction::triggered, this, &TreeViewContextMenu::deleteItem); popup->addAction(deleteAction); @@ -110,7 +108,7 @@ void TreeViewContextMenu::open(const QPoint& pos) } // insert 'Show Hidden Files' - QAction* showHiddenFilesAction = new QAction(i18nc("@action:inmenu", "Show Hidden Files"), this); + QAction *showHiddenFilesAction = new QAction(i18nc("@action:inmenu", "Show Hidden Files"), this); showHiddenFilesAction->setCheckable(true); showHiddenFilesAction->setChecked(m_parent->showHiddenFiles()); popup->addAction(showHiddenFilesAction); @@ -120,7 +118,7 @@ void TreeViewContextMenu::open(const QPoint& pos) // insert 'Limit to Home Directory' const QUrl url = m_fileItem.url(); const bool enableLimitToHomeDirectory = url.isLocalFile(); - QAction* limitFoldersPanelToHomeAction = new QAction(i18nc("@action:inmenu", "Limit to Home Directory"), this); + QAction *limitFoldersPanelToHomeAction = new QAction(i18nc("@action:inmenu", "Limit to Home Directory"), this); limitFoldersPanelToHomeAction->setCheckable(true); limitFoldersPanelToHomeAction->setEnabled(enableLimitToHomeDirectory); limitFoldersPanelToHomeAction->setChecked(m_parent->limitFoldersPanelToHome()); @@ -129,7 +127,7 @@ void TreeViewContextMenu::open(const QPoint& pos) } // insert 'Automatic Scrolling' - QAction* autoScrollingAction = new QAction(i18nc("@action:inmenu", "Automatic Scrolling"), this); + QAction *autoScrollingAction = new QAction(i18nc("@action:inmenu", "Automatic Scrolling"), this); autoScrollingAction->setCheckable(true); autoScrollingAction->setChecked(m_parent->autoScrolling()); // TODO: Temporary disabled. Horizontal autoscrolling will be implemented later either @@ -139,16 +137,16 @@ void TreeViewContextMenu::open(const QPoint& pos) if (!m_fileItem.isNull()) { // insert 'Properties' entry - QAction* propertiesAction = new QAction(i18nc("@action:inmenu", "Properties"), this); + QAction *propertiesAction = new QAction(i18nc("@action:inmenu", "Properties"), this); propertiesAction->setIcon(QIcon::fromTheme(QStringLiteral("document-properties"))); connect(propertiesAction, &QAction::triggered, this, &TreeViewContextMenu::showProperties); popup->addAction(propertiesAction); } - const QList customActions = m_parent->customContextMenuActions(); + const QList customActions = m_parent->customContextMenuActions(); if (!customActions.isEmpty()) { popup->addSeparator(); - for (QAction* action : customActions) { + for (QAction *action : customActions) { popup->addAction(action); } } @@ -160,7 +158,7 @@ void TreeViewContextMenu::open(const QPoint& pos) } } -void TreeViewContextMenu::populateMimeData(QMimeData* mimeData, bool cut) +void TreeViewContextMenu::populateMimeData(QMimeData *mimeData, bool cut) { QList kdeUrls; kdeUrls.append(m_fileItem.url()); @@ -174,14 +172,14 @@ void TreeViewContextMenu::populateMimeData(QMimeData* mimeData, bool cut) void TreeViewContextMenu::cut() { - QMimeData* mimeData = new QMimeData(); + QMimeData *mimeData = new QMimeData(); populateMimeData(mimeData, true); QApplication::clipboard()->setMimeData(mimeData); } void TreeViewContextMenu::copy() { - QMimeData* mimeData = new QMimeData(); + QMimeData *mimeData = new QMimeData(); populateMimeData(mimeData, false); QApplication::clipboard()->setMimeData(mimeData); } @@ -208,7 +206,7 @@ void TreeViewContextMenu::moveToTrash() KIO::JobUiDelegate uiDelegate; uiDelegate.setWindow(m_parent); if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) { - KIO::Job* job = KIO::trash(list); + KIO::Job *job = KIO::trash(list); KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job); KJobWidgets::setWindow(job, m_parent); job->uiDelegate()->setAutoErrorHandlingEnabled(true); @@ -227,7 +225,7 @@ void TreeViewContextMenu::deleteItem() KIO::JobUiDelegate uiDelegate; uiDelegate.setWindow(m_parent); if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) { - KIO::Job* job = KIO::del(list); + KIO::Job *job = KIO::del(list); KJobWidgets::setWindow(job, m_parent); job->uiDelegate()->setAutoErrorHandlingEnabled(true); } @@ -236,7 +234,7 @@ void TreeViewContextMenu::deleteItem() void TreeViewContextMenu::showProperties() { - KPropertiesDialog* dialog = new KPropertiesDialog(m_fileItem.url(), m_parent); + KPropertiesDialog *dialog = new KPropertiesDialog(m_fileItem.url(), m_parent); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } @@ -255,4 +253,3 @@ void TreeViewContextMenu::setAutoScrolling(bool enable) { m_parent->setAutoScrolling(enable); } - diff --git a/src/panels/folders/treeviewcontextmenu.h b/src/panels/folders/treeviewcontextmenu.h index 35f44e90bf..2e9228b00f 100644 --- a/src/panels/folders/treeviewcontextmenu.h +++ b/src/panels/folders/treeviewcontextmenu.h @@ -30,13 +30,12 @@ public: * is applied. If 0 is passed, the context menu * is above the viewport. */ - TreeViewContextMenu(FoldersPanel* parent, - const KFileItem& fileInfo); + TreeViewContextMenu(FoldersPanel *parent, const KFileItem &fileInfo); ~TreeViewContextMenu() override; /** Opens the context menu modal. */ - void open(const QPoint& pos); + void open(const QPoint &pos); private Q_SLOTS: /** Cuts the item m_fileItem. */ @@ -79,10 +78,10 @@ private Q_SLOTS: void setAutoScrolling(bool enable); private: - void populateMimeData(QMimeData* mimeData, bool cut); + void populateMimeData(QMimeData *mimeData, bool cut); private: - FoldersPanel* m_parent; + FoldersPanel *m_parent; KFileItem m_fileItem; }; diff --git a/src/panels/information/informationpanel.cpp b/src/panels/information/informationpanel.cpp index 31617bb5ea..a0dff0d5e2 100644 --- a/src/panels/information/informationpanel.cpp +++ b/src/panels/information/informationpanel.cpp @@ -16,26 +16,26 @@ #include #include -#include -#include -#include #include +#include +#include +#include #include "dolphin_informationpanelsettings.h" -InformationPanel::InformationPanel(QWidget* parent) : - Panel(parent), - m_initialized(false), - m_infoTimer(nullptr), - m_urlChangedTimer(nullptr), - m_resetUrlTimer(nullptr), - m_shownUrl(), - m_urlCandidate(), - m_invalidUrlCandidate(), - m_hoveredItem(), - m_selection(), - m_folderStatJob(nullptr), - m_content(nullptr) +InformationPanel::InformationPanel(QWidget *parent) + : Panel(parent) + , m_initialized(false) + , m_infoTimer(nullptr) + , m_urlChangedTimer(nullptr) + , m_resetUrlTimer(nullptr) + , m_shownUrl() + , m_urlCandidate() + , m_invalidUrlCandidate() + , m_hoveredItem() + , m_selection() + , m_folderStatJob(nullptr) + , m_content(nullptr) { } @@ -43,7 +43,7 @@ InformationPanel::~InformationPanel() { } -void InformationPanel::setSelection(const KFileItemList& selection) +void InformationPanel::setSelection(const KFileItemList &selection) { m_selection = selection; @@ -66,7 +66,7 @@ void InformationPanel::setSelection(const KFileItemList& selection) } } -void InformationPanel::requestDelayedItemInfo(const KFileItem& item) +void InformationPanel::requestDelayedItemInfo(const KFileItem &item) { if (!isVisible()) { return; @@ -115,7 +115,7 @@ bool InformationPanel::urlChanged() return true; } -void InformationPanel::showEvent(QShowEvent* event) +void InformationPanel::showEvent(QShowEvent *event) { Panel::showEvent(event); if (!event->spontaneous()) { @@ -131,7 +131,7 @@ void InformationPanel::showEvent(QShowEvent* event) } } -void InformationPanel::resizeEvent(QResizeEvent* event) +void InformationPanel::resizeEvent(QResizeEvent *event) { if (isVisible()) { m_urlCandidate = m_shownUrl; @@ -140,7 +140,7 @@ void InformationPanel::resizeEvent(QResizeEvent* event) Panel::resizeEvent(event); } -void InformationPanel::contextMenuEvent(QContextMenuEvent* event) +void InformationPanel::contextMenuEvent(QContextMenuEvent *event) { showContextMenu(event->globalPos()); Panel::contextMenuEvent(event); @@ -150,23 +150,23 @@ void InformationPanel::showContextMenu(const QPoint &pos) { QMenu popup(this); - QAction* previewAction = popup.addAction(i18nc("@action:inmenu", "Preview")); + QAction *previewAction = popup.addAction(i18nc("@action:inmenu", "Preview")); previewAction->setIcon(QIcon::fromTheme(QStringLiteral("view-preview"))); previewAction->setCheckable(true); previewAction->setChecked(InformationPanelSettings::previewsShown()); - QAction* previewAutoPlayAction = popup.addAction(i18nc("@action:inmenu", "Auto-Play media files")); + QAction *previewAutoPlayAction = popup.addAction(i18nc("@action:inmenu", "Auto-Play media files")); previewAutoPlayAction->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start"))); previewAutoPlayAction->setCheckable(true); previewAutoPlayAction->setChecked(InformationPanelSettings::previewsAutoPlay()); - QAction* configureAction = popup.addAction(i18nc("@action:inmenu", "Configure...")); + QAction *configureAction = popup.addAction(i18nc("@action:inmenu", "Configure...")); configureAction->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); if (m_inConfigurationMode) { configureAction->setEnabled(false); } - QAction* dateformatAction = popup.addAction(i18nc("@action:inmenu", "Condensed Date")); + QAction *dateformatAction = popup.addAction(i18nc("@action:inmenu", "Condensed Date")); dateformatAction->setIcon(QIcon::fromTheme(QStringLiteral("change-date-symbolic"))); dateformatAction->setCheckable(true); dateformatAction->setChecked(InformationPanelSettings::dateFormat() == static_cast(Baloo::DateFormats::ShortFormat)); @@ -179,7 +179,7 @@ void InformationPanel::showContextMenu(const QPoint &pos) // Open the popup and adjust the settings for the // selected action. - QAction* action = popup.exec(pos); + QAction *action = popup.exec(pos); if (!action) { return; } @@ -238,15 +238,14 @@ void InformationPanel::showItemInfo() if (m_folderStatJob->uiDelegate()) { KJobWidgets::setWindow(m_folderStatJob, this); } - connect(m_folderStatJob, &KIO::Job::result, - this, &InformationPanel::slotFolderStatFinished); + connect(m_folderStatJob, &KIO::Job::result, this, &InformationPanel::slotFolderStatFinished); } } -void InformationPanel::slotFolderStatFinished(KJob* job) +void InformationPanel::slotFolderStatFinished(KJob *job) { m_folderStatJob = nullptr; - const KIO::UDSEntry entry = static_cast(job)->statResult(); + const KIO::UDSEntry entry = static_cast(job)->statResult(); m_content->showItem(KFileItem(entry, m_shownUrl)); } @@ -270,7 +269,7 @@ void InformationPanel::reset() } } -void InformationPanel::slotFileRenamed(const QString& source, const QString& dest) +void InformationPanel::slotFileRenamed(const QString &source, const QString &dest) { auto sourceUrl = QUrl::fromUserInput(source); if (m_shownUrl == sourceUrl) { @@ -290,7 +289,7 @@ void InformationPanel::slotFileRenamed(const QString& source, const QString& des } } -void InformationPanel::slotFilesAdded(const QString& directory) +void InformationPanel::slotFilesAdded(const QString &directory) { if (m_shownUrl == QUrl::fromUserInput(directory)) { // If the 'trash' icon changes because the trash has been emptied or got filled, @@ -307,9 +306,9 @@ void InformationPanel::slotFilesItemChanged(const KFileItemList &changedFileItem } } -void InformationPanel::slotFilesChanged(const QStringList& files) +void InformationPanel::slotFilesChanged(const QStringList &files) { - for (const QString& fileName : files) { + for (const QString &fileName : files) { if (m_shownUrl == QUrl::fromUserInput(fileName)) { showItemInfo(); break; @@ -317,9 +316,9 @@ void InformationPanel::slotFilesChanged(const QStringList& files) } } -void InformationPanel::slotFilesRemoved(const QStringList& files) +void InformationPanel::slotFilesRemoved(const QStringList &files) { - for (const QString& fileName : files) { + for (const QString &fileName : files) { if (m_shownUrl == QUrl::fromUserInput(fileName)) { // the currently shown item has been removed, show // the parent directory as fallback @@ -329,12 +328,12 @@ void InformationPanel::slotFilesRemoved(const QStringList& files) } } -void InformationPanel::slotEnteredDirectory(const QString& directory) +void InformationPanel::slotEnteredDirectory(const QString &directory) { Q_UNUSED(directory) } -void InformationPanel::slotLeftDirectory(const QString& directory) +void InformationPanel::slotLeftDirectory(const QString &directory) { if (m_shownUrl == QUrl::fromUserInput(directory)) { // The signal 'leftDirectory' is also emitted when a media @@ -360,7 +359,7 @@ void InformationPanel::cancelRequest() m_urlCandidate.clear(); } -bool InformationPanel::isEqualToShownUrl(const QUrl& url) const +bool InformationPanel::isEqualToShownUrl(const QUrl &url) const { return m_shownUrl.matches(url, QUrl::StripTrailingSlash); } @@ -376,26 +375,22 @@ void InformationPanel::init() m_infoTimer = new QTimer(this); m_infoTimer->setInterval(300); m_infoTimer->setSingleShot(true); - connect(m_infoTimer, &QTimer::timeout, - this, &InformationPanel::slotInfoTimeout); + connect(m_infoTimer, &QTimer::timeout, this, &InformationPanel::slotInfoTimeout); m_urlChangedTimer = new QTimer(this); m_urlChangedTimer->setInterval(200); m_urlChangedTimer->setSingleShot(true); - connect(m_urlChangedTimer, &QTimer::timeout, - this, &InformationPanel::showItemInfo); + connect(m_urlChangedTimer, &QTimer::timeout, this, &InformationPanel::showItemInfo); m_resetUrlTimer = new QTimer(this); m_resetUrlTimer->setInterval(1000); m_resetUrlTimer->setSingleShot(true); - connect(m_resetUrlTimer, &QTimer::timeout, - this, &InformationPanel::reset); + connect(m_resetUrlTimer, &QTimer::timeout, this, &InformationPanel::reset); Q_ASSERT(m_urlChangedTimer->interval() < m_infoTimer->interval()); Q_ASSERT(m_urlChangedTimer->interval() < m_resetUrlTimer->interval()); - org::kde::KDirNotify* dirNotify = new org::kde::KDirNotify(QString(), QString(), - QDBusConnection::sessionBus(), this); + org::kde::KDirNotify *dirNotify = new org::kde::KDirNotify(QString(), QString(), QDBusConnection::sessionBus(), this); connect(dirNotify, &OrgKdeKDirNotifyInterface::FileRenamed, this, &InformationPanel::slotFileRenamed); connect(dirNotify, &OrgKdeKDirNotifyInterface::FilesAdded, this, &InformationPanel::slotFilesAdded); connect(dirNotify, &OrgKdeKDirNotifyInterface::FilesChanged, this, &InformationPanel::slotFilesChanged); @@ -405,13 +400,14 @@ void InformationPanel::init() m_content = new InformationPanelContent(this); connect(m_content, &InformationPanelContent::urlActivated, this, &InformationPanel::urlActivated); - connect(m_content, &InformationPanelContent::configurationFinished, this, [this]() { m_inConfigurationMode = false; }); + connect(m_content, &InformationPanelContent::configurationFinished, this, [this]() { + m_inConfigurationMode = false; + }); connect(m_content, &InformationPanelContent::contextMenuRequested, this, &InformationPanel::showContextMenu); - QVBoxLayout* layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(m_content); m_initialized = true; } - diff --git a/src/panels/information/informationpanel.h b/src/panels/information/informationpanel.h index b150948cad..ee405cb391 100644 --- a/src/panels/information/informationpanel.h +++ b/src/panels/information/informationpanel.h @@ -14,7 +14,7 @@ class InformationPanelContent; namespace KIO { - class Job; +class Job; } /** @@ -25,18 +25,18 @@ class InformationPanel : public Panel Q_OBJECT public: - explicit InformationPanel(QWidget* parent = nullptr); + explicit InformationPanel(QWidget *parent = nullptr); ~InformationPanel() override; Q_SIGNALS: - void urlActivated(const QUrl& url); + void urlActivated(const QUrl &url); public Q_SLOTS: /** * This is invoked to inform the panel that the user has selected a new * set of items. */ - void setSelection(const KFileItemList& selection); + void setSelection(const KFileItemList &selection); /** * Does a delayed request of information for the item \a item. @@ -44,7 +44,7 @@ public Q_SLOTS: * are invoked, then the request will be skipped. Requesting a delayed item information * makes sense when hovering items. */ - void requestDelayedItemInfo(const KFileItem& item); + void requestDelayedItemInfo(const KFileItem &item); void slotFilesItemChanged(const KFileItemList &changedFileItems); @@ -53,13 +53,13 @@ protected: bool urlChanged() override; /** @see QWidget::showEvent() */ - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; /** @see QWidget::resizeEvent() */ - void resizeEvent(QResizeEvent* event) override; + void resizeEvent(QResizeEvent *event) override; /** @see QWidget::contextMenuEvent() */ - void contextMenuEvent(QContextMenuEvent* event) override; + void contextMenuEvent(QContextMenuEvent *event) override; private Q_SLOTS: /** @@ -72,7 +72,7 @@ private Q_SLOTS: * Shows the information for the currently displayed folder as a result from * a stat job issued in showItemInfo(). */ - void slotFolderStatFinished(KJob* job); + void slotFolderStatFinished(KJob *job); /** * Triggered if the request for item information has timed out. @@ -87,12 +87,12 @@ private Q_SLOTS: */ void reset(); - void slotFileRenamed(const QString& source, const QString& dest); - void slotFilesAdded(const QString& directory); - void slotFilesChanged(const QStringList& files); - void slotFilesRemoved(const QStringList& files); - void slotEnteredDirectory(const QString& directory); - void slotLeftDirectory(const QString& directory); + void slotFileRenamed(const QString &source, const QString &dest); + void slotFilesAdded(const QString &directory); + void slotFilesChanged(const QStringList &files); + void slotFilesRemoved(const QStringList &files); + void slotEnteredDirectory(const QString &directory); + void slotLeftDirectory(const QString &directory); private: /** Assures that any pending item information request is cancelled. */ @@ -101,7 +101,7 @@ private: /** * Returns true, if \a url is equal to the shown URL m_shownUrl. */ - bool isEqualToShownUrl(const QUrl& url) const; + bool isEqualToShownUrl(const QUrl &url) const; /** * Marks the URL as invalid and will reset the Information Panel @@ -121,9 +121,9 @@ private: private: bool m_initialized; - QTimer* m_infoTimer; - QTimer* m_urlChangedTimer; - QTimer* m_resetUrlTimer; + QTimer *m_infoTimer; + QTimer *m_urlChangedTimer; + QTimer *m_resetUrlTimer; // URL that is currently shown in the Information Panel. QUrl m_shownUrl; @@ -141,9 +141,9 @@ private: KFileItem m_hoveredItem; KFileItemList m_selection; - KIO::Job* m_folderStatJob; + KIO::Job *m_folderStatJob; - InformationPanelContent* m_content; + InformationPanelContent *m_content; bool m_inConfigurationMode = false; }; diff --git a/src/panels/information/informationpanelcontent.cpp b/src/panels/information/informationpanelcontent.cpp index f1379f9619..725ef785ba 100644 --- a/src/panels/information/informationpanelcontent.cpp +++ b/src/panels/information/informationpanelcontent.cpp @@ -6,8 +6,8 @@ #include "informationpanelcontent.h" -#include #include +#include #include #include #include @@ -45,17 +45,17 @@ const int PLAY_ARROW_SIZE = 24; const int PLAY_ARROW_BORDER_SIZE = 2; -InformationPanelContent::InformationPanelContent(QWidget* parent) : - QWidget(parent), - m_item(), - m_previewJob(nullptr), - m_outdatedPreviewTimer(nullptr), - m_preview(nullptr), - m_phononWidget(nullptr), - m_nameLabel(nullptr), - m_metaDataWidget(nullptr), - m_metaDataArea(nullptr), - m_isVideo(false) +InformationPanelContent::InformationPanelContent(QWidget *parent) + : QWidget(parent) + , m_item() + , m_previewJob(nullptr) + , m_outdatedPreviewTimer(nullptr) + , m_preview(nullptr) + , m_phononWidget(nullptr) + , m_nameLabel(nullptr) + , m_metaDataWidget(nullptr) + , m_metaDataArea(nullptr) + , m_isVideo(false) { parent->installEventFilter(this); @@ -65,10 +65,9 @@ InformationPanelContent::InformationPanelContent(QWidget* parent) : m_outdatedPreviewTimer = new QTimer(this); m_outdatedPreviewTimer->setInterval(100); m_outdatedPreviewTimer->setSingleShot(true); - connect(m_outdatedPreviewTimer, &QTimer::timeout, - this, &InformationPanelContent::markOutdatedPreview); + connect(m_outdatedPreviewTimer, &QTimer::timeout, this, &InformationPanelContent::markOutdatedPreview); - QVBoxLayout* layout = new QVBoxLayout(this); + QVBoxLayout *layout = new QVBoxLayout(this); // preview const int minPreviewWidth = KIconLoader::SizeEnormous + KIconLoader::SizeMedium; @@ -81,8 +80,7 @@ InformationPanelContent::InformationPanelContent(QWidget* parent) : m_phononWidget->hide(); m_phononWidget->setMinimumWidth(minPreviewWidth); m_phononWidget->setAutoPlay(InformationPanelSettings::previewsAutoPlay()); - connect(m_phononWidget, &PhononWidget::hasVideoChanged, - this, &InformationPanelContent::slotHasVideoChanged); + connect(m_phononWidget, &PhononWidget::hasVideoChanged, this, &InformationPanelContent::slotHasVideoChanged); // name m_nameLabel = new QLabel(parent); @@ -99,40 +97,36 @@ InformationPanelContent::InformationPanelContent(QWidget* parent) : m_metaDataWidget = new Baloo::FileMetaDataWidget(parent); m_metaDataWidget->setDateFormat(static_cast(InformationPanelSettings::dateFormat())); - connect(m_metaDataWidget, &Baloo::FileMetaDataWidget::urlActivated, - this, &InformationPanelContent::urlActivated); + connect(m_metaDataWidget, &Baloo::FileMetaDataWidget::urlActivated, this, &InformationPanelContent::urlActivated); m_metaDataWidget->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont)); m_metaDataWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); // Configuration - m_configureLabel = new QLabel(i18nc("@label::textbox", - "Select which data should be shown:"), this); + m_configureLabel = new QLabel(i18nc("@label::textbox", "Select which data should be shown:"), this); m_configureLabel->setWordWrap(true); m_configureLabel->setVisible(false); m_configureButtons = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel); m_configureButtons->setVisible(false); connect(m_configureButtons, &QDialogButtonBox::accepted, this, [this]() { - m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Accept); - m_configureButtons->setVisible(false); - m_configureLabel->setVisible(false); - Q_EMIT configurationFinished(); - } - ); + m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Accept); + m_configureButtons->setVisible(false); + m_configureLabel->setVisible(false); + Q_EMIT configurationFinished(); + }); connect(m_configureButtons, &QDialogButtonBox::rejected, this, [this]() { - m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Cancel); - m_configureButtons->setVisible(false); - m_configureLabel->setVisible(false); - Q_EMIT configurationFinished(); - } - ); + m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Cancel); + m_configureButtons->setVisible(false); + m_configureLabel->setVisible(false); + Q_EMIT configurationFinished(); + }); m_metaDataArea = new QScrollArea(parent); m_metaDataArea->setWidget(m_metaDataWidget); m_metaDataArea->setWidgetResizable(true); m_metaDataArea->setFrameShape(QFrame::NoFrame); - QWidget* viewport = m_metaDataArea->viewport(); + QWidget *viewport = m_metaDataArea->viewport(); QScroller::grabGesture(viewport, QScroller::TouchGesture); viewport->installEventFilter(this); @@ -152,7 +146,7 @@ InformationPanelContent::~InformationPanelContent() InformationPanelSettings::self()->save(); } -void InformationPanelContent::showItem(const KFileItem& item) +void InformationPanelContent::showItem(const KFileItem &item) { // compares item entries, comparing items only compares urls if (m_item.entry() != item.entry()) { @@ -181,19 +175,15 @@ void InformationPanelContent::refreshPixmapView() const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings"); const QStringList plugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins()); - m_previewJob = new KIO::PreviewJob(KFileItemList() << m_item, - QSize(m_preview->width(), m_preview->height()), - &plugins); + m_previewJob = new KIO::PreviewJob(KFileItemList() << m_item, QSize(m_preview->width(), m_preview->height()), &plugins); m_previewJob->setScaleType(KIO::PreviewJob::Unscaled); m_previewJob->setIgnoreMaximumSize(m_item.isLocalFile() && !m_item.isSlow()); if (m_previewJob->uiDelegate()) { KJobWidgets::setWindow(m_previewJob, this); } - connect(m_previewJob.data(), &KIO::PreviewJob::gotPreview, - this, &InformationPanelContent::showPreview); - connect(m_previewJob.data(), &KIO::PreviewJob::failed, - this, &InformationPanelContent::showIcon); + connect(m_previewJob.data(), &KIO::PreviewJob::gotPreview, this, &InformationPanelContent::showPreview); + connect(m_previewJob.data(), &KIO::PreviewJob::failed, this, &InformationPanelContent::showIcon); } void InformationPanelContent::refreshPreview() @@ -207,7 +197,6 @@ void InformationPanelContent::refreshPreview() m_preview->setCursor(Qt::ArrowCursor); setNameLabelText(m_item.text()); if (InformationPanelSettings::previewsShown()) { - const QUrl itemUrl = m_item.url(); const bool isSearchUrl = itemUrl.scheme().contains(QLatin1String("search")) && m_item.localPath().isEmpty(); if (isSearchUrl) { @@ -216,11 +205,8 @@ void InformationPanelContent::refreshPreview() // in the case of a search-URL the URL is not readable for humans // (at least not useful to show in the Information Panel) - m_preview->setPixmap( - QIcon::fromTheme(QStringLiteral("baloo")).pixmap(m_preview->height(), m_preview->width()) - ); + m_preview->setPixmap(QIcon::fromTheme(QStringLiteral("baloo")).pixmap(m_preview->height(), m_preview->width())); } else { - refreshPixmapView(); const QString mimeType = m_item.mimetype(); @@ -238,12 +224,9 @@ void InformationPanelContent::refreshPreview() // we don't need to update the preview/phonon widget states // unless the previewed file has changed, // or the setting previewshown has changed - if ((m_phononWidget->state() != Phonon::State::PlayingState && - m_phononWidget->state() != Phonon::State::PausedState && - m_phononWidget->state() != Phonon::State::StoppedState) || - m_item.targetUrl() != m_phononWidget->url() || - (!m_preview->isVisible() &&! m_phononWidget->isVisible())) { - + if ((m_phononWidget->state() != Phonon::State::PlayingState && m_phononWidget->state() != Phonon::State::PausedState + && m_phononWidget->state() != Phonon::State::StoppedState) + || m_item.targetUrl() != m_phononWidget->url() || (!m_preview->isVisible() && !m_phononWidget->isVisible())) { if (InformationPanelSettings::previewsAutoPlay() && m_isVideo) { // hides the preview now to avoid flickering when the autoplay video starts m_preview->hide(); @@ -287,7 +270,7 @@ void InformationPanelContent::refreshMetaData() m_metaDataWidget->setItems(KFileItemList() << m_item); } -void InformationPanelContent::showItems(const KFileItemList& items) +void InformationPanelContent::showItems(const KFileItemList &items) { // If there is a preview job, kill it to prevent that we have jobs for // multiple items running, and thus a race condition (bug 250787). @@ -297,9 +280,7 @@ void InformationPanelContent::showItems(const KFileItemList& items) m_preview->stopAnimatedImage(); - m_preview->setPixmap( - QIcon::fromTheme(QStringLiteral("dialog-information")).pixmap(m_preview->height(), m_preview->width()) - ); + m_preview->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-information")).pixmap(m_preview->height(), m_preview->width())); setNameLabelText(i18ncp("@label", "%1 item selected", "%1 items selected", items.count())); m_metaDataWidget->setItems(items); @@ -309,11 +290,11 @@ void InformationPanelContent::showItems(const KFileItemList& items) m_item = KFileItem(); } -bool InformationPanelContent::eventFilter(QObject* obj, QEvent* event) +bool InformationPanelContent::eventFilter(QObject *obj, QEvent *event) { switch (event->type()) { case QEvent::Resize: { - QResizeEvent* resizeEvent = static_cast(event); + QResizeEvent *resizeEvent = static_cast(event); if (obj == m_metaDataArea->viewport()) { // The size of the meta text area has changed. Adjust the fixed // width in a way that no horizontal scrollbar needs to be shown. @@ -339,22 +320,22 @@ bool InformationPanelContent::eventFilter(QObject* obj, QEvent* event) return QWidget::eventFilter(obj, event); } -bool InformationPanelContent::event(QEvent* event) +bool InformationPanelContent::event(QEvent *event) { if (event->type() == QEvent::Gesture) { - gestureEvent(static_cast(event)); + gestureEvent(static_cast(event)); return true; } return QWidget::event(event); } -bool InformationPanelContent::gestureEvent(QGestureEvent* event) +bool InformationPanelContent::gestureEvent(QGestureEvent *event) { if (!underMouse()) { return false; } - QTapAndHoldGesture* tap = static_cast(event->gesture(Qt::TapAndHoldGesture)); + QTapAndHoldGesture *tap = static_cast(event->gesture(Qt::TapAndHoldGesture)); if (tap) { if (tap->state() == Qt::GestureFinished) { @@ -366,7 +347,7 @@ bool InformationPanelContent::gestureEvent(QGestureEvent* event) return false; } -void InformationPanelContent::showIcon(const KFileItem& item) +void InformationPanelContent::showIcon(const KFileItem &item) { m_outdatedPreviewTimer->stop(); QPixmap pixmap = QIcon::fromTheme(item.iconName()).pixmap(m_preview->height(), m_preview->width()); @@ -374,8 +355,7 @@ void InformationPanelContent::showIcon(const KFileItem& item) m_preview->setPixmap(pixmap); } -void InformationPanelContent::showPreview(const KFileItem& item, - const QPixmap& pixmap) +void InformationPanelContent::showPreview(const KFileItem &item, const QPixmap &pixmap) { m_outdatedPreviewTimer->stop(); @@ -400,8 +380,7 @@ void InformationPanelContent::showPreview(const KFileItem& item, QPainterPath path; path.addPolygon(arrow); - QLinearGradient gradient(QPointF(zeroX, zeroY + arrowSize / 2), - QPointF(zeroX + arrowSize, zeroY + arrowSize / 2)); + QLinearGradient gradient(QPointF(zeroX, zeroY + arrowSize / 2), QPointF(zeroX + arrowSize, zeroY + arrowSize / 2)); QColor whiteColor = Qt::white; QColor blackColor = Qt::black; @@ -432,9 +411,7 @@ void InformationPanelContent::markOutdatedPreview() showIcon(m_item); } else { KIconEffect *iconEffect = KIconLoader::global()->iconEffect(); - QPixmap disabledPixmap = iconEffect->apply(m_preview->pixmap(), - KIconLoader::Desktop, - KIconLoader::DisabledState); + QPixmap disabledPixmap = iconEffect->apply(m_preview->pixmap(), KIconLoader::Desktop, KIconLoader::DisabledState); m_preview->setPixmap(disabledPixmap); } } @@ -454,11 +431,12 @@ void InformationPanelContent::slotHasVideoChanged(bool hasVideo) } } -void InformationPanelContent::setPreviewAutoPlay(bool autoPlay) { +void InformationPanelContent::setPreviewAutoPlay(bool autoPlay) +{ m_phononWidget->setAutoPlay(autoPlay); } -void InformationPanelContent::setNameLabelText(const QString& text) +void InformationPanelContent::setNameLabelText(const QString &text) { QTextOption textOption; textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); @@ -511,4 +489,3 @@ void InformationPanelContent::adjustWidgetSizes(int width) m_phononWidget->setVideoSize(QSize(maxWidth, maxWidth)); } } - diff --git a/src/panels/information/informationpanelcontent.h b/src/panels/information/informationpanelcontent.h index b2007b0aac..0ea05d9903 100644 --- a/src/panels/information/informationpanelcontent.h +++ b/src/panels/information/informationpanelcontent.h @@ -7,8 +7,8 @@ #ifndef INFORMATIONPANELCONTENT_H #define INFORMATIONPANELCONTENT_H -#include #include "config-dolphin.h" +#include #include #include @@ -24,12 +24,14 @@ class QLabel; class QScrollArea; class QGestureEvent; -namespace KIO { - class PreviewJob; +namespace KIO +{ +class PreviewJob; } -namespace Baloo { - class FileMetaDataWidget; +namespace Baloo +{ +class FileMetaDataWidget; } /** @@ -41,7 +43,7 @@ class InformationPanelContent : public QWidget Q_OBJECT public: - explicit InformationPanelContent(QWidget* parent = nullptr); + explicit InformationPanelContent(QWidget *parent = nullptr); ~InformationPanelContent() override; /** @@ -49,12 +51,12 @@ public: * The preview of the item is generated asynchronously, * the other meta information are fetched synchronously. */ - void showItem(const KFileItem& item); + void showItem(const KFileItem &item); /** * Shows the meta information for the items \p items and its preview */ - void showItems(const KFileItemList& items); + void showItems(const KFileItemList &items); KFileItemList items(); @@ -76,9 +78,9 @@ public: void setPreviewAutoPlay(bool autoPlay); Q_SIGNALS: - void urlActivated( const QUrl& url ); + void urlActivated(const QUrl &url); void configurationFinished(); - void contextMenuRequested(const QPoint& pos); + void contextMenuRequested(const QPoint &pos); public Q_SLOTS: /** @@ -89,22 +91,22 @@ public Q_SLOTS: protected: /** @see QObject::eventFilter() */ - bool eventFilter(QObject* obj, QEvent* event) override; + bool eventFilter(QObject *obj, QEvent *event) override; - bool event(QEvent * event) override; + bool event(QEvent *event) override; private Q_SLOTS: /** * Is invoked if no preview is available for the item. In this * case the icon will be shown. */ - void showIcon(const KFileItem& item); + void showIcon(const KFileItem &item); /** * Is invoked if a preview is available for the item. The preview * \a pixmap is shown inside the info page. */ - void showPreview(const KFileItem& item, const QPixmap& pixmap); + void showPreview(const KFileItem &item, const QPixmap &pixmap); /** * Marks the currently shown preview as outdated @@ -121,7 +123,7 @@ private: * label width (QLabel::setWordWrap() does not work if the * text represents one extremely long word). */ - void setNameLabelText(const QString& text); + void setNameLabelText(const QString &text); /** * Adjusts the sizes of the widgets dependent on the available @@ -134,21 +136,21 @@ private: */ void refreshPixmapView(); - bool gestureEvent(QGestureEvent* event); + bool gestureEvent(QGestureEvent *event); private: KFileItem m_item; QPointer m_previewJob; - QTimer* m_outdatedPreviewTimer; + QTimer *m_outdatedPreviewTimer; - PixmapViewer* m_preview; - PhononWidget* m_phononWidget; - QLabel* m_nameLabel; - Baloo::FileMetaDataWidget* m_metaDataWidget; - QScrollArea* m_metaDataArea; - QLabel* m_configureLabel; - QDialogButtonBox* m_configureButtons; + PixmapViewer *m_preview; + PhononWidget *m_phononWidget; + QLabel *m_nameLabel; + Baloo::FileMetaDataWidget *m_metaDataWidget; + QScrollArea *m_metaDataArea; + QLabel *m_configureLabel; + QDialogButtonBox *m_configureButtons; bool m_isVideo; }; diff --git a/src/panels/information/phononwidget.cpp b/src/panels/information/phononwidget.cpp index c9ccaa86ce..2993e826e8 100644 --- a/src/panels/information/phononwidget.cpp +++ b/src/panels/information/phononwidget.cpp @@ -21,37 +21,37 @@ class EmbeddedVideoPlayer : public Phonon::VideoWidget { Q_OBJECT - public: - EmbeddedVideoPlayer(QWidget *parent = nullptr) : - Phonon::VideoWidget(parent) - { - } +public: + EmbeddedVideoPlayer(QWidget *parent = nullptr) + : Phonon::VideoWidget(parent) + { + } - void setSizeHint(const QSize& size) - { - m_sizeHint = size; - updateGeometry(); - } + void setSizeHint(const QSize &size) + { + m_sizeHint = size; + updateGeometry(); + } - QSize sizeHint() const override - { - return m_sizeHint.isValid() ? m_sizeHint : Phonon::VideoWidget::sizeHint(); - } + QSize sizeHint() const override + { + return m_sizeHint.isValid() ? m_sizeHint : Phonon::VideoWidget::sizeHint(); + } - private: - QSize m_sizeHint; +private: + QSize m_sizeHint; }; PhononWidget::PhononWidget(QWidget *parent) - : QWidget(parent), - m_url(), - m_playButton(nullptr), - m_pauseButton(nullptr), - m_topLayout(nullptr), - m_media(nullptr), - m_seekSlider(nullptr), - m_audioOutput(nullptr), - m_videoPlayer(nullptr) + : QWidget(parent) + , m_url() + , m_playButton(nullptr) + , m_pauseButton(nullptr) + , m_topLayout(nullptr) + , m_media(nullptr) + , m_seekSlider(nullptr) + , m_audioOutput(nullptr) + , m_videoPlayer(nullptr) { } @@ -99,7 +99,7 @@ bool PhononWidget::eventFilter(QObject *object, QEvent *event) { Q_UNUSED(object) if (event->type() == QEvent::MouseButtonPress) { - const QMouseEvent *mouseEvent = static_cast(event); + const QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::LeftButton) { // toggle playback togglePlayback(); @@ -109,7 +109,7 @@ bool PhononWidget::eventFilter(QObject *object, QEvent *event) return false; } -void PhononWidget::setVideoSize(const QSize& size) +void PhononWidget::setVideoSize(const QSize &size) { if (m_videoSize != size) { m_videoSize = size; @@ -201,10 +201,8 @@ void PhononWidget::play() { if (!m_media) { m_media = new Phonon::MediaObject(this); - connect(m_media, &Phonon::MediaObject::stateChanged, - this, &PhononWidget::stateChanged); - connect(m_media, &Phonon::MediaObject::finished, - this, &PhononWidget::finished); + connect(m_media, &Phonon::MediaObject::stateChanged, this, &PhononWidget::stateChanged); + connect(m_media, &Phonon::MediaObject::finished, this, &PhononWidget::finished); m_seekSlider->setMediaObject(m_media); } diff --git a/src/panels/information/phononwidget.h b/src/panels/information/phononwidget.h index 5510b05442..4662e47af3 100644 --- a/src/panels/information/phononwidget.h +++ b/src/panels/information/phononwidget.h @@ -15,10 +15,10 @@ namespace Phonon { - class AudioOutput; - class MediaObject; - class SeekSlider; - class VideoPlayer; +class AudioOutput; +class MediaObject; +class SeekSlider; +class VideoPlayer; } // namespace Phonon class EmbeddedVideoPlayer; @@ -28,68 +28,64 @@ class QVBoxLayout; class PhononWidget : public QWidget { Q_OBJECT - public: +public: + enum MediaKind { Video, Audio }; - enum MediaKind { - Video, - Audio - }; + explicit PhononWidget(QWidget *parent = nullptr); - explicit PhononWidget(QWidget *parent = nullptr); + void setUrl(const QUrl &url, MediaKind kind); + QUrl url() const; + void clearUrl(); - void setUrl(const QUrl &url, MediaKind kind); - QUrl url() const; - void clearUrl(); + void setVideoSize(const QSize &size); + QSize videoSize() const; + Phonon::State state() const; - void setVideoSize(const QSize& size); - QSize videoSize() const; - Phonon::State state() const; + void setAutoPlay(bool autoPlay); + bool eventFilter(QObject *object, QEvent *event) override; - void setAutoPlay(bool autoPlay); - bool eventFilter(QObject *object, QEvent *event) override; +Q_SIGNALS: + /** + * Is emitted whenever the video-state + * has changed: If true is returned, a video + * including control-buttons will be shown. + * If false is returned, no video is shown + * and the control-buttons are available for + * audio only. + */ + void hasVideoChanged(bool hasVideo); - Q_SIGNALS: - /** - * Is emitted whenever the video-state - * has changed: If true is returned, a video - * including control-buttons will be shown. - * If false is returned, no video is shown - * and the control-buttons are available for - * audio only. - */ - void hasVideoChanged(bool hasVideo); +public Q_SLOTS: + void play(); - public Q_SLOTS: - void play(); +protected: + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; - protected: - void showEvent(QShowEvent *event) override; - void hideEvent(QHideEvent *event) override; +private Q_SLOTS: + void stateChanged(Phonon::State newstate); + void stop(); + void finished(); - private Q_SLOTS: - void stateChanged(Phonon::State newstate); - void stop(); - void finished(); +private: + void applyVideoSize(); - private: - void applyVideoSize(); +private: + void togglePlayback(); - private: - void togglePlayback(); + QUrl m_url; + QSize m_videoSize; - QUrl m_url; - QSize m_videoSize; + QToolButton *m_playButton; + QToolButton *m_pauseButton; - QToolButton *m_playButton; - QToolButton *m_pauseButton; - - QVBoxLayout *m_topLayout; - Phonon::MediaObject *m_media; - Phonon::SeekSlider *m_seekSlider; - Phonon::AudioOutput *m_audioOutput; - EmbeddedVideoPlayer *m_videoPlayer; - bool m_autoPlay; - bool m_isVideo; + QVBoxLayout *m_topLayout; + Phonon::MediaObject *m_media; + Phonon::SeekSlider *m_seekSlider; + Phonon::AudioOutput *m_audioOutput; + EmbeddedVideoPlayer *m_videoPlayer; + bool m_autoPlay; + bool m_isVideo; }; #endif // PHONONWIDGET_H diff --git a/src/panels/information/pixmapviewer.cpp b/src/panels/information/pixmapviewer.cpp index 1f072641e5..7eca876c8b 100644 --- a/src/panels/information/pixmapviewer.cpp +++ b/src/panels/information/pixmapviewer.cpp @@ -13,13 +13,13 @@ #include #include -PixmapViewer::PixmapViewer(QWidget* parent, Transition transition) : - QWidget(parent), - m_animatedImage(nullptr), - m_transition(transition), - m_animationStep(0), - m_sizeHint(), - m_hasAnimatedImage(false) +PixmapViewer::PixmapViewer(QWidget *parent, Transition transition) + : QWidget(parent) + , m_animatedImage(nullptr) + , m_transition(transition) + , m_animationStep(0) + , m_sizeHint() + , m_hasAnimatedImage(false) { setMinimumWidth(KIconLoader::SizeEnormous); setMinimumHeight(KIconLoader::SizeEnormous); @@ -37,7 +37,7 @@ PixmapViewer::~PixmapViewer() { } -void PixmapViewer::setPixmap(const QPixmap& pixmap) +void PixmapViewer::setPixmap(const QPixmap &pixmap) { if (pixmap.isNull()) { return; @@ -61,8 +61,7 @@ void PixmapViewer::setPixmap(const QPixmap& pixmap) m_pixmap = pixmap; update(); - const bool animateTransition = (m_transition != NoTransition) && - (m_pixmap.size() != m_oldPixmap.size()); + const bool animateTransition = (m_transition != NoTransition) && (m_pixmap.size() != m_oldPixmap.size()); if (animateTransition) { m_animation.start(); } else if (m_hasAnimatedImage) { @@ -75,7 +74,7 @@ void PixmapViewer::setPixmap(const QPixmap& pixmap) } } -void PixmapViewer::setSizeHint(const QSize& size) +void PixmapViewer::setSizeHint(const QSize &size) { if (m_animatedImage && size != m_sizeHint) { m_animatedImage->stop(); @@ -105,7 +104,6 @@ void PixmapViewer::setAnimatedImageFileName(const QString &fileName) m_hasAnimatedImage = m_animatedImage->isValid() && (m_animatedImage->frameCount() > 1); } - QString PixmapViewer::animatedImageFileName() const { if (!m_hasAnimatedImage) { @@ -114,7 +112,7 @@ QString PixmapViewer::animatedImageFileName() const return m_animatedImage->fileName(); } -void PixmapViewer::paintEvent(QPaintEvent* event) +void PixmapViewer::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); @@ -122,17 +120,13 @@ void PixmapViewer::paintEvent(QPaintEvent* event) if (m_transition != NoTransition || (m_hasAnimatedImage && m_animatedImage->state() != QMovie::Running)) { const float value = m_animation.currentValue(); - const int scaledWidth = static_cast((m_oldPixmap.width() * (1.0 - value)) + (m_pixmap.width() * value)); + const int scaledWidth = static_cast((m_oldPixmap.width() * (1.0 - value)) + (m_pixmap.width() * value)); const int scaledHeight = static_cast((m_oldPixmap.height() * (1.0 - value)) + (m_pixmap.height() * value)); - const bool useOldPixmap = (m_transition == SizeTransition) && - (m_oldPixmap.width() > m_pixmap.width()); - const QPixmap& largePixmap = useOldPixmap ? m_oldPixmap : m_pixmap; + const bool useOldPixmap = (m_transition == SizeTransition) && (m_oldPixmap.width() > m_pixmap.width()); + const QPixmap &largePixmap = useOldPixmap ? m_oldPixmap : m_pixmap; if (!largePixmap.isNull()) { - const QPixmap scaledPixmap = largePixmap.scaled(scaledWidth, - scaledHeight, - Qt::IgnoreAspectRatio, - Qt::FastTransformation); + const QPixmap scaledPixmap = largePixmap.scaled(scaledWidth, scaledHeight, Qt::IgnoreAspectRatio, Qt::FastTransformation); style()->drawItemPixmap(&painter, rect(), Qt::AlignCenter, scaledPixmap); } @@ -159,7 +153,7 @@ void PixmapViewer::checkPendingPixmaps() void PixmapViewer::updateAnimatedImageFrame() { - Q_ASSERT (m_animatedImage); + Q_ASSERT(m_animatedImage); m_pixmap = m_animatedImage->currentPixmap(); update(); @@ -176,6 +170,7 @@ void PixmapViewer::stopAnimatedImage() bool PixmapViewer::isAnimatedMimeType(const QString &mimeType) { const QList imageFormats = QImageReader::imageFormatsForMimeType(mimeType.toUtf8()); - return std::any_of(imageFormats.begin(), imageFormats.end(), - [](const QByteArray &format){ return QMovie::supportedFormats().contains(format); }); + return std::any_of(imageFormats.begin(), imageFormats.end(), [](const QByteArray &format) { + return QMovie::supportedFormats().contains(format); + }); } diff --git a/src/panels/information/pixmapviewer.h b/src/panels/information/pixmapviewer.h index 6e0fa3e676..32c06fe15d 100644 --- a/src/panels/information/pixmapviewer.h +++ b/src/panels/information/pixmapviewer.h @@ -26,8 +26,7 @@ class PixmapViewer : public QWidget Q_OBJECT public: - enum Transition - { + enum Transition { /** No transition is done when the pixmap is changed. */ NoTransition, @@ -47,21 +46,20 @@ public: SizeTransition }; - explicit PixmapViewer(QWidget* parent, - Transition transition = DefaultTransition); + explicit PixmapViewer(QWidget *parent, Transition transition = DefaultTransition); ~PixmapViewer() override; - void setPixmap(const QPixmap& pixmap); + void setPixmap(const QPixmap &pixmap); QPixmap pixmap() const; /** * Sets the size hint to \a size and triggers a relayout * of the parent widget. Per default no size hint is given. */ - void setSizeHint(const QSize& size); + void setSizeHint(const QSize &size); QSize sizeHint() const override; - void setAnimatedImageFileName(const QString& fileName); + void setAnimatedImageFileName(const QString &fileName); QString animatedImageFileName() const; void stopAnimatedImage(); @@ -72,7 +70,7 @@ public: static bool isAnimatedMimeType(const QString &mimeType); protected: - void paintEvent(QPaintEvent* event) override; + void paintEvent(QPaintEvent *event) override; private Q_SLOTS: void checkPendingPixmaps(); @@ -81,7 +79,7 @@ private Q_SLOTS: private: QPixmap m_pixmap; QPixmap m_oldPixmap; - QMovie* m_animatedImage; + QMovie *m_animatedImage; QQueue m_pendingPixmaps; QTimeLine m_animation; Transition m_transition; @@ -95,5 +93,4 @@ inline QPixmap PixmapViewer::pixmap() const return m_pixmap; } - #endif diff --git a/src/panels/panel.cpp b/src/panels/panel.cpp index 9e62cc8e35..32f293c4ca 100644 --- a/src/panels/panel.cpp +++ b/src/panels/panel.cpp @@ -7,10 +7,10 @@ #include "panel.h" -Panel::Panel(QWidget* parent) : - QWidget(parent), - m_url(), - m_customContextMenuActions() +Panel::Panel(QWidget *parent) + : QWidget(parent) + , m_url() + , m_customContextMenuActions() { } @@ -23,12 +23,12 @@ QUrl Panel::url() const return m_url; } -void Panel::setCustomContextMenuActions(const QList& actions) +void Panel::setCustomContextMenuActions(const QList &actions) { m_customContextMenuActions = actions; } -QList Panel::customContextMenuActions() const +QList Panel::customContextMenuActions() const { return m_customContextMenuActions; } @@ -43,7 +43,7 @@ QSize Panel::sizeHint() const return QSize(180, 180); } -void Panel::setUrl(const QUrl& url) +void Panel::setUrl(const QUrl &url) { if (url.matches(m_url, QUrl::StripTrailingSlash)) { return; @@ -58,6 +58,4 @@ void Panel::setUrl(const QUrl& url) void Panel::readSettings() { - } - diff --git a/src/panels/panel.h b/src/panels/panel.h index 5932ae6af5..5f1fabb4a7 100644 --- a/src/panels/panel.h +++ b/src/panels/panel.h @@ -22,7 +22,7 @@ class Panel : public QWidget Q_OBJECT public: - explicit Panel(QWidget* parent = nullptr); + explicit Panel(QWidget *parent = nullptr); ~Panel() override; /** Returns the current set URL of the active Dolphin view. */ @@ -33,8 +33,8 @@ public: * context menu actions. Allows an application to apply custom actions to * the panel. */ - void setCustomContextMenuActions(const QList& actions); - QList customContextMenuActions() const; + void setCustomContextMenuActions(const QList &actions); + QList customContextMenuActions() const; QSize sizeHint() const override; @@ -62,7 +62,7 @@ protected: private: QUrl m_url; - QList m_customContextMenuActions; + QList m_customContextMenuActions; }; #endif // PANEL_H diff --git a/src/panels/places/placespanel.cpp b/src/panels/places/placespanel.cpp index de71377476..6467f9c230 100644 --- a/src/panels/places/placespanel.cpp +++ b/src/panels/places/placespanel.cpp @@ -11,12 +11,12 @@ #include "placespanel.h" -#include "dolphinplacesmodelsingleton.h" #include "dolphin_generalsettings.h" #include "dolphin_placespanelsettings.h" +#include "dolphinplacesmodelsingleton.h" #include "global.h" -#include "views/draganddrophelper.h" #include "settings/dolphinsettingsdialog.h" +#include "views/draganddrophelper.h" #include #include @@ -31,12 +31,11 @@ #include -PlacesPanel::PlacesPanel(QWidget* parent) +PlacesPanel::PlacesPanel(QWidget *parent) : KFilePlacesView(parent) { setDropOnPlaceEnabled(true); - connect(this, &PlacesPanel::urlsDropped, - this, &PlacesPanel::slotUrlsDropped); + connect(this, &PlacesPanel::urlsDropped, this, &PlacesPanel::slotUrlsDropped); setAutoResizeItemsEnabled(false); @@ -57,7 +56,7 @@ PlacesPanel::PlacesPanel(QWidget* parent) // Don't store 0 size, let's keep -1 for default/small/automatic iconSize = -1; } - PlacesPanelSettings* settings = PlacesPanelSettings::self(); + PlacesPanelSettings *settings = PlacesPanelSettings::self(); settings->setIconSize(iconSize); settings->save(); }); @@ -73,7 +72,7 @@ void PlacesPanel::setUrl(const QUrl &url) KFilePlacesView::setUrl(url); } -QList PlacesPanel::customContextMenuActions() const +QList PlacesPanel::customContextMenuActions() const { return m_customContextMenuActions; } @@ -105,7 +104,7 @@ void PlacesPanel::readSettings() setIconSize(QSize(iconSize, iconSize)); } -void PlacesPanel::showEvent(QShowEvent* event) +void PlacesPanel::showEvent(QShowEvent *event) { if (!event->spontaneous() && !model()) { readSettings(); @@ -163,13 +162,13 @@ void PlacesPanel::slotConfigureTrash() { const QUrl url = currentIndex().data(KFilePlacesModel::UrlRole).toUrl(); - DolphinSettingsDialog* settingsDialog = new DolphinSettingsDialog(url, this); + DolphinSettingsDialog *settingsDialog = new DolphinSettingsDialog(url, this); settingsDialog->setCurrentPage(settingsDialog->trashSettings); settingsDialog->setAttribute(Qt::WA_DeleteOnClose); settingsDialog->show(); } -void PlacesPanel::slotUrlsDropped(const QUrl& dest, QDropEvent* event, QWidget* parent) +void PlacesPanel::slotUrlsDropped(const QUrl &dest, QDropEvent *event, QWidget *parent) { KIO::DropJob *job = DragAndDropHelper::dropUrls(dest, event, parent); if (job) { @@ -225,7 +224,7 @@ void PlacesPanel::slotTearDownRequested(const QModelIndex &index) void PlacesPanel::slotTearDownRequestedExternally(const QString &udi) { Q_UNUSED(udi); - auto *storageAccess = static_cast(sender()); + auto *storageAccess = static_cast(sender()); Q_EMIT storageTearDownExternallyRequested(storageAccess->filePath()); } diff --git a/src/panels/places/placespanel.h b/src/panels/places/placespanel.h index ef213ab300..2eb3094831 100644 --- a/src/panels/places/placespanel.h +++ b/src/panels/places/placespanel.h @@ -11,8 +11,8 @@ #include "panels/panel.h" -#include #include +#include #include // Solid::ErrorType @@ -30,15 +30,15 @@ class PlacesPanel : public KFilePlacesView Q_OBJECT public: - explicit PlacesPanel(QWidget* parent); + explicit PlacesPanel(QWidget *parent); ~PlacesPanel() override; void setUrl(const QUrl &url); // override // for compatibility with Panel, actions that are shown // on the view's context menu - QList customContextMenuActions() const; - void setCustomContextMenuActions(const QList& actions); + QList customContextMenuActions() const; + void setCustomContextMenuActions(const QList &actions); void requestTearDown(); void proceedWithTearDown(); @@ -47,18 +47,18 @@ public Q_SLOTS: void readSettings(); Q_SIGNALS: - void errorMessage(const QString& error); - void storageTearDownRequested(const QString& mountPath); - void storageTearDownExternallyRequested(const QString& mountPath); + void errorMessage(const QString &error); + void storageTearDownRequested(const QString &mountPath); + void storageTearDownExternallyRequested(const QString &mountPath); void storageTearDownSuccessful(); protected: - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; private Q_SLOTS: void slotConfigureTrash(); - void slotUrlsDropped(const QUrl& dest, QDropEvent* event, QWidget* parent); + void slotUrlsDropped(const QUrl &dest, QDropEvent *event, QWidget *parent); void slotContextMenuAboutToShow(const QModelIndex &index, QMenu *menu); void slotTearDownRequested(const QModelIndex &index); void slotTearDownRequestedExternally(const QString &udi); @@ -70,7 +70,7 @@ private: void connectDeviceSignals(const QModelIndex &idx); QUrl m_url; // only used for initial setUrl - QList m_customContextMenuActions; + QList m_customContextMenuActions; QPersistentModelIndex m_indexToTearDown; diff --git a/src/panels/terminal/terminalpanel.cpp b/src/panels/terminal/terminalpanel.cpp index a9c61768b0..53464e620a 100644 --- a/src/panels/terminal/terminalpanel.cpp +++ b/src/panels/terminal/terminalpanel.cpp @@ -28,20 +28,18 @@ #include #include -TerminalPanel::TerminalPanel(QWidget* parent) : - Panel(parent), - m_clearTerminal(true), - m_mostLocalUrlJob(nullptr), - m_layout(nullptr), - m_terminal(nullptr), - m_terminalWidget(nullptr), - m_konsolePartMissingMessage(nullptr), - m_konsolePart(nullptr), - m_konsolePartCurrentDirectory(), - m_sendCdToTerminalHistory(), - m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"), - QStringLiteral("/org/kde/KIOFuse"), - QDBusConnection::sessionBus()) +TerminalPanel::TerminalPanel(QWidget *parent) + : Panel(parent) + , m_clearTerminal(true) + , m_mostLocalUrlJob(nullptr) + , m_layout(nullptr) + , m_terminal(nullptr) + , m_terminalWidget(nullptr) + , m_konsolePartMissingMessage(nullptr) + , m_konsolePart(nullptr) + , m_konsolePartCurrentDirectory() + , m_sendCdToTerminalHistory() + , m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"), QStringLiteral("/org/kde/KIOFuse"), QDBusConnection::sessionBus()) { m_layout = new QVBoxLayout(this); m_layout->setContentsMargins(0, 0, 0, 0); @@ -72,8 +70,7 @@ void TerminalPanel::terminalExited() bool TerminalPanel::isHiddenInVisibleWindow() const { - return parentWidget() - && parentWidget()->isHidden(); + return parentWidget() && parentWidget()->isHidden(); } void TerminalPanel::dockVisibilityChanged() @@ -82,8 +79,7 @@ void TerminalPanel::dockVisibilityChanged() // respond when e.g. Dolphin is minimized. if (isHiddenInVisibleWindow() && m_terminal && !hasProgramRunning()) { // Make sure that the following "cd /" command will not affect the view. - disconnect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), - this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString))); + disconnect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString))); // Make sure this terminal does not prevent unmounting any removable drives changeDir(QUrl::fromLocalFile(QStringLiteral("/"))); @@ -135,7 +131,7 @@ bool TerminalPanel::urlChanged() return true; } -void TerminalPanel::showEvent(QShowEvent* event) +void TerminalPanel::showEvent(QShowEvent *event) { if (event->spontaneous()) { Panel::showEvent(event); @@ -154,7 +150,7 @@ void TerminalPanel::showEvent(QShowEvent* event) if (m_konsolePartMissingMessage) { m_layout->removeWidget(m_konsolePartMissingMessage); } - m_terminal = qobject_cast(m_konsolePart); + m_terminal = qobject_cast(m_konsolePart); // needed to collect the correct KonsolePart actionCollection // namely the one of the single inner terminal and not the outer KonsolePart @@ -174,8 +170,9 @@ void TerminalPanel::showEvent(QShowEvent* event) } else if (!m_konsolePartMissingMessage) { const auto konsoleInstallUrl = QUrl("appstream://org.kde.konsole.desktop"); - const auto konsoleNotInstalledText = i18n("Terminal cannot be shown because Konsole is not installed. " - "Please install it and then reopen the panel."); + const auto konsoleNotInstalledText = i18n( + "Terminal cannot be shown because Konsole is not installed. " + "Please install it and then reopen the panel."); m_konsolePartMissingMessage = new KMessageWidget(konsoleNotInstalledText, this); m_konsolePartMissingMessage->setCloseButtonVisible(false); m_konsolePartMissingMessage->hide(); @@ -195,18 +192,17 @@ void TerminalPanel::showEvent(QShowEvent* event) } if (m_terminal) { m_terminal->showShellInDir(url().toLocalFile()); - if(!hasProgramRunning()) { + if (!hasProgramRunning()) { changeDir(url()); } m_terminalWidget->setFocus(); - connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), - this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString))); + connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString))); } Panel::showEvent(event); } -void TerminalPanel::changeDir(const QUrl& url) +void TerminalPanel::changeDir(const QUrl &url) { delete m_mostLocalUrlJob; m_mostLocalUrlJob = nullptr; @@ -230,9 +226,9 @@ void TerminalPanel::changeDir(const QUrl& url) sendCdToTerminalKIOFuse(url); } -void TerminalPanel::sendCdToTerminal(const QString& dir, HistoryPolicy addToHistory) +void TerminalPanel::sendCdToTerminal(const QString &dir, HistoryPolicy addToHistory) { - if (dir == m_konsolePartCurrentDirectory // We are already there + if (dir == m_konsolePartCurrentDirectory // We are already there && m_sendCdToTerminalHistory.isEmpty() // …and that is not because the terminal couldn't keep up ) { m_clearTerminal = false; @@ -259,13 +255,14 @@ void TerminalPanel::sendCdToTerminal(const QString& dir, HistoryPolicy addToHist } } -void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) { +void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) +{ // URL isn't local, only hope for the terminal to be in sync with the // DolphinView is to mount the remote URL in KIOFuse and point to it. // If we can't do that for any reason, silently fail. auto reply = m_kiofuseInterface.mountUrl(url.toString()); - QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) { + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); + QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) { watcher->deleteLater(); if (!reply.isError()) { // Successfully mounted, point to the KIOFuse equivalent path. @@ -274,9 +271,9 @@ void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) { }); } -void TerminalPanel::slotMostLocalUrlResult(KJob* job) +void TerminalPanel::slotMostLocalUrlResult(KJob *job) { - KIO::StatJob* statJob = static_cast(job); + KIO::StatJob *statJob = static_cast(job); const QUrl url = statJob->mostLocalUrl(); if (url.isLocalFile()) { sendCdToTerminal(url.toLocalFile()); @@ -287,7 +284,7 @@ void TerminalPanel::slotMostLocalUrlResult(KJob* job) m_mostLocalUrlJob = nullptr; } -void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir) +void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString &dir) { m_konsolePartCurrentDirectory = QDir(dir).canonicalPath(); @@ -312,8 +309,8 @@ void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir) } auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory); - QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this); - QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) { + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this); + QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) { watcher->deleteLater(); if (reply.isError()) { // KIOFuse errored out... just show the normal URL diff --git a/src/panels/terminal/terminalpanel.h b/src/panels/terminal/terminalpanel.h index 5a2b0bb839..a1b7af03aa 100644 --- a/src/panels/terminal/terminalpanel.h +++ b/src/panels/terminal/terminalpanel.h @@ -18,12 +18,14 @@ class KMessageWidget; class QVBoxLayout; class QWidget; -namespace KIO { - class StatJob; +namespace KIO +{ +class StatJob; } -namespace KParts { - class ReadOnlyPart; +namespace KParts +{ +class ReadOnlyPart; } class KJob; /** @@ -35,7 +37,7 @@ class TerminalPanel : public Panel Q_OBJECT public: - explicit TerminalPanel(QWidget* parent = nullptr); + explicit TerminalPanel(QWidget *parent = nullptr); ~TerminalPanel() override; /** @@ -60,35 +62,33 @@ Q_SIGNALS: /** * Is emitted if the an URL change is requested. */ - void changeUrl(const QUrl& url); + void changeUrl(const QUrl &url); protected: bool urlChanged() override; - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; private Q_SLOTS: - void slotMostLocalUrlResult(KJob* job); - void slotKonsolePartCurrentDirectoryChanged(const QString& dir); + void slotMostLocalUrlResult(KJob *job); + void slotKonsolePartCurrentDirectoryChanged(const QString &dir); private: - enum class HistoryPolicy { - AddToHistory, - SkipHistory - }; + enum class HistoryPolicy { AddToHistory, SkipHistory }; - void changeDir(const QUrl& url); - void sendCdToTerminal(const QString& path, HistoryPolicy addToHistory = HistoryPolicy::AddToHistory); + void changeDir(const QUrl &url); + void sendCdToTerminal(const QString &path, HistoryPolicy addToHistory = HistoryPolicy::AddToHistory); void sendCdToTerminalKIOFuse(const QUrl &url); + private: bool m_clearTerminal; - KIO::StatJob* m_mostLocalUrlJob; + KIO::StatJob *m_mostLocalUrlJob; - QVBoxLayout* m_layout; - TerminalInterface* m_terminal; - QWidget* m_terminalWidget; - KMessageWidget* m_konsolePartMissingMessage; - KParts::ReadOnlyPart* m_konsolePart; + QVBoxLayout *m_layout; + TerminalInterface *m_terminal; + QWidget *m_terminalWidget; + KMessageWidget *m_konsolePartMissingMessage; + KParts::ReadOnlyPart *m_konsolePart; QString m_konsolePartCurrentDirectory; QQueue m_sendCdToTerminalHistory; org::kde::KIOFuse::VFS m_kiofuseInterface; diff --git a/src/search/dolphinfacetswidget.cpp b/src/search/dolphinfacetswidget.cpp index cc125a2d92..ffc07442a2 100644 --- a/src/search/dolphinfacetswidget.cpp +++ b/src/search/dolphinfacetswidget.cpp @@ -18,31 +18,37 @@ #include #include -DolphinFacetsWidget::DolphinFacetsWidget(QWidget* parent) : - QWidget(parent), - m_typeSelector(nullptr), - m_dateSelector(nullptr), - m_ratingSelector(nullptr), - m_tagsSelector(nullptr) +DolphinFacetsWidget::DolphinFacetsWidget(QWidget *parent) + : QWidget(parent) + , m_typeSelector(nullptr) + , m_dateSelector(nullptr) + , m_ratingSelector(nullptr) + , m_tagsSelector(nullptr) { m_typeSelector = new QComboBox(this); m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("none")), i18nc("@item:inlistbox", "Any Type"), QString()); - m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("inode-directory")), i18nc("@item:inlistbox", "Folders") , QStringLiteral("Folder")); - m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("text-x-generic")), i18nc("@item:inlistbox", "Documents") , QStringLiteral("Document")); - m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("image-x-generic")), i18nc("@item:inlistbox", "Images") , QStringLiteral("Image")); + m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("inode-directory")), i18nc("@item:inlistbox", "Folders"), QStringLiteral("Folder")); + m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("text-x-generic")), i18nc("@item:inlistbox", "Documents"), QStringLiteral("Document")); + m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("image-x-generic")), i18nc("@item:inlistbox", "Images"), QStringLiteral("Image")); m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("audio-x-generic")), i18nc("@item:inlistbox", "Audio Files"), QStringLiteral("Audio")); - m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("video-x-generic")), i18nc("@item:inlistbox", "Videos") , QStringLiteral("Video")); + m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("video-x-generic")), i18nc("@item:inlistbox", "Videos"), QStringLiteral("Video")); initComboBox(m_typeSelector); const QDate currentDate = QDate::currentDate(); m_dateSelector = new QComboBox(this); m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar")), i18nc("@item:inlistbox", "Any Date"), QDate()); - m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Today") , currentDate); - m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Yesterday") , currentDate.addDays(-1)); - m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-week")), i18nc("@item:inlistbox", "This Week") , currentDate.addDays(1 - currentDate.dayOfWeek())); - m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-month")), i18nc("@item:inlistbox", "This Month"), currentDate.addDays(1 - currentDate.day())); - m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-year")), i18nc("@item:inlistbox", "This Year") , currentDate.addDays(1 - currentDate.dayOfYear())); + m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Today"), currentDate); + m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Yesterday"), currentDate.addDays(-1)); + m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-week")), + i18nc("@item:inlistbox", "This Week"), + currentDate.addDays(1 - currentDate.dayOfWeek())); + m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-month")), + i18nc("@item:inlistbox", "This Month"), + currentDate.addDays(1 - currentDate.day())); + m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-year")), + i18nc("@item:inlistbox", "This Year"), + currentDate.addDays(1 - currentDate.dayOfYear())); initComboBox(m_dateSelector); m_ratingSelector = new QComboBox(this); @@ -73,7 +79,7 @@ DolphinFacetsWidget::DolphinFacetsWidget(QWidget* parent) : connect(&m_tagsLister, &KCoreDirLister::itemsAdded, this, &DolphinFacetsWidget::updateTagsMenuItems); updateTagsMenu(); - QHBoxLayout* topLayout = new QHBoxLayout(this); + QHBoxLayout *topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); topLayout->addWidget(m_typeSelector); topLayout->addWidget(m_dateSelector); @@ -139,13 +145,9 @@ QString DolphinFacetsWidget::facetType() const return m_typeSelector->currentData().toString(); } -bool DolphinFacetsWidget::isSearchTerm(const QString& term) const +bool DolphinFacetsWidget::isSearchTerm(const QString &term) const { - static const QLatin1String searchTokens[] { - QLatin1String("modified>="), - QLatin1String("rating>="), - QLatin1String("tag:"), QLatin1String("tag=") - }; + static const QLatin1String searchTokens[]{QLatin1String("modified>="), QLatin1String("rating>="), QLatin1String("tag:"), QLatin1String("tag=")}; for (const auto &searchToken : searchTokens) { if (term.startsWith(searchToken)) { @@ -155,7 +157,7 @@ bool DolphinFacetsWidget::isSearchTerm(const QString& term) const return false; } -void DolphinFacetsWidget::setSearchTerm(const QString& term) +void DolphinFacetsWidget::setSearchTerm(const QString &term) { if (term.startsWith(QLatin1String("modified>="))) { const QString value = term.mid(10); @@ -165,14 +167,13 @@ void DolphinFacetsWidget::setSearchTerm(const QString& term) const QString value = term.mid(8); const int stars = value.toInt() / 2; setRating(stars); - } else if (term.startsWith(QLatin1String("tag:")) || - term.startsWith(QLatin1String("tag="))) { + } else if (term.startsWith(QLatin1String("tag:")) || term.startsWith(QLatin1String("tag="))) { const QString value = term.mid(4); addSearchTag(value); } } -void DolphinFacetsWidget::setFacetType(const QString& type) +void DolphinFacetsWidget::setFacetType(const QString &type) { for (int index = 0; index <= m_typeSelector->count(); index++) { if (type == m_typeSelector->itemData(index).toString()) { @@ -190,7 +191,7 @@ void DolphinFacetsWidget::setRating(const int stars) m_ratingSelector->setCurrentIndex(stars); } -void DolphinFacetsWidget::setTimespan(const QDate& date) +void DolphinFacetsWidget::setTimespan(const QDate &date) { if (!date.isValid()) { return; @@ -204,7 +205,7 @@ void DolphinFacetsWidget::setTimespan(const QDate& date) } } -void DolphinFacetsWidget::addSearchTag(const QString& tag) +void DolphinFacetsWidget::addSearchTag(const QString &tag) { if (tag.isEmpty() || m_searchTags.contains(tag)) { return; @@ -214,7 +215,7 @@ void DolphinFacetsWidget::addSearchTag(const QString& tag) updateTagsSelector(); } -void DolphinFacetsWidget::removeSearchTag(const QString& tag) +void DolphinFacetsWidget::removeSearchTag(const QString &tag) { if (tag.isEmpty() || !m_searchTags.contains(tag)) { return; @@ -230,7 +231,7 @@ void DolphinFacetsWidget::resetSearchTags() updateTagsMenu(); } -void DolphinFacetsWidget::initComboBox(QComboBox* combo) +void DolphinFacetsWidget::initComboBox(QComboBox *combo) { combo->setFrame(false); combo->setMinimumHeight(parentWidget()->height()); @@ -245,8 +246,7 @@ void DolphinFacetsWidget::updateTagsSelector() if (hasSelectedTags) { const QString tagsText = m_searchTags.join(i18nc("String list separator", ", ")); - m_tagsSelector->setText(i18ncp("@action:button %2 is a list of tags", - "Tag: %2", "Tags: %2",m_searchTags.count(), tagsText)); + m_tagsSelector->setText(i18ncp("@action:button %2 is a list of tags", "Tag: %2", "Tags: %2", m_searchTags.count(), tagsText)); } else { m_tagsSelector->setText(i18nc("@action:button", "Add Tags")); } @@ -263,13 +263,13 @@ void DolphinFacetsWidget::updateTagsMenu() } } -void DolphinFacetsWidget::updateTagsMenuItems(const QUrl&, const KFileItemList& items) +void DolphinFacetsWidget::updateTagsMenuItems(const QUrl &, const KFileItemList &items) { QMenu *tagsMenu = m_tagsSelector->menu(); tagsMenu->clear(); QStringList allTags = QStringList(m_searchTags); - for (const KFileItem &item: items) { + for (const KFileItem &item : items) { allTags.append(item.name()); } allTags.sort(Qt::CaseInsensitive); @@ -277,7 +277,7 @@ void DolphinFacetsWidget::updateTagsMenuItems(const QUrl&, const KFileItemList& const bool onlyOneTag = allTags.count() == 1; - for (const QString& tagName : qAsConst(allTags)) { + for (const QString &tagName : qAsConst(allTags)) { QAction *action = tagsMenu->addAction(QIcon::fromTheme(QStringLiteral("tag")), tagName); action->setCheckable(true); action->setChecked(m_searchTags.contains(tagName)); diff --git a/src/search/dolphinfacetswidget.h b/src/search/dolphinfacetswidget.h index 3e3b0f2644..1d266ac97a 100644 --- a/src/search/dolphinfacetswidget.h +++ b/src/search/dolphinfacetswidget.h @@ -7,8 +7,8 @@ #ifndef DOLPHINFACETSWIDGET_H #define DOLPHINFACETSWIDGET_H -#include #include +#include class QComboBox; class QDate; @@ -36,43 +36,43 @@ class DolphinFacetsWidget : public QWidget Q_OBJECT public: - explicit DolphinFacetsWidget(QWidget* parent = nullptr); + explicit DolphinFacetsWidget(QWidget *parent = nullptr); ~DolphinFacetsWidget() override; QStringList searchTerms() const; QString facetType() const; - bool isSearchTerm(const QString& term) const; - void setSearchTerm(const QString& term); + bool isSearchTerm(const QString &term) const; + void setSearchTerm(const QString &term); void resetSearchTerms(); - void setFacetType(const QString& type); + void setFacetType(const QString &type); Q_SIGNALS: void facetChanged(); protected: - void changeEvent(QEvent* event) override; + void changeEvent(QEvent *event) override; private Q_SLOTS: void updateTagsMenu(); - void updateTagsMenuItems(const QUrl&, const KFileItemList& items); + void updateTagsMenuItems(const QUrl &, const KFileItemList &items); private: void setRating(const int stars); - void setTimespan(const QDate& date); - void addSearchTag(const QString& tag); - void removeSearchTag(const QString& tag); + void setTimespan(const QDate &date); + void addSearchTag(const QString &tag); + void removeSearchTag(const QString &tag); void resetSearchTags(); - void initComboBox(QComboBox* combo); + void initComboBox(QComboBox *combo); void updateTagsSelector(); private: - QComboBox* m_typeSelector; - QComboBox* m_dateSelector; - QComboBox* m_ratingSelector; - QToolButton* m_tagsSelector; + QComboBox *m_typeSelector; + QComboBox *m_dateSelector; + QComboBox *m_ratingSelector; + QToolButton *m_tagsSelector; QStringList m_searchTags; KCoreDirLister m_tagsLister; diff --git a/src/search/dolphinquery.cpp b/src/search/dolphinquery.cpp index 687213cbf1..f9e5da84f5 100644 --- a/src/search/dolphinquery.cpp +++ b/src/search/dolphinquery.cpp @@ -13,65 +13,63 @@ #include #endif -namespace { +namespace +{ #if HAVE_BALOO - /** Checks if a given term in the Baloo::Query::searchString() is a special search term - * @return: the specific search token of the term, or an empty QString() if none is found - */ - QString searchTermToken(const QString& term) - { - static const QLatin1String searchTokens[] { - QLatin1String("filename:"), - QLatin1String("modified>="), - QLatin1String("rating>="), - QLatin1String("tag:"), QLatin1String("tag=") - }; +/** Checks if a given term in the Baloo::Query::searchString() is a special search term + * @return: the specific search token of the term, or an empty QString() if none is found + */ +QString searchTermToken(const QString &term) +{ + static const QLatin1String searchTokens[]{QLatin1String("filename:"), + QLatin1String("modified>="), + QLatin1String("rating>="), + QLatin1String("tag:"), + QLatin1String("tag=")}; - for (const auto &searchToken : searchTokens) { - if (term.startsWith(searchToken)) { - return searchToken; - } + for (const auto &searchToken : searchTokens) { + if (term.startsWith(searchToken)) { + return searchToken; } - return QString(); - } - - QString stripQuotes(const QString& text) - { - if (text.length() >= 2 && text.at(0) == QLatin1Char('"') - && text.back() == QLatin1Char('"')) { - return text.mid(1, text.size() - 2); - } - return text; - } - - QStringList splitOutsideQuotes(const QString& text) - { - // Match groups on 3 possible conditions: - // - Groups with two leading quotes must close both on them (filename:""abc xyz" tuv") - // - Groups enclosed in quotes - // - Words separated by spaces - const QRegularExpression subTermsRegExp("(\\S*?\"\"[^\"]+\"[^\"]+\"+|\\S*?\"[^\"]+\"+|(?<=\\s|^)\\S+(?=\\s|$))"); - auto subTermsMatchIterator = subTermsRegExp.globalMatch(text); - - QStringList textParts; - while (subTermsMatchIterator.hasNext()) { - textParts << subTermsMatchIterator.next().captured(0); - } - return textParts; - } -#endif - - QString trimChar(const QString& text, const QLatin1Char aChar) - { - const int start = text.startsWith(aChar) ? 1 : 0; - const int end = (text.length() > 1 && text.endsWith(aChar)) ? 1 : 0; - - return text.mid(start, text.length() - start - end); } + return QString(); } +QString stripQuotes(const QString &text) +{ + if (text.length() >= 2 && text.at(0) == QLatin1Char('"') && text.back() == QLatin1Char('"')) { + return text.mid(1, text.size() - 2); + } + return text; +} -DolphinQuery DolphinQuery::fromSearchUrl(const QUrl& searchUrl) +QStringList splitOutsideQuotes(const QString &text) +{ + // Match groups on 3 possible conditions: + // - Groups with two leading quotes must close both on them (filename:""abc xyz" tuv") + // - Groups enclosed in quotes + // - Words separated by spaces + const QRegularExpression subTermsRegExp("(\\S*?\"\"[^\"]+\"[^\"]+\"+|\\S*?\"[^\"]+\"+|(?<=\\s|^)\\S+(?=\\s|$))"); + auto subTermsMatchIterator = subTermsRegExp.globalMatch(text); + + QStringList textParts; + while (subTermsMatchIterator.hasNext()) { + textParts << subTermsMatchIterator.next().captured(0); + } + return textParts; +} +#endif + +QString trimChar(const QString &text, const QLatin1Char aChar) +{ + const int start = text.startsWith(aChar) ? 1 : 0; + const int end = (text.length() > 1 && text.endsWith(aChar)) ? 1 : 0; + + return text.mid(start, text.length() - start - end); +} +} + +DolphinQuery DolphinQuery::fromSearchUrl(const QUrl &searchUrl) { DolphinQuery model; model.m_searchUrl = searchUrl; @@ -87,7 +85,7 @@ DolphinQuery DolphinQuery::fromSearchUrl(const QUrl& searchUrl) return model; } -bool DolphinQuery::supportsScheme(const QString& urlScheme) +bool DolphinQuery::supportsScheme(const QString &urlScheme) { static const QStringList supportedSchemes = { QStringLiteral("baloosearch"), @@ -111,7 +109,7 @@ void DolphinQuery::parseBalooQuery() QString fileName; const QStringList subTerms = splitOutsideQuotes(query.searchString()); - for (const QString& subTerm : subTerms) { + for (const QString &subTerm : subTerms) { const QString token = searchTermToken(subTerm); const QString value = stripQuotes(subTerm.mid(token.length())); @@ -144,7 +142,6 @@ void DolphinQuery::parseBalooQuery() #endif } - QUrl DolphinQuery::searchUrl() const { return m_searchUrl; diff --git a/src/search/dolphinquery.h b/src/search/dolphinquery.h index a620e95d82..1334958f15 100644 --- a/src/search/dolphinquery.h +++ b/src/search/dolphinquery.h @@ -20,9 +20,9 @@ class DolphinQuery { public: /** Parses the components of @p searchUrl for the supported schemes */ - static DolphinQuery fromSearchUrl(const QUrl& searchUrl); + static DolphinQuery fromSearchUrl(const QUrl &searchUrl); /** Checks whether the DolphinQuery supports the given @p urlScheme */ - static bool supportsScheme(const QString& urlScheme); + static bool supportsScheme(const QString &urlScheme); /** @return the \a searchUrl passed to Baloo::Query::fromSearchUrl() */ QUrl searchUrl() const; diff --git a/src/search/dolphinsearchbox.cpp b/src/search/dolphinsearchbox.cpp index 26c78c1115..b44f19092b 100644 --- a/src/search/dolphinsearchbox.cpp +++ b/src/search/dolphinsearchbox.cpp @@ -4,21 +4,21 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ -#include "global.h" #include "dolphinsearchbox.h" +#include "global.h" #include "dolphin_searchsettings.h" #include "dolphinfacetswidget.h" #include "dolphinplacesmodelsingleton.h" #include "dolphinquery.h" +#include "config-dolphin.h" #include #include #include -#include "config-dolphin.h" #if HAVE_BALOO -#include #include +#include #endif #include @@ -34,22 +34,22 @@ #include #include -DolphinSearchBox::DolphinSearchBox(QWidget* parent) : - QWidget(parent), - m_startedSearching(false), - m_active(true), - m_topLayout(nullptr), - m_searchInput(nullptr), - m_saveSearchAction(nullptr), - m_optionsScrollArea(nullptr), - m_fileNameButton(nullptr), - m_contentButton(nullptr), - m_separator(nullptr), - m_fromHereButton(nullptr), - m_everywhereButton(nullptr), - m_facetsWidget(nullptr), - m_searchPath(), - m_startSearchTimer(nullptr) +DolphinSearchBox::DolphinSearchBox(QWidget *parent) + : QWidget(parent) + , m_startedSearching(false) + , m_active(true) + , m_topLayout(nullptr) + , m_searchInput(nullptr) + , m_saveSearchAction(nullptr) + , m_optionsScrollArea(nullptr) + , m_fileNameButton(nullptr) + , m_contentButton(nullptr) + , m_separator(nullptr) + , m_fromHereButton(nullptr) + , m_everywhereButton(nullptr) + , m_facetsWidget(nullptr) + , m_searchPath() + , m_startSearchTimer(nullptr) { } @@ -58,7 +58,7 @@ DolphinSearchBox::~DolphinSearchBox() saveSettings(); } -void DolphinSearchBox::setText(const QString& text) +void DolphinSearchBox::setText(const QString &text) { m_searchInput->setText(text); } @@ -68,7 +68,7 @@ QString DolphinSearchBox::text() const return m_searchInput->text(); } -void DolphinSearchBox::setSearchPath(const QUrl& url) +void DolphinSearchBox::setSearchPath(const QUrl &url) { if (url == m_searchPath) { return; @@ -130,7 +130,7 @@ QUrl DolphinSearchBox::urlForSearching() const return url; } -void DolphinSearchBox::fromSearchUrl(const QUrl& url) +void DolphinSearchBox::fromSearchUrl(const QUrl &url) { if (DolphinQuery::supportsScheme(url.scheme())) { const DolphinQuery query = DolphinQuery::fromSearchUrl(url); @@ -173,7 +173,7 @@ bool DolphinSearchBox::isActive() const return m_active; } -bool DolphinSearchBox::event(QEvent* event) +bool DolphinSearchBox::event(QEvent *event) { if (event->type() == QEvent::Polish) { init(); @@ -181,7 +181,7 @@ bool DolphinSearchBox::event(QEvent* event) return QWidget::event(event); } -void DolphinSearchBox::showEvent(QShowEvent* event) +void DolphinSearchBox::showEvent(QShowEvent *event) { if (!event->spontaneous()) { m_searchInput->setFocus(); @@ -189,14 +189,14 @@ void DolphinSearchBox::showEvent(QShowEvent* event) } } -void DolphinSearchBox::hideEvent(QHideEvent* event) +void DolphinSearchBox::hideEvent(QHideEvent *event) { Q_UNUSED(event) m_startedSearching = false; m_startSearchTimer->stop(); } -void DolphinSearchBox::keyReleaseEvent(QKeyEvent* event) +void DolphinSearchBox::keyReleaseEvent(QKeyEvent *event) { QWidget::keyReleaseEvent(event); if (event->key() == Qt::Key_Escape) { @@ -205,13 +205,12 @@ void DolphinSearchBox::keyReleaseEvent(QKeyEvent* event) } else { m_searchInput->clear(); } - } - else if (event->key() == Qt::Key_Down) { + } else if (event->key() == Qt::Key_Down) { Q_EMIT focusViewRequest(); } } -bool DolphinSearchBox::eventFilter(QObject* obj, QEvent* event) +bool DolphinSearchBox::eventFilter(QObject *obj, QEvent *event) { switch (event->type()) { case QEvent::FocusIn: @@ -259,9 +258,8 @@ void DolphinSearchBox::slotConfigurationChanged() } } -void DolphinSearchBox::slotSearchTextChanged(const QString& text) +void DolphinSearchBox::slotSearchTextChanged(const QString &text) { - if (text.isEmpty()) { m_startSearchTimer->stop(); } else { @@ -292,7 +290,7 @@ void DolphinSearchBox::slotSearchSaved() } } -void DolphinSearchBox::initButton(QToolButton* button) +void DolphinSearchBox::initButton(QToolButton *button) { button->installEventFilter(this); button->setAutoExclusive(true); @@ -333,29 +331,27 @@ void DolphinSearchBox::init() m_searchInput->installEventFilter(this); m_searchInput->setClearButtonEnabled(true); m_searchInput->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont)); - connect(m_searchInput, &QLineEdit::returnPressed, - this, &DolphinSearchBox::slotReturnPressed); - connect(m_searchInput, &QLineEdit::textChanged, - this, &DolphinSearchBox::slotSearchTextChanged); + connect(m_searchInput, &QLineEdit::returnPressed, this, &DolphinSearchBox::slotReturnPressed); + connect(m_searchInput, &QLineEdit::textChanged, this, &DolphinSearchBox::slotSearchTextChanged); setFocusProxy(m_searchInput); // Add "Save search" button inside search box m_saveSearchAction = new QAction(this); - m_saveSearchAction->setIcon (QIcon::fromTheme(QStringLiteral("document-save-symbolic"))); + m_saveSearchAction->setIcon(QIcon::fromTheme(QStringLiteral("document-save-symbolic"))); m_saveSearchAction->setText(i18nc("action:button", "Save this search to quickly access it again in the future")); m_saveSearchAction->setEnabled(false); m_searchInput->addAction(m_saveSearchAction, QLineEdit::TrailingPosition); connect(m_saveSearchAction, &QAction::triggered, this, &DolphinSearchBox::slotSearchSaved); // Create close button - QToolButton* closeButton = new QToolButton(this); + QToolButton *closeButton = new QToolButton(this); closeButton->setAutoRaise(true); closeButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close"))); closeButton->setToolTip(i18nc("@info:tooltip", "Quit searching")); connect(closeButton, &QToolButton::clicked, this, &DolphinSearchBox::emitCloseRequest); // Apply layout for the search input - QHBoxLayout* searchInputLayout = new QHBoxLayout(); + QHBoxLayout *searchInputLayout = new QHBoxLayout(); searchInputLayout->setContentsMargins(0, 0, 0, 0); searchInputLayout->addWidget(m_searchInput); searchInputLayout->addWidget(closeButton); @@ -369,7 +365,7 @@ void DolphinSearchBox::init() m_contentButton->setText(i18nc("action:button", "Content")); initButton(m_contentButton); - QButtonGroup* searchWhatGroup = new QButtonGroup(this); + QButtonGroup *searchWhatGroup = new QButtonGroup(this); searchWhatGroup->addButton(m_fileNameButton); searchWhatGroup->addButton(m_contentButton); @@ -387,7 +383,7 @@ void DolphinSearchBox::init() m_everywhereButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); initButton(m_everywhereButton); - QButtonGroup* searchLocationGroup = new QButtonGroup(this); + QButtonGroup *searchLocationGroup = new QButtonGroup(this); searchLocationGroup->addButton(m_fromHereButton); searchLocationGroup->addButton(m_everywhereButton); @@ -398,12 +394,11 @@ void DolphinSearchBox::init() moreSearchToolsButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); moreSearchToolsButton->setText(i18n("More Search Tools")); moreSearchToolsButton->setMenu(new QMenu(this)); - connect(moreSearchToolsButton->menu(), &QMenu::aboutToShow, moreSearchToolsButton->menu(), [this, moreSearchToolsButton]() - { + connect(moreSearchToolsButton->menu(), &QMenu::aboutToShow, moreSearchToolsButton->menu(), [this, moreSearchToolsButton]() { m_menuFactory.reset(new KMoreToolsMenuFactory("dolphin/search-tools")); moreSearchToolsButton->menu()->clear(); - m_menuFactory->fillMenuFromGroupingNames(moreSearchToolsButton->menu(), { "files-find" }, this->m_searchPath); - } ); + m_menuFactory->fillMenuFromGroupingNames(moreSearchToolsButton->menu(), {"files-find"}, this->m_searchPath); + }); // Create "Facets" widget m_facetsWidget = new DolphinFacetsWidget(this); @@ -414,10 +409,10 @@ void DolphinSearchBox::init() // Put the options into a QScrollArea. This prevents increasing the view width // in case that not enough width for the options is available. - QWidget* optionsContainer = new QWidget(this); + QWidget *optionsContainer = new QWidget(this); // Apply layout for the options - QHBoxLayout* optionsLayout = new QHBoxLayout(optionsContainer); + QHBoxLayout *optionsLayout = new QHBoxLayout(optionsContainer); optionsLayout->setContentsMargins(0, 0, 0, 0); optionsLayout->setSpacing(Dolphin::LAYOUT_SPACING_SMALL); optionsLayout->addWidget(m_fileNameButton); @@ -455,10 +450,9 @@ void DolphinSearchBox::init() connect(m_startSearchTimer, &QTimer::timeout, this, &DolphinSearchBox::emitSearchRequest); } -QString DolphinSearchBox::queryTitle(const QString& text) const +QString DolphinSearchBox::queryTitle(const QString &text) const { - return i18nc("@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.", - "Query Results from '%1'", text); + return i18nc("@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.", "Query Results from '%1'", text); } QUrl DolphinSearchBox::balooUrlForSearching() const @@ -489,7 +483,7 @@ QUrl DolphinSearchBox::balooUrlForSearching() const #endif } -void DolphinSearchBox::updateFromQuery(const DolphinQuery& query) +void DolphinSearchBox::updateFromQuery(const DolphinQuery &query) { // Block all signals to avoid unnecessary "searchRequest" signals // while we adjust the search text and the facet widget. @@ -509,14 +503,14 @@ void DolphinSearchBox::updateFromQuery(const DolphinQuery& query) if (query.hasContentSearch()) { m_contentButton->setChecked(true); - } else if (query.hasFileName()) { + } else if (query.hasFileName()) { m_fileNameButton->setChecked(true); } m_facetsWidget->resetSearchTerms(); m_facetsWidget->setFacetType(query.type()); const QStringList searchTerms = query.searchTerms(); - for (const QString& searchTerm : searchTerms) { + for (const QString &searchTerm : searchTerms) { m_facetsWidget->setSearchTerm(searchTerm); } diff --git a/src/search/dolphinsearchbox.h b/src/search/dolphinsearchbox.h index 1bd21f17b7..4ccb7ac107 100644 --- a/src/search/dolphinsearchbox.h +++ b/src/search/dolphinsearchbox.h @@ -30,18 +30,19 @@ class KMoreToolsMenuFactory; * If Baloo is available and the current folder is indexed, further * options are offered. */ -class DolphinSearchBox : public QWidget { +class DolphinSearchBox : public QWidget +{ Q_OBJECT public: - explicit DolphinSearchBox(QWidget* parent = nullptr); + explicit DolphinSearchBox(QWidget *parent = nullptr); ~DolphinSearchBox() override; /** * Sets the text that should be used as input for * searching. */ - void setText(const QString& text); + void setText(const QString &text); /** * Returns the text that should be used as input @@ -53,7 +54,7 @@ public: * Sets the current path that is used as root for searching files. * If @url is the Home dir, "From Here" is selected instead. */ - void setSearchPath(const QUrl& url); + void setSearchPath(const QUrl &url); QUrl searchPath() const; /** @return URL that will start the searching of files. */ @@ -63,7 +64,7 @@ public: * Extracts information from the given search \a url to * initialize the search box properly. */ - void fromSearchUrl(const QUrl& url); + void fromSearchUrl(const QUrl &url); /** * Selects the whole text of the search box. @@ -87,11 +88,11 @@ public: bool isActive() const; protected: - bool event(QEvent* event) override; - void showEvent(QShowEvent* event) override; - void hideEvent(QHideEvent* event) override; - void keyReleaseEvent(QKeyEvent* event) override; - bool eventFilter(QObject* obj, QEvent* event) override; + bool event(QEvent *event) override; + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; + void keyReleaseEvent(QKeyEvent *event) override; + bool eventFilter(QObject *obj, QEvent *event) override; Q_SIGNALS: /** @@ -103,7 +104,7 @@ Q_SIGNALS: * Is emitted when the user has changed a character of * the text that should be used as input for searching. */ - void searchTextChanged(const QString& text); + void searchTextChanged(const QString &text); /** * Emitted as soon as the search box should get closed. @@ -122,13 +123,13 @@ private Q_SLOTS: void emitSearchRequest(); void emitCloseRequest(); void slotConfigurationChanged(); - void slotSearchTextChanged(const QString& text); + void slotSearchTextChanged(const QString &text); void slotReturnPressed(); void slotFacetChanged(); void slotSearchSaved(); private: - void initButton(QToolButton* button); + void initButton(QToolButton *button); void loadSettings(); void saveSettings(); void init(); @@ -141,34 +142,34 @@ private: /** * Sets the searchbox UI with the parameters established by the \a query */ - void updateFromQuery(const DolphinQuery& query); + void updateFromQuery(const DolphinQuery &query); void updateFacetsVisible(); bool isIndexingEnabled() const; private: - QString queryTitle(const QString& text) const; + QString queryTitle(const QString &text) const; bool m_startedSearching; bool m_active; - QVBoxLayout* m_topLayout; + QVBoxLayout *m_topLayout; - QLineEdit* m_searchInput; - QAction* m_saveSearchAction; - QScrollArea* m_optionsScrollArea; - QToolButton* m_fileNameButton; - QToolButton* m_contentButton; - KSeparator* m_separator; - QToolButton* m_fromHereButton; - QToolButton* m_everywhereButton; - DolphinFacetsWidget* m_facetsWidget; + QLineEdit *m_searchInput; + QAction *m_saveSearchAction; + QScrollArea *m_optionsScrollArea; + QToolButton *m_fileNameButton; + QToolButton *m_contentButton; + KSeparator *m_separator; + QToolButton *m_fromHereButton; + QToolButton *m_everywhereButton; + DolphinFacetsWidget *m_facetsWidget; QUrl m_searchPath; QScopedPointer m_menuFactory; - QTimer* m_startSearchTimer; + QTimer *m_startSearchTimer; }; #endif diff --git a/src/selectionmode/actiontexthelper.cpp b/src/selectionmode/actiontexthelper.cpp index 1036042362..28a247185d 100644 --- a/src/selectionmode/actiontexthelper.cpp +++ b/src/selectionmode/actiontexthelper.cpp @@ -9,9 +9,10 @@ using namespace SelectionMode; -ActionTextHelper::ActionTextHelper(QObject *parent) : - QObject(parent) -{ } +ActionTextHelper::ActionTextHelper(QObject *parent) + : QObject(parent) +{ +} void ActionTextHelper::registerTextWhenNothingIsSelected(QAction *action, QString registeredText) { diff --git a/src/selectionmode/actiontexthelper.h b/src/selectionmode/actiontexthelper.h index 1b88403754..6ca99990f8 100644 --- a/src/selectionmode/actiontexthelper.h +++ b/src/selectionmode/actiontexthelper.h @@ -42,10 +42,7 @@ public: void textsWhenNothingIsSelectedEnabled(bool enabled); private: - enum TextState { - TextWhenNothingIsSelected, - TextWhenSomethingIsSelected - }; + enum TextState { TextWhenNothingIsSelected, TextWhenSomethingIsSelected }; /** * Utility struct to allow switching back and forth between registered actions showing their @@ -53,16 +50,15 @@ private: * An example is "Copy" or "Copy…". The latter one is used when nothing is selected and signifies * that it will trigger SelectionMode so items can be selected and then copied. */ - struct RegisteredActionTextChange { + struct RegisteredActionTextChange { QPointer action; QString registeredText; TextState textStateOfRegisteredText; - RegisteredActionTextChange(QAction *action, QString registeredText, TextState state) : - action{action}, - registeredText{registeredText}, - textStateOfRegisteredText{state} - { }; + RegisteredActionTextChange(QAction *action, QString registeredText, TextState state) + : action{action} + , registeredText{registeredText} + , textStateOfRegisteredText{state} {}; }; /** diff --git a/src/selectionmode/actionwithwidget.cpp b/src/selectionmode/actionwithwidget.cpp index 82ce045dbf..1284912b65 100644 --- a/src/selectionmode/actionwithwidget.cpp +++ b/src/selectionmode/actionwithwidget.cpp @@ -14,13 +14,14 @@ using namespace SelectionMode; -ActionWithWidget::ActionWithWidget(QAction *action) : - m_action{action} -{ } +ActionWithWidget::ActionWithWidget(QAction *action) + : m_action{action} +{ +} -ActionWithWidget::ActionWithWidget(QAction *action, QAbstractButton *button) : - m_action{action}, - m_widget{button} +ActionWithWidget::ActionWithWidget(QAction *action, QAbstractButton *button) + : m_action{action} + , m_widget{button} { copyActionDataToButton(button, action); } diff --git a/src/selectionmode/actionwithwidget.h b/src/selectionmode/actionwithwidget.h index 14db6df222..9b83022dea 100644 --- a/src/selectionmode/actionwithwidget.h +++ b/src/selectionmode/actionwithwidget.h @@ -42,13 +42,15 @@ public: ActionWithWidget(QAction *action, QAbstractButton *button); /** @returns the action of this object. */ - inline QAction *action() { + inline QAction *action() + { Q_CHECK_PTR(m_action); return m_action; }; /** @returns the widget of this object. */ - inline QWidget *widget() { + inline QWidget *widget() + { return m_widget; } @@ -61,7 +63,8 @@ public: QWidget *newWidget(QWidget *parent); /** returns true if the widget exists and is visible. false otherwise. */ - inline bool isWidgetVisible() const { + inline bool isWidgetVisible() const + { return m_widget && m_widget->isVisible(); }; diff --git a/src/selectionmode/backgroundcolorhelper.cpp b/src/selectionmode/backgroundcolorhelper.cpp index 799db43d59..1615c36bbb 100644 --- a/src/selectionmode/backgroundcolorhelper.cpp +++ b/src/selectionmode/backgroundcolorhelper.cpp @@ -23,11 +23,10 @@ BackgroundColorHelper *BackgroundColorHelper::instance() return s_instance; } - void setBackgroundColorForWidget(QWidget *widget, QColor color) { QPalette palette; - palette.setBrush(QPalette::Active, QPalette::Window, color); + palette.setBrush(QPalette::Active, QPalette::Window, color); palette.setBrush(QPalette::Inactive, QPalette::Window, color); palette.setBrush(QPalette::Disabled, QPalette::Window, color); widget->setAutoFillBackground(true); @@ -38,7 +37,8 @@ void BackgroundColorHelper::controlBackgroundColor(QWidget *widget) { setBackgroundColorForWidget(widget, m_backgroundColor); - Q_ASSERT_X(std::find(m_colorControlledWidgets.begin(), m_colorControlledWidgets.end(), widget) == m_colorControlledWidgets.end(), "controlBackgroundColor", + Q_ASSERT_X(std::find(m_colorControlledWidgets.begin(), m_colorControlledWidgets.end(), widget) == m_colorControlledWidgets.end(), + "controlBackgroundColor", "Duplicate insertion is not necessary because the background color should already automatically update itself on paletteChanged"); m_colorControlledWidgets.emplace_back(widget); } @@ -46,7 +46,9 @@ void BackgroundColorHelper::controlBackgroundColor(QWidget *widget) BackgroundColorHelper::BackgroundColorHelper() { updateBackgroundColor(); - QObject::connect(qApp, &QGuiApplication::paletteChanged, [=](){ slotPaletteChanged(); }); + QObject::connect(qApp, &QGuiApplication::paletteChanged, [=]() { + slotPaletteChanged(); + }); } void BackgroundColorHelper::slotPaletteChanged() @@ -77,9 +79,7 @@ void BackgroundColorHelper::updateBackgroundColor() if (std::abs(hueDifference) > 80) { newHue = (activeBackgroundColor.hue() + positiveBackgroundColor.hue()) / 2; } else { - newHue = hueDifference > 0 ? - activeBackgroundColor.hue() + 40 : - activeBackgroundColor.hue() - 40; + newHue = hueDifference > 0 ? activeBackgroundColor.hue() + 40 : activeBackgroundColor.hue() - 40; newHue %= 360; // hue needs to be between 0 and 359 per Qt documentation. } diff --git a/src/selectionmode/bottombar.cpp b/src/selectionmode/bottombar.cpp index c912dd4891..f394310762 100644 --- a/src/selectionmode/bottombar.cpp +++ b/src/selectionmode/bottombar.cpp @@ -7,8 +7,8 @@ #include "bottombar.h" -#include "bottombarcontentscontainer.h" #include "backgroundcolorhelper.h" +#include "bottombarcontentscontainer.h" #include #include @@ -18,8 +18,8 @@ using namespace SelectionMode; -BottomBar::BottomBar(KActionCollection *actionCollection, QWidget *parent) : - QWidget{parent} +BottomBar::BottomBar(KActionCollection *actionCollection, QWidget *parent) + : QWidget{parent} { // Showing of this widget is normally animated. We hide it for now and make it small. hide(); @@ -44,7 +44,7 @@ BottomBar::BottomBar(KActionCollection *actionCollection, QWidget *parent) : m_scrollArea->setWidget(m_contentsContainer); m_contentsContainer->installEventFilter(this); // Adjusts the height of this bar to the height of the contentsContainer connect(m_contentsContainer, &BottomBarContentsContainer::error, this, &BottomBar::error); - connect(m_contentsContainer, &BottomBarContentsContainer::barVisibilityChangeRequested, this, [this](bool visible){ + connect(m_contentsContainer, &BottomBarContentsContainer::barVisibilityChangeRequested, this, [this](bool visible) { if (!m_allowedToBeVisible && visible) { return; } @@ -77,20 +77,18 @@ void BottomBar::setVisibleInternal(bool visible, Animated animated) m_heightAnimation->stop(); // deletes because of QAbstractAnimation::DeleteWhenStopped. } m_heightAnimation = new QPropertyAnimation(this, "maximumHeight"); - m_heightAnimation->setDuration(2 * - style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * - GlobalConfig::animationDurationFactor()); + m_heightAnimation->setDuration(2 * style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * GlobalConfig::animationDurationFactor()); m_heightAnimation->setStartValue(height()); m_heightAnimation->setEasingCurve(QEasingCurve::OutCubic); if (visible) { show(); m_heightAnimation->setEndValue(sizeHint().height()); - connect(m_heightAnimation, &QAbstractAnimation::finished, - this, [this](){ setMaximumHeight(sizeHint().height()); }); + connect(m_heightAnimation, &QAbstractAnimation::finished, this, [this]() { + setMaximumHeight(sizeHint().height()); + }); } else { m_heightAnimation->setEndValue(0); - connect(m_heightAnimation, &QAbstractAnimation::finished, - this, &QWidget::hide); + connect(m_heightAnimation, &QAbstractAnimation::finished, this, &QWidget::hide); } m_heightAnimation->start(QAbstractAnimation::DeleteWhenStopped); diff --git a/src/selectionmode/bottombar.h b/src/selectionmode/bottombar.h index 2ee05f39c5..3ad361ef66 100644 --- a/src/selectionmode/bottombar.h +++ b/src/selectionmode/bottombar.h @@ -24,7 +24,7 @@ class QUrl; namespace SelectionMode { - class BottomBarContentsContainer; +class BottomBarContentsContainer; /** * @brief A bar used in selection mode that serves various purposes depending on what the user is currently trying to do. diff --git a/src/selectionmode/bottombarcontentscontainer.cpp b/src/selectionmode/bottombarcontentscontainer.cpp index 522afcd01d..4619bcae07 100644 --- a/src/selectionmode/bottombarcontentscontainer.cpp +++ b/src/selectionmode/bottombarcontentscontainer.cpp @@ -25,9 +25,9 @@ using namespace SelectionMode; -BottomBarContentsContainer::BottomBarContentsContainer(KActionCollection *actionCollection, QWidget *parent) : - QWidget{parent}, - m_actionCollection{actionCollection} +BottomBarContentsContainer::BottomBarContentsContainer(KActionCollection *actionCollection, QWidget *parent) + : QWidget{parent} + , m_actionCollection{actionCollection} { // We will mostly interact with m_layout when changing the contents and not care about the other internal hierarchy. m_layout = new QHBoxLayout(this); @@ -38,7 +38,9 @@ void BottomBarContentsContainer::resetContents(BottomBar::Contents contents) emptyBarContents(); // A label is added in many of the methods below. We only know its size a bit later and if it should be hidden. - QTimer::singleShot(10, this, [this](){ updateExplanatoryLabelVisibility(); }); + QTimer::singleShot(10, this, [this]() { + updateExplanatoryLabelVisibility(); + }); Q_CHECK_PTR(m_actionCollection); m_contents = contents; @@ -155,8 +157,10 @@ void BottomBarContentsContainer::addCopyContents() m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to copy files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Copying"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -188,8 +192,10 @@ void BottomBarContentsContainer::addCopyLocationContents() m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to copy the location of files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Copying"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -201,14 +207,18 @@ void BottomBarContentsContainer::addCopyLocationContents() void BottomBarContentsContainer::addCopyToOtherViewContents() { + // clang-format off // i18n: "Copy over" refers to copying to the other split view area that is currently visible to the user. m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be copied over."), this); + // clang-format on m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to copy the location of files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Copying"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -225,8 +235,10 @@ void BottomBarContentsContainer::addCutContents() m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to cut files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Cutting"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -240,7 +252,7 @@ void BottomBarContentsContainer::addCutContents() // Connect the cut action as a second step. m_mainAction = ActionWithWidget(m_actionCollection->action(KStandardAction::name(KStandardAction::Cut)), cutButton); // Finally connect the lambda that actually changes the contents to the PasteContents. - connect(cutButton, &QAbstractButton::clicked, [this](){ + connect(cutButton, &QAbstractButton::clicked, [this]() { if (GeneralSettings::showPasteBarAfterCopying()) { resetContents(BottomBar::Contents::PasteContents); // resetContents() needs to be connected last because // it instantly deletes the button and then the other slots won't be called. @@ -253,13 +265,16 @@ void BottomBarContentsContainer::addCutContents() void BottomBarContentsContainer::addDeleteContents() { - m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be permanently deleted."), this); + m_explanatoryLabel = + new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be permanently deleted."), this); m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to delete files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -276,8 +291,10 @@ void BottomBarContentsContainer::addDuplicateContents() m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to duplicate files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Duplicating"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -290,9 +307,11 @@ void BottomBarContentsContainer::addDuplicateContents() void BottomBarContentsContainer::addGeneralContents() { if (!m_overflowButton) { + // clang-format off // i18n: This button appears in a bar if there isn't enough horizontal space to fit all the other buttons so please keep it short. // The small button opens a menu that contains the actions that didn't fit on the bar. m_overflowButton = new QPushButton{QIcon::fromTheme(QStringLiteral("view-more-symbolic")), i18nc("@action keep short", "More"), this}; + // clang-format on m_overflowButton->setMenu(new QMenu{m_overflowButton}); m_overflowButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::MinimumExpanding); // Makes sure it has the same height as the labeled buttons. m_layout->addWidget(m_overflowButton); @@ -335,14 +354,18 @@ void BottomBarContentsContainer::addGeneralContents() void BottomBarContentsContainer::addMoveToOtherViewContents() { + // clang-format off // i18n: "Move over" refers to moving to the other split view area that is currently visible to the user. m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be moved over."), this); + // clang-format on m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to copy the location of files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Moving"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -354,13 +377,16 @@ void BottomBarContentsContainer::addMoveToOtherViewContents() void BottomBarContentsContainer::addMoveToTrashContents() { - m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be moved to the Trash."), this); + m_explanatoryLabel = + new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be moved to the Trash."), this); m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process of moving files to the trash by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -373,9 +399,10 @@ void BottomBarContentsContainer::addMoveToTrashContents() void BottomBarContentsContainer::addPasteContents() { m_explanatoryLabel = new QLabel(xi18n("The selected files and folders were added to the Clipboard. " - "Now the Paste action can be used to transfer them from the Clipboard " - "to any other location. They can even be transferred to other applications by using their " - "respective Paste actions."), this); + "Now the Paste action can be used to transfer them from the Clipboard " + "to any other location. They can even be transferred to other applications by using their " + "respective Paste actions."), + this); m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); @@ -415,13 +442,17 @@ void BottomBarContentsContainer::addPasteContents() void BottomBarContentsContainer::addRenameContents() { - m_explanatoryLabel = new QLabel(i18nc("@info explains the next step in a process", "Select the file or folder that should be renamed.\nBulk renaming is possible when multiple items are selected."), this); + m_explanatoryLabel = new QLabel(i18nc("@info explains the next step in a process", + "Select the file or folder that should be renamed.\nBulk renaming is possible when multiple items are selected."), + this); m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); m_explanatoryLabel->setWordWrap(true); m_layout->addWidget(m_explanatoryLabel); + // clang-format off // i18n: Aborts the current step-by-step process to delete files by leaving the selection mode. auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Renaming"), this); + // clang-format on connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested); m_layout->addWidget(cancelButton); @@ -439,15 +470,15 @@ void BottomBarContentsContainer::emptyBarContents() QLayoutItem *grandChild; while ((grandChild = childLayout->takeAt(0)) != nullptr) { delete grandChild->widget(); // delete the widget - delete grandChild; // delete the layout item + delete grandChild; // delete the layout item } } delete child->widget(); // delete the widget - delete child; // delete the layout item + delete child; // delete the layout item } } -std::vector BottomBarContentsContainer::contextActionsFor(const KFileItemList& selectedItems, const QUrl& baseUrl) +std::vector BottomBarContentsContainer::contextActionsFor(const KFileItemList &selectedItems, const QUrl &baseUrl) { if (selectedItems.isEmpty()) { // There are no contextual actions to show for these items. @@ -483,7 +514,8 @@ std::vector BottomBarContentsContainer::contextActionsFor(const KFile // KHamburgerMenu would only be visible if there is no menu available anywhere on the user interface. This might be useful for recovery from // such a situation in theory but a bar with context dependent actions doesn't really seem like the right place for it. - Q_ASSERT(internalContextMenuActions.first()->icon().name() == m_actionCollection->action(KStandardAction::name(KStandardAction::HamburgerMenu))->icon().name()); + Q_ASSERT(internalContextMenuActions.first()->icon().name() + == m_actionCollection->action(KStandardAction::name(KStandardAction::HamburgerMenu))->icon().name()); internalContextMenuActions.removeFirst(); for (auto it = internalContextMenuActions.constBegin(); it != internalContextMenuActions.constEnd(); ++it) { @@ -529,7 +561,7 @@ int BottomBarContentsContainer::unusedSpace() const sumOfPreferredWidths += m_layout->itemAt(i)->sizeHint().width() + m_layout->spacing(); } return m_barWidth - sumOfPreferredWidths - 20; // We consider all space used when there are only 20 pixels left - // so there is some room to breath and not too much wonkyness while resizing. + // so there is some room to breath and not too much wonkyness while resizing. } void BottomBarContentsContainer::updateExplanatoryLabelVisibility() @@ -544,7 +576,7 @@ void BottomBarContentsContainer::updateExplanatoryLabelVisibility() m_explanatoryLabel->setVisible(unusedSpace() > m_explanatoryLabel->sizeHint().width() + 20); } } - +// clang-format off void BottomBarContentsContainer::updateMainActionButton(const KFileItemList& selectedItems) { if (!m_mainAction.widget()) { @@ -627,3 +659,4 @@ void BottomBarContentsContainer::updateMainActionButton(const KFileItemList& sel updateExplanatoryLabelVisibility(); } } +// clang-format on diff --git a/src/selectionmode/bottombarcontentscontainer.h b/src/selectionmode/bottombarcontentscontainer.h index 6cb66fcc1b..5602202587 100644 --- a/src/selectionmode/bottombarcontentscontainer.h +++ b/src/selectionmode/bottombarcontentscontainer.h @@ -52,7 +52,8 @@ public: return m_contents; }; - inline bool hasSomethingToShow() { + inline bool hasSomethingToShow() + { return contents() != BottomBar::GeneralContents || m_internalContextMenu; } diff --git a/src/selectionmode/singleclickselectionproxystyle.h b/src/selectionmode/singleclickselectionproxystyle.h index ece46cce6d..a0c1585d5d 100644 --- a/src/selectionmode/singleclickselectionproxystyle.h +++ b/src/selectionmode/singleclickselectionproxystyle.h @@ -21,8 +21,8 @@ namespace SelectionMode class SingleClickSelectionProxyStyle : public QProxyStyle { public: - inline int styleHint(StyleHint hint, const QStyleOption *option = nullptr, - const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override + inline int + styleHint(StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override { if (hint == QStyle::SH_ItemView_ActivateItemOnSingleClick) { return 0; diff --git a/src/selectionmode/topbar.cpp b/src/selectionmode/topbar.cpp index b2934a4d78..1981be4110 100644 --- a/src/selectionmode/topbar.cpp +++ b/src/selectionmode/topbar.cpp @@ -21,19 +21,20 @@ using namespace SelectionMode; -TopBar::TopBar(QWidget *parent) : - QWidget{parent} +TopBar::TopBar(QWidget *parent) + : QWidget{parent} { // Showing of this widget is normally animated. We hide it for now and make it small. hide(); setMaximumHeight(0); setToolTip(KToolTipHelper::whatsThisHintOnly()); - setWhatsThis(xi18nc("@info:whatsthis", "Selection ModeSelect files or folders to manage or manipulate them." - "Press on a file or folder to select it.Press on an already selected file or folder to deselect it." - "Pressing an empty area does not clear the selection." - "Selection rectangles (created by dragging from an empty area) invert the selection status of items within." - "The available action buttons at the bottom change depending on the current selection.")); + setWhatsThis(xi18nc("@info:whatsthis", + "Selection ModeSelect files or folders to manage or manipulate them." + "Press on a file or folder to select it.Press on an already selected file or folder to deselect it." + "Pressing an empty area does not clear the selection." + "Selection rectangles (created by dragging from an empty area) invert the selection status of items within." + "The available action buttons at the bottom change depending on the current selection.")); auto fillParentLayout = new QGridLayout(this); fillParentLayout->setContentsMargins(0, 0, 0, 0); @@ -54,10 +55,8 @@ TopBar::TopBar(QWidget *parent) : setMinimumWidth(0); - m_fullLabelString = i18nc("@info label above the view explaining the state", - "Selection Mode: Click on files or folders to select or deselect them."); - m_shortLabelString = i18nc("@info label above the view explaining the state", - "Selection Mode"); + m_fullLabelString = i18nc("@info label above the view explaining the state", "Selection Mode: Click on files or folders to select or deselect them."); + m_shortLabelString = i18nc("@info label above the view explaining the state", "Selection Mode"); m_label = new QLabel(contentsContainer); m_label->setMinimumWidth(0); BackgroundColorHelper::instance()->controlBackgroundColor(m_label); @@ -65,8 +64,7 @@ TopBar::TopBar(QWidget *parent) : m_closeButton = new QPushButton(QIcon::fromTheme(QStringLiteral("window-close-symbolic")), "", contentsContainer); m_closeButton->setText(i18nc("@action:button", "Exit Selection Mode")); m_closeButton->setFlat(true); - connect(m_closeButton, &QAbstractButton::clicked, - this, &TopBar::selectionModeLeavingRequested); + connect(m_closeButton, &QAbstractButton::clicked, this, &TopBar::selectionModeLeavingRequested); QHBoxLayout *layout = new QHBoxLayout(contentsContainer); auto contentsMargins = layout->contentsMargins(); @@ -89,9 +87,7 @@ void TopBar::setVisible(bool visible, Animated animated) m_heightAnimation->stop(); // deletes because of QAbstractAnimation::DeleteWhenStopped. } m_heightAnimation = new QPropertyAnimation(this, "maximumHeight"); - m_heightAnimation->setDuration(2 * - style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * - GlobalConfig::animationDurationFactor()); + m_heightAnimation->setDuration(2 * style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * GlobalConfig::animationDurationFactor()); m_heightAnimation->setStartValue(height()); m_heightAnimation->setEasingCurve(QEasingCurve::OutCubic); @@ -100,8 +96,7 @@ void TopBar::setVisible(bool visible, Animated animated) m_heightAnimation->setEndValue(m_preferredHeight); } else { m_heightAnimation->setEndValue(0); - connect(m_heightAnimation, &QAbstractAnimation::finished, - this, &QWidget::hide); + connect(m_heightAnimation, &QAbstractAnimation::finished, this, &QWidget::hide); } m_heightAnimation->start(QAbstractAnimation::DeleteWhenStopped); @@ -116,7 +111,9 @@ void TopBar::resizeEvent(QResizeEvent *resizeEvent) void TopBar::updateLabelString() { QFontMetrics fontMetrics = m_label->fontMetrics(); - if (fontMetrics.horizontalAdvance(m_fullLabelString) + m_closeButton->sizeHint().width() + style()->pixelMetric(QStyle::PM_LayoutLeftMargin) * 2 + style()->pixelMetric(QStyle::PM_LayoutRightMargin) * 2 < width()) { + if (fontMetrics.horizontalAdvance(m_fullLabelString) + m_closeButton->sizeHint().width() + style()->pixelMetric(QStyle::PM_LayoutLeftMargin) * 2 + + style()->pixelMetric(QStyle::PM_LayoutRightMargin) * 2 + < width()) { m_label->setText(m_fullLabelString); } else { m_label->setText(m_shortLabelString); diff --git a/src/settings/applyviewpropsjob.cpp b/src/settings/applyviewpropsjob.cpp index 430b511216..9de2affe67 100644 --- a/src/settings/applyviewpropsjob.cpp +++ b/src/settings/applyviewpropsjob.cpp @@ -11,12 +11,11 @@ #include "views/viewproperties.h" -ApplyViewPropsJob::ApplyViewPropsJob(const QUrl& dir, - const ViewProperties& viewProps) : - KIO::Job(), - m_viewProps(nullptr), - m_progress(0), - m_dir(dir) +ApplyViewPropsJob::ApplyViewPropsJob(const QUrl &dir, const ViewProperties &viewProps) + : KIO::Job() + , m_viewProps(nullptr) + , m_progress(0) + , m_dir(dir) { m_viewProps = new ViewProperties(dir); m_viewProps->setViewMode(viewProps.viewMode()); @@ -25,21 +24,20 @@ ApplyViewPropsJob::ApplyViewPropsJob(const QUrl& dir, m_viewProps->setSortRole(viewProps.sortRole()); m_viewProps->setSortOrder(viewProps.sortOrder()); - KIO::ListJob* listJob = KIO::listRecursive(dir, KIO::HideProgressInfo); - connect(listJob, &KIO::ListJob::entries, - this, &ApplyViewPropsJob::slotEntries); + KIO::ListJob *listJob = KIO::listRecursive(dir, KIO::HideProgressInfo); + connect(listJob, &KIO::ListJob::entries, this, &ApplyViewPropsJob::slotEntries); addSubjob(listJob); } ApplyViewPropsJob::~ApplyViewPropsJob() { - delete m_viewProps; // the properties are written by the destructor + delete m_viewProps; // the properties are written by the destructor m_viewProps = nullptr; } -void ApplyViewPropsJob::slotEntries(KIO::Job*, const KIO::UDSEntryList& list) +void ApplyViewPropsJob::slotEntries(KIO::Job *, const KIO::UDSEntryList &list) { - for (const KIO::UDSEntry& entry : list) { + for (const KIO::UDSEntry &entry : list) { const QString name = entry.stringValue(KIO::UDSEntry::UDS_NAME); if (name != QLatin1Char('.') && name != QLatin1String("..") && entry.isDir()) { ++m_progress; @@ -56,7 +54,7 @@ void ApplyViewPropsJob::slotEntries(KIO::Job*, const KIO::UDSEntryList& list) } } -void ApplyViewPropsJob::slotResult(KJob* job) +void ApplyViewPropsJob::slotResult(KJob *job) { if (job->error()) { setError(job->error()); @@ -64,4 +62,3 @@ void ApplyViewPropsJob::slotResult(KJob* job) } emitResult(); } - diff --git a/src/settings/applyviewpropsjob.h b/src/settings/applyviewpropsjob.h index 0e5b83f7ad..60432c12d6 100644 --- a/src/settings/applyviewpropsjob.h +++ b/src/settings/applyviewpropsjob.h @@ -47,16 +47,16 @@ public: * @param viewProps View properties for the directory \a dir including its * sub directories. */ - ApplyViewPropsJob(const QUrl& dir, const ViewProperties& viewProps); + ApplyViewPropsJob(const QUrl &dir, const ViewProperties &viewProps); ~ApplyViewPropsJob() override; int progress() const; private Q_SLOTS: - void slotResult(KJob* job) override; - void slotEntries(KIO::Job*, const KIO::UDSEntryList&); + void slotResult(KJob *job) override; + void slotEntries(KIO::Job *, const KIO::UDSEntryList &); private: - ViewProperties* m_viewProps; + ViewProperties *m_viewProps; int m_progress; QUrl m_dir; }; diff --git a/src/settings/contextmenu/contextmenusettingspage.cpp b/src/settings/contextmenu/contextmenusettingspage.cpp index 974ddb5317..2205fadd01 100644 --- a/src/settings/contextmenu/contextmenusettingspage.cpp +++ b/src/settings/contextmenu/contextmenusettingspage.cpp @@ -6,12 +6,12 @@ #include "contextmenusettingspage.h" +#include "dolphin_contextmenusettings.h" #include "dolphin_generalsettings.h" #include "dolphin_versioncontrolsettings.h" -#include "dolphin_contextmenusettings.h" +#include "global.h" #include "settings/serviceitemdelegate.h" #include "settings/servicemodel.h" -#include "global.h" #include #include @@ -26,49 +26,48 @@ #include #include -#include #include +#include +#include #include #include +#include #include #include #include #include -#include -#include namespace { - const bool ShowDeleteDefault = false; - const char VersionControlServicePrefix[] = "_version_control_"; - const char DeleteService[] = "_delete"; - const char CopyToMoveToService[] ="_copy_to_move_to"; +const bool ShowDeleteDefault = false; +const char VersionControlServicePrefix[] = "_version_control_"; +const char DeleteService[] = "_delete"; +const char CopyToMoveToService[] = "_copy_to_move_to"; - bool laterSelected = false; +bool laterSelected = false; } -ContextMenuSettingsPage::ContextMenuSettingsPage(QWidget* parent, - const KActionCollection* actions, - const QStringList& actionIds) : - SettingsPageBase(parent), - m_initialized(false), - m_serviceModel(nullptr), - m_sortModel(nullptr), - m_listView(nullptr), - m_enabledVcsPlugins(), - m_actions(actions), - m_actionIds(actionIds) +ContextMenuSettingsPage::ContextMenuSettingsPage(QWidget *parent, const KActionCollection *actions, const QStringList &actionIds) + : SettingsPageBase(parent) + , m_initialized(false) + , m_serviceModel(nullptr) + , m_sortModel(nullptr) + , m_listView(nullptr) + , m_enabledVcsPlugins() + , m_actions(actions) + , m_actionIds(actionIds) { - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); - QLabel* label = new QLabel(i18nc("@label:textbox", + QLabel *label = new QLabel(i18nc("@label:textbox", "Select which services should " - "be shown in the context menu:"), this); + "be shown in the context menu:"), + this); label->setWordWrap(true); m_searchLineEdit = new QLineEdit(this); m_searchLineEdit->setPlaceholderText(i18nc("@label:textbox", "Search...")); - connect(m_searchLineEdit, &QLineEdit::textChanged, this, [this](const QString &filter){ + connect(m_searchLineEdit, &QLineEdit::textChanged, this, [this](const QString &filter) { m_sortModel->setFilterFixedString(filter); }); @@ -94,14 +93,12 @@ ContextMenuSettingsPage::ContextMenuSettingsPage(QWidget* parent, #ifndef Q_OS_WIN using NewStuffButton = KNSWidgets::Button; - auto *downloadButton = new NewStuffButton(i18nc("@action:button", "Download New Services..."), - QStringLiteral("servicemenu.knsrc"), - this); + auto *downloadButton = new NewStuffButton(i18nc("@action:button", "Download New Services..."), QStringLiteral("servicemenu.knsrc"), this); connect(downloadButton, &NewStuffButton::dialogFinished, this, [this](const auto &changedEntries) { - if (!changedEntries.isEmpty()) { - m_serviceModel->clear(); - loadServices(); - } + if (!changedEntries.isEmpty()) { + m_serviceModel->clear(); + loadServices(); + } }); topLayout->addWidget(downloadButton); #endif // Q_OS_WIN @@ -110,10 +107,11 @@ ContextMenuSettingsPage::ContextMenuSettingsPage(QWidget* parent, std::sort(m_enabledVcsPlugins.begin(), m_enabledVcsPlugins.end()); } -ContextMenuSettingsPage::~ContextMenuSettingsPage() { +ContextMenuSettingsPage::~ContextMenuSettingsPage() +{ } -bool ContextMenuSettingsPage::entryVisible(const QString& id) +bool ContextMenuSettingsPage::entryVisible(const QString &id) { if (id == "add_to_places") { return ContextMenuSettings::showAddToPlaces(); @@ -135,7 +133,7 @@ bool ContextMenuSettingsPage::entryVisible(const QString& id) return false; } -void ContextMenuSettingsPage::setEntryVisible(const QString& id, bool visible) +void ContextMenuSettingsPage::setEntryVisible(const QString &id, bool visible) { if (id == "add_to_places") { ContextMenuSettings::setShowAddToPlaces(visible); @@ -201,16 +199,18 @@ void ContextMenuSettingsPage::applySettings() if (!laterSelected) { #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - KMessageBox::ButtonCode promptRestart = KMessageBox::questionTwoActions(window(), + KMessageBox::ButtonCode promptRestart = + KMessageBox::questionTwoActions(window(), #else - KMessageBox::ButtonCode promptRestart = KMessageBox::questionYesNo(window(), + KMessageBox::ButtonCode promptRestart = + KMessageBox::questionYesNo(window(), #endif - i18nc("@info", "Dolphin must be restarted to apply the " - "updated version control system settings."), - i18nc("@info", "Restart now?"), - KGuiItem(QApplication::translate("KStandardGuiItem", "&Restart"), QStringLiteral("dialog-restart")), - KGuiItem(QApplication::translate("KStandardGuiItem", "&Later"), QStringLiteral("dialog-later")) - ); + i18nc("@info", + "Dolphin must be restarted to apply the " + "updated version control system settings."), + i18nc("@info", "Restart now?"), + KGuiItem(QApplication::translate("KStandardGuiItem", "&Restart"), QStringLiteral("dialog-restart")), + KGuiItem(QApplication::translate("KStandardGuiItem", "&Later"), QStringLiteral("dialog-later"))); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) if (promptRestart == KMessageBox::ButtonCode::PrimaryAction) { #else @@ -227,19 +227,18 @@ void ContextMenuSettingsPage::applySettings() void ContextMenuSettingsPage::restoreDefaults() { - QAbstractItemModel* model = m_listView->model(); + QAbstractItemModel *model = m_listView->model(); for (int i = 0; i < model->rowCount(); ++i) { const QModelIndex index = model->index(i, 0); const QString service = model->data(index, ServiceModel::DesktopEntryNameRole).toString(); - const bool checked = !service.startsWith(VersionControlServicePrefix) - && service != QLatin1String(DeleteService) - && service != QLatin1String(CopyToMoveToService); + const bool checked = + !service.startsWith(VersionControlServicePrefix) && service != QLatin1String(DeleteService) && service != QLatin1String(CopyToMoveToService); model->setData(index, checked, Qt::CheckStateRole); } } -void ContextMenuSettingsPage::showEvent(QShowEvent* event) +void ContextMenuSettingsPage::showEvent(QShowEvent *event) { if (!event->spontaneous() && !m_initialized) { loadServices(); @@ -249,10 +248,7 @@ void ContextMenuSettingsPage::showEvent(QShowEvent* event) // Add "Show 'Delete' command" as service KSharedConfig::Ptr globalConfig = KSharedConfig::openConfig(QStringLiteral("kdeglobals"), KConfig::IncludeGlobals); KConfigGroup configGroup(globalConfig, "KDE"); - addRow(QStringLiteral("edit-delete"), - i18nc("@option:check", "Delete"), - DeleteService, - configGroup.readEntry("ShowDeleteCommand", ShowDeleteDefault)); + addRow(QStringLiteral("edit-delete"), i18nc("@option:check", "Delete"), DeleteService, configGroup.readEntry("ShowDeleteCommand", ShowDeleteDefault)); // Add "Show 'Copy To' and 'Move To' commands" as service addRow(QStringLiteral("edit-copy"), @@ -260,10 +256,10 @@ void ContextMenuSettingsPage::showEvent(QShowEvent* event) CopyToMoveToService, ContextMenuSettings::showCopyMoveMenu()); - if (m_actions){ + if (m_actions) { // Add other built-in actions - for (const QString& id : m_actionIds) { - const QAction* action = m_actions->action(id); + for (const QString &id : m_actionIds) { + const QAction *action = m_actions->action(id); if (action) { addRow(action->icon().name(), action->text(), id, entryVisible(id)); } @@ -304,9 +300,7 @@ void ContextMenuSettingsPage::loadServices() const bool addService = !action.noDisplay() && !action.isSeparator() && !isInServicesList(serviceName); if (addService) { - const QString itemName = subMenuName.isEmpty() - ? action.text() - : i18nc("@item:inmenu", "%1: %2", subMenuName, action.text()); + const QString itemName = subMenuName.isEmpty() ? action.text() : i18nc("@item:inmenu", "%1: %2", subMenuName, action.text()); const bool checked = showGroup.readEntry(serviceName, true); addRow(action.icon(), itemName, serviceName, checked); } @@ -350,10 +344,7 @@ void ContextMenuSettingsPage::loadVersionControlSystems() const QVector plugins = KPluginMetaData::findPlugins(QStringLiteral("dolphin/vcs")); for (const auto &plugin : plugins) { const QString pluginName = plugin.name(); - addRow(QStringLiteral("code-class"), - pluginName, - VersionControlServicePrefix + pluginName, - enabledPlugins.contains(pluginName)); + addRow(QStringLiteral("code-class"), pluginName, VersionControlServicePrefix + pluginName, enabledPlugins.contains(pluginName)); loadedPlugins += pluginName; } @@ -371,10 +362,7 @@ bool ContextMenuSettingsPage::isInServicesList(const QString &service) const return false; } -void ContextMenuSettingsPage::addRow(const QString &icon, - const QString &text, - const QString &value, - bool checked) +void ContextMenuSettingsPage::addRow(const QString &icon, const QString &text, const QString &value, bool checked) { m_serviceModel->insertRow(0); diff --git a/src/settings/contextmenu/contextmenusettingspage.h b/src/settings/contextmenu/contextmenusettingspage.h index a8fae08f67..6bdda1eafa 100644 --- a/src/settings/contextmenu/contextmenusettingspage.h +++ b/src/settings/contextmenu/contextmenusettingspage.h @@ -25,9 +25,7 @@ class ContextMenuSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit ContextMenuSettingsPage(QWidget* parent, - const KActionCollection* actions, - const QStringList& actionIds); + explicit ContextMenuSettingsPage(QWidget *parent, const KActionCollection *actions, const QStringList &actionIds); ~ContextMenuSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -37,7 +35,7 @@ public: void restoreDefaults() override; protected: - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; private Q_SLOTS: /** @@ -56,21 +54,18 @@ private: /** * Adds a row to the model of m_listView. */ - void addRow(const QString &icon, - const QString &text, - const QString &value, - bool checked); - bool entryVisible(const QString& id); - void setEntryVisible(const QString& id, bool visible); + void addRow(const QString &icon, const QString &text, const QString &value, bool checked); + bool entryVisible(const QString &id); + void setEntryVisible(const QString &id, bool visible); private: bool m_initialized; ServiceModel *m_serviceModel; QSortFilterProxyModel *m_sortModel; - QListView* m_listView; + QListView *m_listView; QLineEdit *m_searchLineEdit; QStringList m_enabledVcsPlugins; - const KActionCollection* m_actions; + const KActionCollection *m_actions; const QStringList m_actionIds; }; diff --git a/src/settings/contextmenu/servicemenuinstaller/servicemenuinstaller.cpp b/src/settings/contextmenu/servicemenuinstaller/servicemenuinstaller.cpp index 9a6d2f6d6f..acee97cf1d 100644 --- a/src/settings/contextmenu/servicemenuinstaller/servicemenuinstaller.cpp +++ b/src/settings/contextmenu/servicemenuinstaller/servicemenuinstaller.cpp @@ -4,30 +4,29 @@ * SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "../../../config-dolphin.h" -Q_GLOBAL_STATIC_WITH_ARGS(QStringList, binaryPackages, ({QLatin1String("application/vnd.debian.binary-package"), - QLatin1String("application/x-rpm"), - QLatin1String("application/x-xz"), - QLatin1String("application/zstd")})) +Q_GLOBAL_STATIC_WITH_ARGS(QStringList, + binaryPackages, + ({QLatin1String("application/vnd.debian.binary-package"), + QLatin1String("application/x-rpm"), + QLatin1String("application/x-xz"), + QLatin1String("application/zstd")})) -enum PackageOperation { - Install, - Uninstall -}; +enum PackageOperation { Install, Uninstall }; #if HAVE_PACKAGEKIT #include @@ -41,7 +40,7 @@ enum PackageOperation { Q_NORETURN void fail(const QString &str) { qCritical() << str; - const QStringList args = {"--detailederror" ,i18n("Dolphin service menu installation failed"), str}; + const QStringList args = {"--detailederror", i18n("Dolphin service menu installation failed"), str}; QProcess::startDetached("kdialog", args); exit(1); @@ -59,20 +58,18 @@ void packageKitInstall(const QString &fileName) PackageKit::Transaction *transaction = PackageKit::Daemon::installFile(fileName, PackageKit::Transaction::TransactionFlagNone); const auto exitWithError = [=](PackageKit::Transaction::Error, const QString &details) { - fail(details); + fail(details); }; - QObject::connect(transaction, &PackageKit::Transaction::finished, - [=](PackageKit::Transaction::Exit status, uint) { - if (status == PackageKit::Transaction::ExitSuccess) { - exit(0); - } - // Fallback error handling - QTimer::singleShot(500, [=](){ - fail(i18n("Failed to install \"%1\", exited with status \"%2\"", - fileName, QVariant::fromValue(status).toString())); - }); - }); + QObject::connect(transaction, &PackageKit::Transaction::finished, [=](PackageKit::Transaction::Exit status, uint) { + if (status == PackageKit::Transaction::ExitSuccess) { + exit(0); + } + // Fallback error handling + QTimer::singleShot(500, [=]() { + fail(i18n("Failed to install \"%1\", exited with status \"%2\"", fileName, QVariant::fromValue(status).toString())); + }); + }); QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError); } @@ -88,25 +85,22 @@ void packageKitUninstall(const QString &fileName) }; PackageKit::Transaction *transaction = PackageKit::Daemon::getDetailsLocal(fileName); - QObject::connect(transaction, &PackageKit::Transaction::details, - [=](const PackageKit::Details &details) { - PackageKit::Transaction *transaction = PackageKit::Daemon::removePackage(details.packageId()); - QObject::connect(transaction, &PackageKit::Transaction::finished, uninstallLambda); - QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError); - }); + QObject::connect(transaction, &PackageKit::Transaction::details, [=](const PackageKit::Details &details) { + PackageKit::Transaction *transaction = PackageKit::Daemon::removePackage(details.packageId()); + QObject::connect(transaction, &PackageKit::Transaction::finished, uninstallLambda); + QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError); + }); QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError); // Fallback error handling - QObject::connect(transaction, &PackageKit::Transaction::finished, - [=](PackageKit::Transaction::Exit status, uint) { - if (status != PackageKit::Transaction::ExitSuccess) { - QTimer::singleShot(500, [=]() { - fail(i18n("Failed to uninstall \"%1\", exited with status \"%2\"", - fileName, QVariant::fromValue(status).toString())); - }); - } - }); - } + QObject::connect(transaction, &PackageKit::Transaction::finished, [=](PackageKit::Transaction::Exit status, uint) { + if (status != PackageKit::Transaction::ExitSuccess) { + QTimer::singleShot(500, [=]() { + fail(i18n("Failed to uninstall \"%1\", exited with status \"%2\"", fileName, QVariant::fromValue(status).toString())); + }); + } + }); +} #endif Q_NORETURN void packageKit(PackageOperation operation, const QString &fileName) @@ -131,41 +125,49 @@ Q_NORETURN void packageKit(PackageOperation operation, const QString &fileName) #endif } -struct UncompressCommand -{ +struct UncompressCommand { QString command; QStringList args1; QStringList args2; }; -enum ScriptExecution{ - Process, - Konsole -}; +enum ScriptExecution { Process, Konsole }; void runUncompress(const QString &inputPath, const QString &outputPath) { QVector> mimeTypeToCommand; - mimeTypeToCommand.append({{"application/x-tar", "application/tar", "application/x-gtar", "multipart/x-tar"}, - UncompressCommand({"tar", {"-xf"}, {"-C"}})}); - mimeTypeToCommand.append({{"application/x-gzip", "application/gzip", - "application/x-gzip-compressed-tar", "application/gzip-compressed-tar", - "application/x-gzip-compressed", "application/gzip-compressed", - "application/tgz", "application/x-compressed-tar", - "application/x-compressed-gtar", "file/tgz", - "multipart/x-tar-gz", "application/x-gunzip", "application/gzipped", + mimeTypeToCommand.append({{"application/x-tar", "application/tar", "application/x-gtar", "multipart/x-tar"}, UncompressCommand({"tar", {"-xf"}, {"-C"}})}); + mimeTypeToCommand.append({{"application/x-gzip", + "application/gzip", + "application/x-gzip-compressed-tar", + "application/gzip-compressed-tar", + "application/x-gzip-compressed", + "application/gzip-compressed", + "application/tgz", + "application/x-compressed-tar", + "application/x-compressed-gtar", + "file/tgz", + "multipart/x-tar-gz", + "application/x-gunzip", + "application/gzipped", "gzip/document"}, UncompressCommand({"tar", {"-zxf"}, {"-C"}})}); - mimeTypeToCommand.append({{"application/bzip", "application/bzip2", "application/x-bzip", - "application/x-bzip2", "application/bzip-compressed", - "application/bzip2-compressed", "application/x-bzip-compressed", - "application/x-bzip2-compressed", "application/bzip-compressed-tar", - "application/bzip2-compressed-tar", "application/x-bzip-compressed-tar", - "application/x-bzip2-compressed-tar", "application/x-bz2"}, + mimeTypeToCommand.append({{"application/bzip", + "application/bzip2", + "application/x-bzip", + "application/x-bzip2", + "application/bzip-compressed", + "application/bzip2-compressed", + "application/x-bzip-compressed", + "application/x-bzip2-compressed", + "application/bzip-compressed-tar", + "application/bzip2-compressed-tar", + "application/x-bzip-compressed-tar", + "application/x-bzip2-compressed-tar", + "application/x-bz2"}, UncompressCommand({"tar", {"-jxf"}, {"-C"}})}); - mimeTypeToCommand.append({{"application/zip", "application/x-zip", "application/x-zip-compressed", - "multipart/x-zip"}, - UncompressCommand({"unzip", {}, {"-d"}})}); + mimeTypeToCommand.append( + {{"application/zip", "application/x-zip", "application/x-zip-compressed", "multipart/x-zip"}, UncompressCommand({"unzip", {}, {"-d"}})}); const auto mime = QMimeDatabase().mimeTypeForFile(inputPath).name(); @@ -182,17 +184,13 @@ void runUncompress(const QString &inputPath, const QString &outputPath) } QProcess process; - process.start( - command.command, - QStringList() << command.args1 << inputPath << command.args2 << outputPath, - QIODevice::NotOpen); + process.start(command.command, QStringList() << command.args1 << inputPath << command.args2 << outputPath, QIODevice::NotOpen); if (!process.waitForStarted()) { fail(i18n("Failed to run uncompressor command for %1", inputPath)); } if (!process.waitForFinished()) { - fail( - i18n("Process did not finish in reasonable time: %1 %2", process.program(), process.arguments().join(" "))); + fail(i18n("Process did not finish in reasonable time: %1 %2", process.program(), process.arguments().join(" "))); } if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) { @@ -224,7 +222,11 @@ bool runScriptOnce(const QString &path, const QStringList &args, ScriptExecution bashCommand.append("|| $SHELL"); // If the install script fails a shell opens and the user can fix the problem // without an error konsole closes - process.start("konsole", QStringList() << "-e" << "bash" << "-c" << bashCommand, QIODevice::NotOpen); + process.start("konsole", + QStringList() << "-e" + << "bash" + << "-c" << bashCommand, + QIODevice::NotOpen); } else { process.start(path, args, QIODevice::NotOpen); } @@ -267,9 +269,10 @@ bool runScriptVariants(const QString &path, bool hasArgVariants, const QStringLi return true; } - errorText = i18nc( - "%2 = comma separated list of arguments", - "Installer script %1 failed, tried arguments \"%2\".", path, argVariants.join(i18nc("Separator between arguments", "\", \""))); + errorText = i18nc("%2 = comma separated list of arguments", + "Installer script %1 failed, tried arguments \"%2\".", + path, + argVariants.join(i18nc("Separator between arguments", "\", \""))); return false; } @@ -396,8 +399,7 @@ bool cmdUninstall(const QString &archive, QString &errorText) } else { // If "deinstall" is missing, try "install --uninstall" QString installerPath; - const QStringList basenames2 = {"install-it.sh", "install-it", "installKDE4.sh", - "installKDE4", "install.sh", "install"}; + const QStringList basenames2 = {"install-it.sh", "install-it", "installKDE4.sh", "installKDE4", "install.sh", "install"}; for (const auto &basename : basenames2) { const auto path = findRecursive(dir, basename); if (!path.isEmpty()) { @@ -407,8 +409,7 @@ bool cmdUninstall(const QString &archive, QString &errorText) } if (!installerPath.isEmpty()) { - const bool ok = runScriptVariants(installerPath, true, - {"--remove", "--delete", "--uninstall", "--deinstall"}, errorText); + const bool ok = runScriptVariants(installerPath, true, {"--remove", "--delete", "--uninstall", "--deinstall"}, errorText); if (!ok) { return ok; } diff --git a/src/settings/dolphinsettingsdialog.cpp b/src/settings/dolphinsettingsdialog.cpp index eed2f51557..ec92cb6353 100644 --- a/src/settings/dolphinsettingsdialog.cpp +++ b/src/settings/dolphinsettingsdialog.cpp @@ -6,15 +6,15 @@ #include "dolphinsettingsdialog.h" +#include "config-dolphin.h" +#include "contextmenu/contextmenusettingspage.h" #include "dolphin_generalsettings.h" #include "dolphinmainwindow.h" #include "general/generalsettingspage.h" #include "navigation/navigationsettingspage.h" -#include "contextmenu/contextmenusettingspage.h" #include "startup/startupsettingspage.h" #include "trash/trashsettingspage.h" #include "viewmodes/viewsettingspage.h" -#include "config-dolphin.h" #if HAVE_KUSERFEEDBACK #include "userfeedback/dolphinfeedbackprovider.h" #include "userfeedback/userfeedbacksettingspage.h" @@ -22,18 +22,18 @@ #include #include -#include #include +#include #include #include #include -DolphinSettingsDialog::DolphinSettingsDialog(const QUrl& url, QWidget* parent, KActionCollection* actions) : - KPageDialog(parent), - m_pages(), - m_unsavedChanges(false) +DolphinSettingsDialog::DolphinSettingsDialog(const QUrl &url, QWidget *parent, KActionCollection *actions) + : KPageDialog(parent) + , m_pages() + , m_unsavedChanges(false) { const QSize minSize = minimumSize(); @@ -41,8 +41,7 @@ DolphinSettingsDialog::DolphinSettingsDialog(const QUrl& url, QWidget* parent, K setFaceType(List); setWindowTitle(i18nc("@title:window", "Configure")); - QDialogButtonBox* box = new QDialogButtonBox(QDialogButtonBox::Ok - | QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); + QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); box->button(QDialogButtonBox::Apply)->setEnabled(false); box->button(QDialogButtonBox::Ok)->setDefault(true); setButtonBox(box); @@ -52,64 +51,58 @@ DolphinSettingsDialog::DolphinSettingsDialog(const QUrl& url, QWidget* parent, K connect(box->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, this, &DolphinSettingsDialog::restoreDefaults); // General - GeneralSettingsPage* generalSettingsPage = new GeneralSettingsPage(url, this); - KPageWidgetItem* generalSettingsFrame = addPage(generalSettingsPage, - i18nc("@title:group General settings", "General")); + GeneralSettingsPage *generalSettingsPage = new GeneralSettingsPage(url, this); + KPageWidgetItem *generalSettingsFrame = addPage(generalSettingsPage, i18nc("@title:group General settings", "General")); generalSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("system-file-manager"))); connect(generalSettingsPage, &GeneralSettingsPage::changed, this, &DolphinSettingsDialog::enableApply); // Startup - StartupSettingsPage* startupSettingsPage = new StartupSettingsPage(url, this); - KPageWidgetItem* startupSettingsFrame = addPage(startupSettingsPage, - i18nc("@title:group", "Startup")); + StartupSettingsPage *startupSettingsPage = new StartupSettingsPage(url, this); + KPageWidgetItem *startupSettingsFrame = addPage(startupSettingsPage, i18nc("@title:group", "Startup")); startupSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-launch-feedback"))); connect(startupSettingsPage, &StartupSettingsPage::changed, this, &DolphinSettingsDialog::enableApply); // View Modes - ViewSettingsPage* viewSettingsPage = new ViewSettingsPage(this); - KPageWidgetItem* viewSettingsFrame = addPage(viewSettingsPage, - i18nc("@title:group", "View Modes")); + ViewSettingsPage *viewSettingsPage = new ViewSettingsPage(this); + KPageWidgetItem *viewSettingsFrame = addPage(viewSettingsPage, i18nc("@title:group", "View Modes")); viewSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-icons"))); connect(viewSettingsPage, &ViewSettingsPage::changed, this, &DolphinSettingsDialog::enableApply); // Navigation - NavigationSettingsPage* navigationSettingsPage = new NavigationSettingsPage(this); - KPageWidgetItem* navigationSettingsFrame = addPage(navigationSettingsPage, - i18nc("@title:group", "Navigation")); + NavigationSettingsPage *navigationSettingsPage = new NavigationSettingsPage(this); + KPageWidgetItem *navigationSettingsFrame = addPage(navigationSettingsPage, i18nc("@title:group", "Navigation")); navigationSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-navigation"))); connect(navigationSettingsPage, &NavigationSettingsPage::changed, this, &DolphinSettingsDialog::enableApply); // Context Menu - auto contextMenuSettingsPage = new ContextMenuSettingsPage(this, actions, { - QStringLiteral("add_to_places"), - QStringLiteral("sort"), - QStringLiteral("view_mode"), - QStringLiteral("open_in_new_tab"), - QStringLiteral("open_in_new_window"), - QStringLiteral("copy_location"), - QStringLiteral("duplicate"), - QStringLiteral("open_terminal_here") - }); - KPageWidgetItem* contextMenuSettingsFrame = addPage(contextMenuSettingsPage, - i18nc("@title:group", "Context Menu")); + auto contextMenuSettingsPage = new ContextMenuSettingsPage(this, + actions, + {QStringLiteral("add_to_places"), + QStringLiteral("sort"), + QStringLiteral("view_mode"), + QStringLiteral("open_in_new_tab"), + QStringLiteral("open_in_new_window"), + QStringLiteral("copy_location"), + QStringLiteral("duplicate"), + QStringLiteral("open_terminal_here")}); + KPageWidgetItem *contextMenuSettingsFrame = addPage(contextMenuSettingsPage, i18nc("@title:group", "Context Menu")); contextMenuSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-menu-edit"))); connect(contextMenuSettingsPage, &ContextMenuSettingsPage::changed, this, &DolphinSettingsDialog::enableApply); // Trash - SettingsPageBase* trashSettingsPage = nullptr; + SettingsPageBase *trashSettingsPage = nullptr; #ifndef Q_OS_WIN trashSettingsPage = createTrashSettingsPage(this); #endif if (trashSettingsPage) { - trashSettings = addPage(trashSettingsPage, - i18nc("@title:group", "Trash")); + trashSettings = addPage(trashSettingsPage, i18nc("@title:group", "Trash")); trashSettings->setIcon(QIcon::fromTheme(QStringLiteral("user-trash"))); connect(trashSettingsPage, &TrashSettingsPage::changed, this, &DolphinSettingsDialog::enableApply); } #if HAVE_KUSERFEEDBACK // User Feedback - UserFeedbackSettingsPage* feedbackSettingsPage = nullptr; + UserFeedbackSettingsPage *feedbackSettingsPage = nullptr; if (DolphinFeedbackProvider::instance()->isEnabled()) { feedbackSettingsPage = new UserFeedbackSettingsPage(this); auto feedbackSettingsFrame = addPage(feedbackSettingsPage, i18nc("@title:group", "User Feedback")); @@ -150,13 +143,13 @@ void DolphinSettingsDialog::enableApply() void DolphinSettingsDialog::applySettings() { - for (SettingsPageBase* page : qAsConst(m_pages)) { + for (SettingsPageBase *page : qAsConst(m_pages)) { page->applySettings(); } Q_EMIT settingsChanged(); - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); if (settings->modifiedStartupSettings()) { // Reset the modified startup settings hint. The changed startup settings // have been applied already due to emitting settingsChanged(). @@ -169,12 +162,12 @@ void DolphinSettingsDialog::applySettings() void DolphinSettingsDialog::restoreDefaults() { - for (SettingsPageBase* page : qAsConst(m_pages)) { + for (SettingsPageBase *page : qAsConst(m_pages)) { page->restoreDefaults(); } } -void DolphinSettingsDialog::closeEvent(QCloseEvent* event) +void DolphinSettingsDialog::closeEvent(QCloseEvent *event) { if (!m_unsavedChanges) { event->accept(); @@ -186,35 +179,34 @@ void DolphinSettingsDialog::closeEvent(QCloseEvent* event) #else const auto response = KMessageBox::warningYesNoCancel(this, #endif - i18n("You have unsaved changes. Do you want to apply the changes or discard them?"), - i18n("Warning"), - KStandardGuiItem::save(), - KStandardGuiItem::discard(), - KStandardGuiItem::cancel()); + i18n("You have unsaved changes. Do you want to apply the changes or discard them?"), + i18n("Warning"), + KStandardGuiItem::save(), + KStandardGuiItem::discard(), + KStandardGuiItem::cancel()); switch (response) { #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - case KMessageBox::PrimaryAction: + case KMessageBox::PrimaryAction: #else - case KMessageBox::Yes: + case KMessageBox::Yes: #endif - applySettings(); - Q_FALLTHROUGH(); + applySettings(); + Q_FALLTHROUGH(); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - case KMessageBox::SecondaryAction: + case KMessageBox::SecondaryAction: #else - case KMessageBox::No: + case KMessageBox::No: #endif - event->accept(); - break; - case KMessageBox::Cancel: - event->ignore(); - break; - default: - break; + event->accept(); + break; + case KMessageBox::Cancel: + event->ignore(); + break; + default: + break; } } - SettingsPageBase *DolphinSettingsDialog::createTrashSettingsPage(QWidget *parent) { if (!KAuthorized::authorizeControlModule(QStringLiteral("kcmtrash.desktop"))) { diff --git a/src/settings/dolphinsettingsdialog.h b/src/settings/dolphinsettingsdialog.h index f9a5652eaa..f0322c5f0c 100644 --- a/src/settings/dolphinsettingsdialog.h +++ b/src/settings/dolphinsettingsdialog.h @@ -7,8 +7,8 @@ #ifndef DOLPHINSETTINGSDIALOG_H #define DOLPHINSETTINGSDIALOG_H -#include #include +#include class QUrl; class SettingsPageBase; @@ -23,10 +23,10 @@ class DolphinSettingsDialog : public KPageDialog Q_OBJECT public: - explicit DolphinSettingsDialog(const QUrl& url, QWidget* parent = nullptr, KActionCollection* actions = {}); + explicit DolphinSettingsDialog(const QUrl &url, QWidget *parent = nullptr, KActionCollection *actions = {}); ~DolphinSettingsDialog() override; - KPageWidgetItem* trashSettings; + KPageWidgetItem *trashSettings; Q_SIGNALS: void settingsChanged(); @@ -38,12 +38,12 @@ private Q_SLOTS: void restoreDefaults(); protected: - void closeEvent(QCloseEvent* event) override; + void closeEvent(QCloseEvent *event) override; private: static SettingsPageBase *createTrashSettingsPage(QWidget *parent); - QList m_pages; + QList m_pages; bool m_unsavedChanges; }; diff --git a/src/settings/general/behaviorsettingspage.cpp b/src/settings/general/behaviorsettingspage.cpp index 4e78447c7d..33f65b599b 100644 --- a/src/settings/general/behaviorsettingspage.cpp +++ b/src/settings/general/behaviorsettingspage.cpp @@ -17,43 +17,40 @@ #include #include -BehaviorSettingsPage::BehaviorSettingsPage(const QUrl& url, QWidget* parent) : - SettingsPageBase(parent), - m_url(url), - m_localViewProps(nullptr), - m_globalViewProps(nullptr), - m_showToolTips(nullptr), - m_showSelectionToggle(nullptr), - m_naturalSorting(nullptr), - m_caseSensitiveSorting(nullptr), - m_caseInsensitiveSorting(nullptr), - m_renameInline(nullptr), - m_useTabForSplitViewSwitch(nullptr) +BehaviorSettingsPage::BehaviorSettingsPage(const QUrl &url, QWidget *parent) + : SettingsPageBase(parent) + , m_url(url) + , m_localViewProps(nullptr) + , m_globalViewProps(nullptr) + , m_showToolTips(nullptr) + , m_showSelectionToggle(nullptr) + , m_naturalSorting(nullptr) + , m_caseSensitiveSorting(nullptr) + , m_caseInsensitiveSorting(nullptr) + , m_renameInline(nullptr) + , m_useTabForSplitViewSwitch(nullptr) { - QFormLayout* topLayout = new QFormLayout(this); - + QFormLayout *topLayout = new QFormLayout(this); // View properties m_globalViewProps = new QRadioButton(i18nc("@option:radio", "Use common display style for all folders")); m_localViewProps = new QRadioButton(i18nc("@option:radio", "Remember display style for each folder")); m_localViewProps->setToolTip(i18nc("@info", "Dolphin will create a hidden .directory file in each folder you change view properties for.")); - QButtonGroup* viewGroup = new QButtonGroup(this); + QButtonGroup *viewGroup = new QButtonGroup(this); viewGroup->addButton(m_globalViewProps); viewGroup->addButton(m_localViewProps); topLayout->addRow(i18nc("@title:group", "View: "), m_globalViewProps); topLayout->addRow(QString(), m_localViewProps); - topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed)); - // Sorting properties m_naturalSorting = new QRadioButton(i18nc("option:radio", "Natural")); m_caseInsensitiveSorting = new QRadioButton(i18nc("option:radio", "Alphabetical, case insensitive")); m_caseSensitiveSorting = new QRadioButton(i18nc("option:radio", "Alphabetical, case sensitive")); - QButtonGroup* sortingModeGroup = new QButtonGroup(this); + QButtonGroup *sortingModeGroup = new QButtonGroup(this); sortingModeGroup->addButton(m_naturalSorting); sortingModeGroup->addButton(m_caseInsensitiveSorting); sortingModeGroup->addButton(m_caseSensitiveSorting); @@ -61,10 +58,8 @@ BehaviorSettingsPage::BehaviorSettingsPage(const QUrl& url, QWidget* parent) : topLayout->addRow(QString(), m_caseInsensitiveSorting); topLayout->addRow(QString(), m_caseSensitiveSorting); - topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed)); - #if HAVE_BALOO // 'Show tooltips' m_showToolTips = new QCheckBox(i18nc("@option:check", "Show tooltips")); @@ -114,8 +109,8 @@ BehaviorSettingsPage::~BehaviorSettingsPage() void BehaviorSettingsPage::applySettings() { - GeneralSettings* settings = GeneralSettings::self(); - ViewProperties props(m_url); // read current view properties + GeneralSettings *settings = GeneralSettings::self(); + ViewProperties props(m_url); // read current view properties const bool useGlobalViewProps = m_globalViewProps->isChecked(); settings->setGlobalViewProps(useGlobalViewProps); @@ -141,7 +136,7 @@ void BehaviorSettingsPage::applySettings() void BehaviorSettingsPage::restoreDefaults() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->useDefaults(true); loadSettings(); settings->useDefaults(false); diff --git a/src/settings/general/behaviorsettingspage.h b/src/settings/general/behaviorsettingspage.h index b054e6d35e..ba8ce63843 100644 --- a/src/settings/general/behaviorsettingspage.h +++ b/src/settings/general/behaviorsettingspage.h @@ -23,7 +23,7 @@ class BehaviorSettingsPage : public SettingsPageBase Q_OBJECT public: - BehaviorSettingsPage(const QUrl &url, QWidget* parent); + BehaviorSettingsPage(const QUrl &url, QWidget *parent); ~BehaviorSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -34,26 +34,26 @@ public: private: void loadSettings(); - void setSortingChoiceValue(GeneralSettings* settings); + void setSortingChoiceValue(GeneralSettings *settings); void loadSortingChoiceSettings(); private: QUrl m_url; - QRadioButton* m_localViewProps; - QRadioButton* m_globalViewProps; + QRadioButton *m_localViewProps; + QRadioButton *m_globalViewProps; - QCheckBox* m_showToolTips; - QLabel* m_configureToolTips; - QCheckBox* m_showSelectionToggle; + QCheckBox *m_showToolTips; + QLabel *m_configureToolTips; + QCheckBox *m_showSelectionToggle; - QRadioButton* m_naturalSorting; - QRadioButton* m_caseSensitiveSorting; - QRadioButton* m_caseInsensitiveSorting; + QRadioButton *m_naturalSorting; + QRadioButton *m_caseSensitiveSorting; + QRadioButton *m_caseInsensitiveSorting; - QCheckBox* m_renameInline; - QCheckBox* m_useTabForSplitViewSwitch; - QCheckBox* m_closeActiveSplitView; + QCheckBox *m_renameInline; + QCheckBox *m_useTabForSplitViewSwitch; + QCheckBox *m_closeActiveSplitView; }; #endif diff --git a/src/settings/general/configurepreviewplugindialog.cpp b/src/settings/general/configurepreviewplugindialog.cpp index 5aa3f9d39f..a391812dfd 100644 --- a/src/settings/general/configurepreviewplugindialog.cpp +++ b/src/settings/general/configurepreviewplugindialog.cpp @@ -21,17 +21,15 @@ #include #include -ConfigurePreviewPluginDialog::ConfigurePreviewPluginDialog(const QString& pluginName, - const QString& desktopEntryName, - QWidget* parent) : - QDialog(parent) +ConfigurePreviewPluginDialog::ConfigurePreviewPluginDialog(const QString &pluginName, const QString &desktopEntryName, QWidget *parent) + : QDialog(parent) { QSharedPointer previewPlugin; const QString pluginPath = QPluginLoader(desktopEntryName).fileName(); if (!pluginPath.isEmpty()) { newCreator create = (newCreator)QLibrary::resolve(pluginPath, "new_creator"); if (create) { - previewPlugin.reset(dynamic_cast(create())); + previewPlugin.reset(dynamic_cast(create())); } } diff --git a/src/settings/general/configurepreviewplugindialog.h b/src/settings/general/configurepreviewplugindialog.h index 2da7a3afd2..66504cce2e 100644 --- a/src/settings/general/configurepreviewplugindialog.h +++ b/src/settings/general/configurepreviewplugindialog.h @@ -28,9 +28,7 @@ public: * widget. * @param parent Parent widget. */ - ConfigurePreviewPluginDialog(const QString& pluginName, - const QString& desktopEntryName, - QWidget* parent); + ConfigurePreviewPluginDialog(const QString &pluginName, const QString &desktopEntryName, QWidget *parent); ~ConfigurePreviewPluginDialog() override = default; }; #endif // KIOWIDGETS_BUILD_DEPRECATED_SINCE diff --git a/src/settings/general/confirmationssettingspage.cpp b/src/settings/general/confirmationssettingspage.cpp index af4e2877f9..106a420587 100644 --- a/src/settings/general/confirmationssettingspage.cpp +++ b/src/settings/general/confirmationssettingspage.cpp @@ -13,61 +13,55 @@ #include #include -#include #include +#include #include -namespace { - enum ScriptExecution - { - AlwaysAsk = 0, - Open = 1, - Execute = 2 - }; +namespace +{ +enum ScriptExecution { AlwaysAsk = 0, Open = 1, Execute = 2 }; - const bool ConfirmEmptyTrash = true; - const bool ConfirmTrash = false; - const bool ConfirmDelete = true; - const int ConfirmScriptExecution = ScriptExecution::AlwaysAsk; +const bool ConfirmEmptyTrash = true; +const bool ConfirmTrash = false; +const bool ConfirmDelete = true; +const int ConfirmScriptExecution = ScriptExecution::AlwaysAsk; } -ConfirmationsSettingsPage::ConfirmationsSettingsPage(QWidget* parent) : - SettingsPageBase(parent), - m_confirmMoveToTrash(nullptr), - m_confirmEmptyTrash(nullptr), - m_confirmDelete(nullptr), +ConfirmationsSettingsPage::ConfirmationsSettingsPage(QWidget *parent) + : SettingsPageBase(parent) + , m_confirmMoveToTrash(nullptr) + , m_confirmEmptyTrash(nullptr) + , m_confirmDelete(nullptr) + , #if HAVE_TERMINAL - m_confirmClosingTerminalRunningProgram(nullptr), + m_confirmClosingTerminalRunningProgram(nullptr) + , #endif m_confirmClosingMultipleTabs(nullptr) { - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); - QLabel* confirmLabelKde = new QLabel(i18nc("@title:group", "Ask for confirmation in all KDE applications when:"), this); + QLabel *confirmLabelKde = new QLabel(i18nc("@title:group", "Ask for confirmation in all KDE applications when:"), this); confirmLabelKde->setWordWrap(true); - m_confirmMoveToTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when", - "Moving files or folders to trash"), this); - m_confirmEmptyTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when", - "Emptying trash"), this); - m_confirmDelete = new QCheckBox(i18nc("@option:check Ask for confirmation when", - "Deleting files or folders"), this); + m_confirmMoveToTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when", "Moving files or folders to trash"), this); + m_confirmEmptyTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when", "Emptying trash"), this); + m_confirmDelete = new QCheckBox(i18nc("@option:check Ask for confirmation when", "Deleting files or folders"), this); - QLabel* confirmLabelDolphin = new QLabel(i18nc("@title:group", "Ask for confirmation in Dolphin when:"), this); + QLabel *confirmLabelDolphin = new QLabel(i18nc("@title:group", "Ask for confirmation in Dolphin when:"), this); confirmLabelDolphin->setWordWrap(true); - m_confirmClosingMultipleTabs = new QCheckBox(i18nc("@option:check Ask for confirmation in Dolphin when", - "Closing windows with multiple tabs"), this); + m_confirmClosingMultipleTabs = new QCheckBox(i18nc("@option:check Ask for confirmation in Dolphin when", "Closing windows with multiple tabs"), this); #if HAVE_TERMINAL - m_confirmClosingTerminalRunningProgram = new QCheckBox(i18nc("@option:check Ask for confirmation when", - "Closing windows with a program running in the Terminal panel"), this); + m_confirmClosingTerminalRunningProgram = + new QCheckBox(i18nc("@option:check Ask for confirmation when", "Closing windows with a program running in the Terminal panel"), this); #endif - QHBoxLayout* executableScriptLayout = new QHBoxLayout(); - QLabel* executableScriptLabel = new QLabel(i18nc("@title:group", "When opening an executable file:"), this); + QHBoxLayout *executableScriptLayout = new QHBoxLayout(); + QLabel *executableScriptLabel = new QLabel(i18nc("@title:group", "When opening an executable file:"), this); confirmLabelKde->setWordWrap(true); executableScriptLayout->addWidget(executableScriptLabel); @@ -132,7 +126,7 @@ void ConfirmationsSettingsPage::applySettings() } kioConfig->sync(); - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->setConfirmClosingMultipleTabs(m_confirmClosingMultipleTabs->isChecked()); #if HAVE_TERMINAL @@ -144,7 +138,7 @@ void ConfirmationsSettingsPage::applySettings() void ConfirmationsSettingsPage::restoreDefaults() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->useDefaults(true); loadSettings(); settings->useDefaults(false); @@ -179,4 +173,3 @@ void ConfirmationsSettingsPage::loadSettings() m_confirmClosingTerminalRunningProgram->setChecked(GeneralSettings::confirmClosingTerminalRunningProgram()); #endif } - diff --git a/src/settings/general/confirmationssettingspage.h b/src/settings/general/confirmationssettingspage.h index 09ba56886f..56dd1a78cc 100644 --- a/src/settings/general/confirmationssettingspage.h +++ b/src/settings/general/confirmationssettingspage.h @@ -20,7 +20,7 @@ class ConfirmationsSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit ConfirmationsSettingsPage(QWidget* parent); + explicit ConfirmationsSettingsPage(QWidget *parent); ~ConfirmationsSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -33,16 +33,16 @@ private: void loadSettings(); private: - QCheckBox* m_confirmMoveToTrash; - QCheckBox* m_confirmEmptyTrash; - QCheckBox* m_confirmDelete; + QCheckBox *m_confirmMoveToTrash; + QCheckBox *m_confirmEmptyTrash; + QCheckBox *m_confirmDelete; #if HAVE_TERMINAL - QCheckBox* m_confirmClosingTerminalRunningProgram; + QCheckBox *m_confirmClosingTerminalRunningProgram; #endif - QCheckBox* m_confirmClosingMultipleTabs; - QComboBox* m_confirmScriptExecution; + QCheckBox *m_confirmClosingMultipleTabs; + QComboBox *m_confirmScriptExecution; }; #endif diff --git a/src/settings/general/generalsettingspage.cpp b/src/settings/general/generalsettingspage.cpp index 16650ff9e7..c40e45274f 100644 --- a/src/settings/general/generalsettingspage.cpp +++ b/src/settings/general/generalsettingspage.cpp @@ -16,32 +16,32 @@ #include #include -GeneralSettingsPage::GeneralSettingsPage(const QUrl& url, QWidget* parent) : - SettingsPageBase(parent), - m_pages() +GeneralSettingsPage::GeneralSettingsPage(const QUrl &url, QWidget *parent) + : SettingsPageBase(parent) + , m_pages() { - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); - QTabWidget* tabWidget = new QTabWidget(this); + QTabWidget *tabWidget = new QTabWidget(this); // initialize 'Behavior' tab - BehaviorSettingsPage* behaviorPage = new BehaviorSettingsPage(url, tabWidget); + BehaviorSettingsPage *behaviorPage = new BehaviorSettingsPage(url, tabWidget); tabWidget->addTab(behaviorPage, i18nc("@title:tab Behavior settings", "Behavior")); connect(behaviorPage, &BehaviorSettingsPage::changed, this, &GeneralSettingsPage::changed); // initialize 'Previews' tab - PreviewsSettingsPage* previewsPage = new PreviewsSettingsPage(tabWidget); + PreviewsSettingsPage *previewsPage = new PreviewsSettingsPage(tabWidget); tabWidget->addTab(previewsPage, i18nc("@title:tab Previews settings", "Previews")); connect(previewsPage, &PreviewsSettingsPage::changed, this, &GeneralSettingsPage::changed); // initialize 'Context Menu' tab - ConfirmationsSettingsPage* confirmationsPage = new ConfirmationsSettingsPage(tabWidget); + ConfirmationsSettingsPage *confirmationsPage = new ConfirmationsSettingsPage(tabWidget); tabWidget->addTab(confirmationsPage, i18nc("@title:tab Confirmations settings", "Confirmations")); connect(confirmationsPage, &ConfirmationsSettingsPage::changed, this, &GeneralSettingsPage::changed); // initialize 'Status Bar' tab - StatusBarSettingsPage* statusBarPage = new StatusBarSettingsPage(tabWidget); + StatusBarSettingsPage *statusBarPage = new StatusBarSettingsPage(tabWidget); tabWidget->addTab(statusBarPage, i18nc("@title:tab Status Bar settings", "Status Bar")); connect(statusBarPage, &StatusBarSettingsPage::changed, this, &GeneralSettingsPage::changed); @@ -59,15 +59,14 @@ GeneralSettingsPage::~GeneralSettingsPage() void GeneralSettingsPage::applySettings() { - for (SettingsPageBase* page : qAsConst(m_pages)) { + for (SettingsPageBase *page : qAsConst(m_pages)) { page->applySettings(); } } void GeneralSettingsPage::restoreDefaults() { - for (SettingsPageBase* page : qAsConst(m_pages)) { + for (SettingsPageBase *page : qAsConst(m_pages)) { page->restoreDefaults(); } } - diff --git a/src/settings/general/generalsettingspage.h b/src/settings/general/generalsettingspage.h index 5e79216d56..bb9099af05 100644 --- a/src/settings/general/generalsettingspage.h +++ b/src/settings/general/generalsettingspage.h @@ -27,7 +27,7 @@ class GeneralSettingsPage : public SettingsPageBase Q_OBJECT public: - GeneralSettingsPage(const QUrl& url, QWidget* parent); + GeneralSettingsPage(const QUrl &url, QWidget *parent); ~GeneralSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -37,7 +37,7 @@ public: void restoreDefaults() override; private: - QList m_pages; + QList m_pages; }; #endif diff --git a/src/settings/general/previewssettingspage.cpp b/src/settings/general/previewssettingspage.cpp index b30d1940af..358798f58e 100644 --- a/src/settings/general/previewssettingspage.cpp +++ b/src/settings/general/previewssettingspage.cpp @@ -6,8 +6,8 @@ #include "previewssettingspage.h" -#include "dolphin_generalsettings.h" #include "configurepreviewplugindialog.h" +#include "dolphin_generalsettings.h" #include "settings/serviceitemdelegate.h" #include "settings/servicemodel.h" @@ -24,35 +24,35 @@ #include // default settings -namespace { - const int DefaultMaxLocalPreviewSize = 0; // 0 MB - const int DefaultMaxRemotePreviewSize = 0; // 0 MB +namespace +{ +const int DefaultMaxLocalPreviewSize = 0; // 0 MB +const int DefaultMaxRemotePreviewSize = 0; // 0 MB } -PreviewsSettingsPage::PreviewsSettingsPage(QWidget* parent) : - SettingsPageBase(parent), - m_initialized(false), - m_listView(nullptr), - m_enabledPreviewPlugins(), - m_localFileSizeBox(nullptr), - m_remoteFileSizeBox(nullptr) +PreviewsSettingsPage::PreviewsSettingsPage(QWidget *parent) + : SettingsPageBase(parent) + , m_initialized(false) + , m_listView(nullptr) + , m_enabledPreviewPlugins() + , m_localFileSizeBox(nullptr) + , m_remoteFileSizeBox(nullptr) { - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); - QLabel* showPreviewsLabel = new QLabel(i18nc("@title:group", "Show previews in the view for:"), this); + QLabel *showPreviewsLabel = new QLabel(i18nc("@title:group", "Show previews in the view for:"), this); m_listView = new QListView(this); QScroller::grabGesture(m_listView->viewport(), QScroller::TouchGesture); #if KIOWIDGETS_BUILD_DEPRECATED_SINCE(5, 87) - ServiceItemDelegate* delegate = new ServiceItemDelegate(m_listView, m_listView); - connect(delegate, &ServiceItemDelegate::requestServiceConfiguration, - this, &PreviewsSettingsPage::configureService); + ServiceItemDelegate *delegate = new ServiceItemDelegate(m_listView, m_listView); + connect(delegate, &ServiceItemDelegate::requestServiceConfiguration, this, &PreviewsSettingsPage::configureService); m_listView->setItemDelegate(delegate); #endif - ServiceModel* serviceModel = new ServiceModel(this); - QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this); + ServiceModel *serviceModel = new ServiceModel(this); + QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(serviceModel); proxyModel->setSortRole(Qt::DisplayRole); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); @@ -61,7 +61,7 @@ PreviewsSettingsPage::PreviewsSettingsPage(QWidget* parent) : m_listView->setVerticalScrollMode(QListView::ScrollPerPixel); m_listView->setUniformItemSizes(true); - QLabel* localFileSizeLabel = new QLabel(i18n("Skip previews for local files above:"), this); + QLabel *localFileSizeLabel = new QLabel(i18n("Skip previews for local files above:"), this); m_localFileSizeBox = new QSpinBox(this); m_localFileSizeBox->setSingleStep(1); @@ -69,12 +69,12 @@ PreviewsSettingsPage::PreviewsSettingsPage(QWidget* parent) : m_localFileSizeBox->setRange(0, 9999999); /* MB */ m_localFileSizeBox->setSpecialValueText(i18n("No limit")); - QHBoxLayout* localFileSizeBoxLayout = new QHBoxLayout(); + QHBoxLayout *localFileSizeBoxLayout = new QHBoxLayout(); localFileSizeBoxLayout->addWidget(localFileSizeLabel); localFileSizeBoxLayout->addStretch(0); localFileSizeBoxLayout->addWidget(m_localFileSizeBox); - QLabel* remoteFileSizeLabel = new QLabel(i18nc("@label", "Skip previews for remote files above:"), this); + QLabel *remoteFileSizeLabel = new QLabel(i18nc("@label", "Skip previews for remote files above:"), this); m_remoteFileSizeBox = new QSpinBox(this); m_remoteFileSizeBox->setSingleStep(1); @@ -82,7 +82,7 @@ PreviewsSettingsPage::PreviewsSettingsPage(QWidget* parent) : m_remoteFileSizeBox->setRange(0, 9999999); /* MB */ m_remoteFileSizeBox->setSpecialValueText(i18n("No previews")); - QHBoxLayout* remoteFileSizeBoxLayout = new QHBoxLayout(); + QHBoxLayout *remoteFileSizeBoxLayout = new QHBoxLayout(); remoteFileSizeBoxLayout->addWidget(remoteFileSizeLabel); remoteFileSizeBoxLayout->addStretch(0); remoteFileSizeBoxLayout->addWidget(m_remoteFileSizeBox); @@ -105,7 +105,7 @@ PreviewsSettingsPage::~PreviewsSettingsPage() void PreviewsSettingsPage::applySettings() { - const QAbstractItemModel* model = m_listView->model(); + const QAbstractItemModel *model = m_listView->model(); const int rowCount = model->rowCount(); if (rowCount > 0) { m_enabledPreviewPlugins.clear(); @@ -126,15 +126,11 @@ void PreviewsSettingsPage::applySettings() globalConfig.deleteEntry("MaximumSize", KConfigBase::Normal | KConfigBase::Global); } else { const qulonglong maximumLocalSize = static_cast(m_localFileSizeBox->value()) * 1024 * 1024; - globalConfig.writeEntry("MaximumSize", - maximumLocalSize, - KConfigBase::Normal | KConfigBase::Global); + globalConfig.writeEntry("MaximumSize", maximumLocalSize, KConfigBase::Normal | KConfigBase::Global); } const qulonglong maximumRemoteSize = static_cast(m_remoteFileSizeBox->value()) * 1024 * 1024; - globalConfig.writeEntry("MaximumRemoteSize", - maximumRemoteSize, - KConfigBase::Normal | KConfigBase::Global); + globalConfig.writeEntry("MaximumRemoteSize", maximumRemoteSize, KConfigBase::Normal | KConfigBase::Global); globalConfig.sync(); } @@ -145,7 +141,7 @@ void PreviewsSettingsPage::restoreDefaults() m_remoteFileSizeBox->setValue(DefaultMaxRemotePreviewSize); } -void PreviewsSettingsPage::showEvent(QShowEvent* event) +void PreviewsSettingsPage::showEvent(QShowEvent *event) { if (!event->spontaneous() && !m_initialized) { loadPreviewPlugins(); @@ -155,13 +151,13 @@ void PreviewsSettingsPage::showEvent(QShowEvent* event) } #if KIOWIDGETS_BUILD_DEPRECATED_SINCE(5, 87) -void PreviewsSettingsPage::configureService(const QModelIndex& index) +void PreviewsSettingsPage::configureService(const QModelIndex &index) { - const QAbstractItemModel* model = index.model(); + const QAbstractItemModel *model = index.model(); const QString pluginName = model->data(index).toString(); const QString desktopEntryName = model->data(index, ServiceModel::DesktopEntryNameRole).toString(); - ConfigurePreviewPluginDialog* dialog = new ConfigurePreviewPluginDialog(pluginName, desktopEntryName, this); + ConfigurePreviewPluginDialog *dialog = new ConfigurePreviewPluginDialog(pluginName, desktopEntryName, this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } @@ -169,7 +165,7 @@ void PreviewsSettingsPage::configureService(const QModelIndex& index) void PreviewsSettingsPage::loadPreviewPlugins() { - QAbstractItemModel* model = m_listView->model(); + QAbstractItemModel *model = m_listView->model(); const QVector plugins = KIO::PreviewJob::availableThumbnailerPlugins(); for (const KPluginMetaData &plugin : plugins) { diff --git a/src/settings/general/previewssettingspage.h b/src/settings/general/previewssettingspage.h index 4dee27adad..2c3e4dfeff 100644 --- a/src/settings/general/previewssettingspage.h +++ b/src/settings/general/previewssettingspage.h @@ -7,7 +7,6 @@ #ifndef PREVIEWSSETTINGSPAGE_H #define PREVIEWSSETTINGSPAGE_H - #include #include "settings/settingspagebase.h" @@ -24,7 +23,7 @@ class PreviewsSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit PreviewsSettingsPage(QWidget* parent); + explicit PreviewsSettingsPage(QWidget *parent); ~PreviewsSettingsPage() override; /** @@ -38,11 +37,11 @@ public: void restoreDefaults() override; protected: - void showEvent(QShowEvent* event) override; + void showEvent(QShowEvent *event) override; private Q_SLOTS: #if KIOWIDGETS_BUILD_DEPRECATED_SINCE(5, 87) - void configureService(const QModelIndex& index); + void configureService(const QModelIndex &index); #endif private: @@ -53,8 +52,8 @@ private: bool m_initialized; QListView *m_listView; QStringList m_enabledPreviewPlugins; - QSpinBox* m_localFileSizeBox; - QSpinBox* m_remoteFileSizeBox; + QSpinBox *m_localFileSizeBox; + QSpinBox *m_remoteFileSizeBox; }; #endif diff --git a/src/settings/general/statusbarsettingspage.cpp b/src/settings/general/statusbarsettingspage.cpp index 9d90a64fdb..0d5be04bfc 100644 --- a/src/settings/general/statusbarsettingspage.cpp +++ b/src/settings/general/statusbarsettingspage.cpp @@ -13,17 +13,17 @@ #include #include -StatusBarSettingsPage::StatusBarSettingsPage(QWidget* parent) : - SettingsPageBase(parent), - m_showStatusBar(nullptr), - m_showZoomSlider(nullptr), - m_showSpaceInfo(nullptr) +StatusBarSettingsPage::StatusBarSettingsPage(QWidget *parent) + : SettingsPageBase(parent) + , m_showStatusBar(nullptr) + , m_showZoomSlider(nullptr) + , m_showSpaceInfo(nullptr) { m_showStatusBar = new QCheckBox(i18nc("@option:check", "Show status bar"), this); m_showZoomSlider = new QCheckBox(i18nc("@option:check", "Show zoom slider"), this); m_showSpaceInfo = new QCheckBox(i18nc("@option:check", "Show space information"), this); - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); topLayout->addWidget(m_showStatusBar); topLayout->addWidget(m_showZoomSlider); topLayout->addWidget(m_showSpaceInfo); @@ -50,7 +50,7 @@ void StatusBarSettingsPage::onShowStatusBarToggled() void StatusBarSettingsPage::applySettings() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->setShowStatusBar(m_showStatusBar->isChecked()); settings->setShowZoomSlider(m_showZoomSlider->isChecked()); settings->setShowSpaceInfo(m_showSpaceInfo->isChecked()); @@ -59,7 +59,7 @@ void StatusBarSettingsPage::applySettings() void StatusBarSettingsPage::restoreDefaults() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->useDefaults(true); loadSettings(); settings->useDefaults(false); @@ -73,4 +73,3 @@ void StatusBarSettingsPage::loadSettings() onShowStatusBarToggled(); } - diff --git a/src/settings/general/statusbarsettingspage.h b/src/settings/general/statusbarsettingspage.h index af8e061641..adff05dc14 100644 --- a/src/settings/general/statusbarsettingspage.h +++ b/src/settings/general/statusbarsettingspage.h @@ -18,7 +18,7 @@ class StatusBarSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit StatusBarSettingsPage(QWidget* parent); + explicit StatusBarSettingsPage(QWidget *parent); ~StatusBarSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -32,9 +32,9 @@ private: void onShowStatusBarToggled(); private: - QCheckBox* m_showStatusBar; - QCheckBox* m_showZoomSlider; - QCheckBox* m_showSpaceInfo; + QCheckBox *m_showStatusBar; + QCheckBox *m_showZoomSlider; + QCheckBox *m_showSpaceInfo; }; #endif diff --git a/src/settings/kcm/kcmdolphingeneral.cpp b/src/settings/kcm/kcmdolphingeneral.cpp index 5e38c24094..25e3b6876d 100644 --- a/src/settings/kcm/kcmdolphingeneral.cpp +++ b/src/settings/kcm/kcmdolphingeneral.cpp @@ -7,8 +7,8 @@ #include "kcmdolphingeneral.h" #include "settings/general/behaviorsettingspage.h" -#include "settings/general/previewssettingspage.h" #include "settings/general/confirmationssettingspage.h" +#include "settings/general/previewssettingspage.h" #include #include @@ -19,30 +19,30 @@ K_PLUGIN_CLASS_WITH_JSON(DolphinGeneralConfigModule, "kcmdolphingeneral.json") -DolphinGeneralConfigModule::DolphinGeneralConfigModule(QWidget *parent, const QVariantList &args) : - KCModule(parent, args), - m_pages() +DolphinGeneralConfigModule::DolphinGeneralConfigModule(QWidget *parent, const QVariantList &args) + : KCModule(parent, args) + , m_pages() { setButtons(KCModule::Default | KCModule::Help | KCModule::Apply); - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); - QTabWidget* tabWidget = new QTabWidget(this); + QTabWidget *tabWidget = new QTabWidget(this); // initialize 'Behavior' tab - BehaviorSettingsPage* behaviorPage = new BehaviorSettingsPage(QUrl::fromLocalFile(QDir::homePath()), tabWidget); + BehaviorSettingsPage *behaviorPage = new BehaviorSettingsPage(QUrl::fromLocalFile(QDir::homePath()), tabWidget); tabWidget->addTab(behaviorPage, i18nc("@title:tab Behavior settings", "Behavior")); connect(behaviorPage, &BehaviorSettingsPage::changed, this, &DolphinGeneralConfigModule::markAsChanged); // initialize 'Previews' tab - PreviewsSettingsPage* previewsPage = new PreviewsSettingsPage(tabWidget); + PreviewsSettingsPage *previewsPage = new PreviewsSettingsPage(tabWidget); tabWidget->addTab(previewsPage, i18nc("@title:tab Previews settings", "Previews")); connect(previewsPage, &PreviewsSettingsPage::changed, this, &DolphinGeneralConfigModule::markAsChanged); // initialize 'Confirmations' tab - ConfirmationsSettingsPage* confirmationsPage = new ConfirmationsSettingsPage(tabWidget); - tabWidget->addTab(confirmationsPage, i18nc("@title:tab Confirmations settings", "Confirmations")); + ConfirmationsSettingsPage *confirmationsPage = new ConfirmationsSettingsPage(tabWidget); + tabWidget->addTab(confirmationsPage, i18nc("@title:tab Confirmations settings", "Confirmations")); connect(confirmationsPage, &ConfirmationsSettingsPage::changed, this, &DolphinGeneralConfigModule::markAsChanged); m_pages.append(behaviorPage); m_pages.append(previewsPage); @@ -57,14 +57,14 @@ DolphinGeneralConfigModule::~DolphinGeneralConfigModule() void DolphinGeneralConfigModule::save() { - for (SettingsPageBase* page : qAsConst(m_pages)) { + for (SettingsPageBase *page : qAsConst(m_pages)) { page->applySettings(); } } void DolphinGeneralConfigModule::defaults() { - for (SettingsPageBase* page : qAsConst(m_pages)) { + for (SettingsPageBase *page : qAsConst(m_pages)) { page->applySettings(); } } diff --git a/src/settings/kcm/kcmdolphingeneral.h b/src/settings/kcm/kcmdolphingeneral.h index d4040cc8d9..8893177387 100644 --- a/src/settings/kcm/kcmdolphingeneral.h +++ b/src/settings/kcm/kcmdolphingeneral.h @@ -28,7 +28,7 @@ public: void defaults() override; private: - QList m_pages; + QList m_pages; }; #endif diff --git a/src/settings/kcm/kcmdolphinnavigation.cpp b/src/settings/kcm/kcmdolphinnavigation.cpp index 223b6dcf19..63591f4fd2 100644 --- a/src/settings/kcm/kcmdolphinnavigation.cpp +++ b/src/settings/kcm/kcmdolphinnavigation.cpp @@ -15,13 +15,13 @@ K_PLUGIN_CLASS_WITH_JSON(DolphinNavigationConfigModule, "kcmdolphinnavigation.json") -DolphinNavigationConfigModule::DolphinNavigationConfigModule(QWidget *parent, const QVariantList &args) : - KCModule(parent, args), - m_navigation(nullptr) +DolphinNavigationConfigModule::DolphinNavigationConfigModule(QWidget *parent, const QVariantList &args) + : KCModule(parent, args) + , m_navigation(nullptr) { setButtons(KCModule::Default | KCModule::Help | KCModule::Apply); - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); m_navigation = new NavigationSettingsPage(this); diff --git a/src/settings/kcm/kcmdolphinviewmodes.cpp b/src/settings/kcm/kcmdolphinviewmodes.cpp index b8b350c107..50ee136189 100644 --- a/src/settings/kcm/kcmdolphinviewmodes.cpp +++ b/src/settings/kcm/kcmdolphinviewmodes.cpp @@ -19,29 +19,29 @@ K_PLUGIN_CLASS_WITH_JSON(DolphinViewModesConfigModule, "kcmdolphinviewmodes.json") -DolphinViewModesConfigModule::DolphinViewModesConfigModule(QWidget *parent, const QVariantList &args) : - KCModule(parent, args), - m_tabs() +DolphinViewModesConfigModule::DolphinViewModesConfigModule(QWidget *parent, const QVariantList &args) + : KCModule(parent, args) + , m_tabs() { setButtons(KCModule::Default | KCModule::Help | KCModule::Apply); - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); - QTabWidget* tabWidget = new QTabWidget(this); + QTabWidget *tabWidget = new QTabWidget(this); // Initialize 'Icons' tab - ViewSettingsTab* iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget); + ViewSettingsTab *iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget); tabWidget->addTab(iconsTab, QIcon::fromTheme(QStringLiteral("view-list-icons")), i18nc("@title:tab", "Icons")); connect(iconsTab, &ViewSettingsTab::changed, this, &DolphinViewModesConfigModule::viewModeChanged); // Initialize 'Compact' tab - ViewSettingsTab* compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget); + ViewSettingsTab *compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget); tabWidget->addTab(compactTab, QIcon::fromTheme(QStringLiteral("view-list-details")), i18nc("@title:tab", "Compact")); connect(compactTab, &ViewSettingsTab::changed, this, &DolphinViewModesConfigModule::viewModeChanged); // Initialize 'Details' tab - ViewSettingsTab* detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget); + ViewSettingsTab *detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget); tabWidget->addTab(detailsTab, QIcon::fromTheme(QStringLiteral("view-list-tree")), i18nc("@title:tab", "Details")); connect(detailsTab, &ViewSettingsTab::changed, this, &DolphinViewModesConfigModule::viewModeChanged); @@ -74,9 +74,8 @@ void DolphinViewModesConfigModule::defaults() void DolphinViewModesConfigModule::reparseConfiguration() { - QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KonqMain"), - QStringLiteral("org.kde.Konqueror.Main"), - QStringLiteral("reparseConfiguration")); + QDBusMessage message = + QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration")); QDBusConnection::sessionBus().send(message); } diff --git a/src/settings/kcm/kcmdolphinviewmodes.h b/src/settings/kcm/kcmdolphinviewmodes.h index ea61bcf892..33c0b77a52 100644 --- a/src/settings/kcm/kcmdolphinviewmodes.h +++ b/src/settings/kcm/kcmdolphinviewmodes.h @@ -29,10 +29,10 @@ private: void reparseConfiguration(); private Q_SLOTS: - void viewModeChanged(); + void viewModeChanged(); private: - QList m_tabs; + QList m_tabs; }; #endif diff --git a/src/settings/navigation/navigationsettingspage.cpp b/src/settings/navigation/navigationsettingspage.cpp index 48f5062a0e..956d25fdff 100644 --- a/src/settings/navigation/navigationsettingspage.cpp +++ b/src/settings/navigation/navigationsettingspage.cpp @@ -6,8 +6,8 @@ #include "navigationsettingspage.h" -#include "global.h" #include "dolphin_generalsettings.h" +#include "global.h" #include @@ -16,19 +16,19 @@ #include #include -NavigationSettingsPage::NavigationSettingsPage(QWidget* parent) : - SettingsPageBase(parent), - m_openArchivesAsFolder(nullptr), - m_autoExpandFolders(nullptr), - m_openNewTabAfterLastTab(nullptr), - m_openNewTabAfterCurrentTab(nullptr) +NavigationSettingsPage::NavigationSettingsPage(QWidget *parent) + : SettingsPageBase(parent) + , m_openArchivesAsFolder(nullptr) + , m_autoExpandFolders(nullptr) + , m_openNewTabAfterLastTab(nullptr) + , m_openNewTabAfterCurrentTab(nullptr) { - QFormLayout* topLayout = new QFormLayout(this); + QFormLayout *topLayout = new QFormLayout(this); // Tabs properties m_openNewTabAfterCurrentTab = new QRadioButton(i18nc("option:radio", "After current tab")); m_openNewTabAfterLastTab = new QRadioButton(i18nc("option:radio", "At end of tab bar")); - QButtonGroup* tabsBehaviorGroup = new QButtonGroup(this); + QButtonGroup *tabsBehaviorGroup = new QButtonGroup(this); tabsBehaviorGroup->addButton(m_openNewTabAfterCurrentTab); tabsBehaviorGroup->addButton(m_openNewTabAfterLastTab); topLayout->addRow(i18nc("@title:group", "Open new tabs: "), m_openNewTabAfterCurrentTab); @@ -55,7 +55,7 @@ NavigationSettingsPage::~NavigationSettingsPage() void NavigationSettingsPage::applySettings() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->setBrowseThroughArchives(m_openArchivesAsFolder->isChecked()); settings->setAutoExpandFolders(m_autoExpandFolders->isChecked()); settings->setOpenNewTabAfterLastTab(m_openNewTabAfterLastTab->isChecked()); @@ -65,7 +65,7 @@ void NavigationSettingsPage::applySettings() void NavigationSettingsPage::restoreDefaults() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->useDefaults(true); loadSettings(); settings->useDefaults(false); @@ -78,4 +78,3 @@ void NavigationSettingsPage::loadSettings() m_openNewTabAfterLastTab->setChecked(GeneralSettings::openNewTabAfterLastTab()); m_openNewTabAfterCurrentTab->setChecked(!m_openNewTabAfterLastTab->isChecked()); } - diff --git a/src/settings/navigation/navigationsettingspage.h b/src/settings/navigation/navigationsettingspage.h index a0c75e7f5d..e0f92884fb 100644 --- a/src/settings/navigation/navigationsettingspage.h +++ b/src/settings/navigation/navigationsettingspage.h @@ -19,7 +19,7 @@ class NavigationSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit NavigationSettingsPage(QWidget* parent); + explicit NavigationSettingsPage(QWidget *parent); ~NavigationSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -32,10 +32,10 @@ private: void loadSettings(); private: - QCheckBox* m_openArchivesAsFolder; - QCheckBox* m_autoExpandFolders; - QRadioButton* m_openNewTabAfterLastTab; - QRadioButton* m_openNewTabAfterCurrentTab; + QCheckBox *m_openArchivesAsFolder; + QCheckBox *m_autoExpandFolders; + QRadioButton *m_openNewTabAfterLastTab; + QRadioButton *m_openNewTabAfterCurrentTab; }; #endif diff --git a/src/settings/serviceitemdelegate.cpp b/src/settings/serviceitemdelegate.cpp index cd3499d03f..d8f446a37b 100644 --- a/src/settings/serviceitemdelegate.cpp +++ b/src/settings/serviceitemdelegate.cpp @@ -13,8 +13,8 @@ #include #include -ServiceItemDelegate::ServiceItemDelegate(QAbstractItemView* itemView, QObject* parent) : - KWidgetItemDelegate(itemView, parent) +ServiceItemDelegate::ServiceItemDelegate(QAbstractItemView *itemView, QObject *parent) + : KWidgetItemDelegate(itemView, parent) { } @@ -22,20 +22,17 @@ ServiceItemDelegate::~ServiceItemDelegate() { } -QSize ServiceItemDelegate::sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const +QSize ServiceItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index) const QStyle *style = itemView()->style(); - const int buttonHeight = style->pixelMetric(QStyle::PM_ButtonMargin) * 2 + - style->pixelMetric(QStyle::PM_ButtonIconSize); + const int buttonHeight = style->pixelMetric(QStyle::PM_ButtonMargin) * 2 + style->pixelMetric(QStyle::PM_ButtonIconSize); const int fontHeight = option.fontMetrics.height(); return QSize(100, qMax(buttonHeight, fontHeight)); } -void ServiceItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const +void ServiceItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index) painter->save(); @@ -49,31 +46,29 @@ void ServiceItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& o painter->restore(); } -QList ServiceItemDelegate::createItemWidgets(const QModelIndex&) const +QList ServiceItemDelegate::createItemWidgets(const QModelIndex &) const { - QCheckBox* checkBox = new QCheckBox(); + QCheckBox *checkBox = new QCheckBox(); QPalette palette = checkBox->palette(); palette.setColor(QPalette::WindowText, palette.color(QPalette::Text)); checkBox->setPalette(palette); connect(checkBox, &QCheckBox::clicked, this, &ServiceItemDelegate::slotCheckBoxClicked); - QPushButton* configureButton = new QPushButton(); + QPushButton *configureButton = new QPushButton(); connect(configureButton, &QPushButton::clicked, this, &ServiceItemDelegate::slotConfigureButtonClicked); return {checkBox, configureButton}; } -void ServiceItemDelegate::updateItemWidgets(const QList widgets, - const QStyleOptionViewItem& option, - const QPersistentModelIndex& index) const +void ServiceItemDelegate::updateItemWidgets(const QList widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const { - QCheckBox* checkBox = static_cast(widgets[0]); - QPushButton *configureButton = static_cast(widgets[1]); + QCheckBox *checkBox = static_cast(widgets[0]); + QPushButton *configureButton = static_cast(widgets[1]); const int itemHeight = sizeHint(option, index).height(); // Update the checkbox showing the service name and icon - const QAbstractItemModel* model = index.model(); + const QAbstractItemModel *model = index.model(); checkBox->setText(model->data(index).toString()); const QString iconName = model->data(index, Qt::DecorationRole).toString(); if (!iconName.isEmpty()) { @@ -95,15 +90,14 @@ void ServiceItemDelegate::updateItemWidgets(const QList widgets, configureButton->setEnabled(checkBox->isChecked()); configureButton->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); configureButton->resize(configureButton->sizeHint()); - configureButton->move(option.rect.right() - configureButton->width(), - (itemHeight - configureButton->height()) / 2); + configureButton->move(option.rect.right() - configureButton->width(), (itemHeight - configureButton->height()) / 2); } configureButton->setVisible(configurable); } void ServiceItemDelegate::slotCheckBoxClicked(bool checked) { - QAbstractItemModel* model = const_cast(focusedIndex().model()); + QAbstractItemModel *model = const_cast(focusedIndex().model()); model->setData(focusedIndex(), checked, Qt::CheckStateRole); } @@ -111,4 +105,3 @@ void ServiceItemDelegate::slotConfigureButtonClicked() { Q_EMIT requestServiceConfiguration(focusedIndex()); } - diff --git a/src/settings/serviceitemdelegate.h b/src/settings/serviceitemdelegate.h index 5c516916f7..74f7dfd6a2 100644 --- a/src/settings/serviceitemdelegate.h +++ b/src/settings/serviceitemdelegate.h @@ -20,23 +20,19 @@ class ServiceItemDelegate : public KWidgetItemDelegate Q_OBJECT public: - explicit ServiceItemDelegate(QAbstractItemView* itemView, QObject* parent = nullptr); + explicit ServiceItemDelegate(QAbstractItemView *itemView, QObject *parent = nullptr); ~ServiceItemDelegate() override; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; - void paint(QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const override; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - QList createItemWidgets(const QModelIndex&) const override; + QList createItemWidgets(const QModelIndex &) const override; - void updateItemWidgets(const QList widgets, - const QStyleOptionViewItem& option, - const QPersistentModelIndex& index) const override; + void updateItemWidgets(const QList widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const override; Q_SIGNALS: - void requestServiceConfiguration(const QModelIndex& index); + void requestServiceConfiguration(const QModelIndex &index); private Q_SLOTS: void slotCheckBoxClicked(bool checked); diff --git a/src/settings/servicemodel.cpp b/src/settings/servicemodel.cpp index 9bfe1dad3e..6caafdd775 100644 --- a/src/settings/servicemodel.cpp +++ b/src/settings/servicemodel.cpp @@ -6,9 +6,9 @@ #include "servicemodel.h" -ServiceModel::ServiceModel(QObject* parent) : - QAbstractListModel(parent), - m_items() +ServiceModel::ServiceModel(QObject *parent) + : QAbstractListModel(parent) + , m_items() { } @@ -16,7 +16,7 @@ ServiceModel::~ServiceModel() { } -bool ServiceModel::insertRows(int row, int count, const QModelIndex& parent) +bool ServiceModel::insertRows(int row, int count, const QModelIndex &parent) { if (row > rowCount()) { return false; @@ -38,7 +38,7 @@ bool ServiceModel::insertRows(int row, int count, const QModelIndex& parent) return true; } -bool ServiceModel::setData(const QModelIndex& index, const QVariant& value, int role) +bool ServiceModel::setData(const QModelIndex &index, const QVariant &value, int role) { const int row = index.row(); if (row >= rowCount()) { @@ -69,24 +69,30 @@ bool ServiceModel::setData(const QModelIndex& index, const QVariant& value, int return true; } -QVariant ServiceModel::data(const QModelIndex& index, int role) const +QVariant ServiceModel::data(const QModelIndex &index, int role) const { const int row = index.row(); if (row < rowCount()) { switch (role) { - case ConfigurableRole: return m_items[row].configurable; - case Qt::CheckStateRole: return m_items[row].checked; - case Qt::DecorationRole: return m_items[row].icon; - case Qt::DisplayRole: return m_items[row].text; - case DesktopEntryNameRole: return m_items[row].desktopEntryName; - default: break; + case ConfigurableRole: + return m_items[row].configurable; + case Qt::CheckStateRole: + return m_items[row].checked; + case Qt::DecorationRole: + return m_items[row].icon; + case Qt::DisplayRole: + return m_items[row].text; + case DesktopEntryNameRole: + return m_items[row].desktopEntryName; + default: + break; } } return QVariant(); } -int ServiceModel::rowCount(const QModelIndex& parent) const +int ServiceModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return m_items.count(); @@ -98,4 +104,3 @@ void ServiceModel::clear() m_items.clear(); endRemoveRows(); } - diff --git a/src/settings/servicemodel.h b/src/settings/servicemodel.h index 150159137c..23c752e934 100644 --- a/src/settings/servicemodel.h +++ b/src/settings/servicemodel.h @@ -25,24 +25,19 @@ class ServiceModel : public QAbstractListModel Q_OBJECT public: - enum Role - { - DesktopEntryNameRole = Qt::UserRole, - ConfigurableRole - }; + enum Role { DesktopEntryNameRole = Qt::UserRole, ConfigurableRole }; - explicit ServiceModel(QObject* parent = nullptr); + explicit ServiceModel(QObject *parent = nullptr); ~ServiceModel() override; - bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex()) override; - bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override; - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - int rowCount(const QModelIndex& parent = QModelIndex()) const override; + bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; void clear(); - private: - struct ServiceItem - { +private: + struct ServiceItem { bool checked; bool configurable; QString icon; diff --git a/src/settings/settingspagebase.cpp b/src/settings/settingspagebase.cpp index 963966a4eb..8e1bede2a3 100644 --- a/src/settings/settingspagebase.cpp +++ b/src/settings/settingspagebase.cpp @@ -6,11 +6,11 @@ #include "settingspagebase.h" -SettingsPageBase::SettingsPageBase(QWidget* parent) : - QWidget(parent) -{} +SettingsPageBase::SettingsPageBase(QWidget *parent) + : QWidget(parent) +{ +} SettingsPageBase::~SettingsPageBase() -{} - - +{ +} diff --git a/src/settings/settingspagebase.h b/src/settings/settingspagebase.h index c6842dec47..d331b7d358 100644 --- a/src/settings/settingspagebase.h +++ b/src/settings/settingspagebase.h @@ -17,7 +17,7 @@ class SettingsPageBase : public QWidget Q_OBJECT public: - explicit SettingsPageBase(QWidget* parent = nullptr); + explicit SettingsPageBase(QWidget *parent = nullptr); ~SettingsPageBase() override; /** diff --git a/src/settings/startup/startupsettingspage.cpp b/src/settings/startup/startupsettingspage.cpp index a7fcec4fa3..689b43cfb0 100644 --- a/src/settings/startup/startupsettingspage.cpp +++ b/src/settings/startup/startupsettingspage.cpp @@ -18,73 +18,69 @@ #include #include #include -#include -#include -#include #include #include #include +#include +#include +#include -StartupSettingsPage::StartupSettingsPage(const QUrl& url, QWidget* parent) : - SettingsPageBase(parent), - m_url(url), - m_homeUrl(nullptr), - m_homeUrlBoxLayoutContainer(nullptr), - m_buttonBoxLayoutContainer(nullptr), - m_rememberOpenedTabsRadioButton(nullptr), - m_homeUrlRadioButton(nullptr), - m_splitView(nullptr), - m_editableUrl(nullptr), - m_showFullPath(nullptr), - m_filterBar(nullptr), - m_showFullPathInTitlebar(nullptr), - m_openExternallyCalledFolderInNewTab(nullptr) +StartupSettingsPage::StartupSettingsPage(const QUrl &url, QWidget *parent) + : SettingsPageBase(parent) + , m_url(url) + , m_homeUrl(nullptr) + , m_homeUrlBoxLayoutContainer(nullptr) + , m_buttonBoxLayoutContainer(nullptr) + , m_rememberOpenedTabsRadioButton(nullptr) + , m_homeUrlRadioButton(nullptr) + , m_splitView(nullptr) + , m_editableUrl(nullptr) + , m_showFullPath(nullptr) + , m_filterBar(nullptr) + , m_showFullPathInTitlebar(nullptr) + , m_openExternallyCalledFolderInNewTab(nullptr) { - QFormLayout* topLayout = new QFormLayout(this); + QFormLayout *topLayout = new QFormLayout(this); m_rememberOpenedTabsRadioButton = new QRadioButton(i18nc("@option:radio Startup Settings", "Folders, tabs, and window state from last time")); m_homeUrlRadioButton = new QRadioButton(); // HACK: otherwise the radio button has too much spacing in a grid layout m_homeUrlRadioButton->setMaximumWidth(24); - QButtonGroup* initialViewGroup = new QButtonGroup(this); + QButtonGroup *initialViewGroup = new QButtonGroup(this); initialViewGroup->addButton(m_rememberOpenedTabsRadioButton); initialViewGroup->addButton(m_homeUrlRadioButton); - // create 'Home URL' editor m_homeUrlBoxLayoutContainer = new QWidget(this); - QHBoxLayout* homeUrlBoxLayout = new QHBoxLayout(m_homeUrlBoxLayoutContainer); + QHBoxLayout *homeUrlBoxLayout = new QHBoxLayout(m_homeUrlBoxLayoutContainer); homeUrlBoxLayout->setContentsMargins(0, 0, 0, 0); m_homeUrl = new QLineEdit(); m_homeUrl->setClearButtonEnabled(true); homeUrlBoxLayout->addWidget(m_homeUrl); - QPushButton* selectHomeUrlButton = new QPushButton(QIcon::fromTheme(QStringLiteral("folder-open")), QString()); + QPushButton *selectHomeUrlButton = new QPushButton(QIcon::fromTheme(QStringLiteral("folder-open")), QString()); homeUrlBoxLayout->addWidget(selectHomeUrlButton); #ifndef QT_NO_ACCESSIBILITY selectHomeUrlButton->setAccessibleName(i18nc("@action:button", "Select Home Location")); #endif - connect(selectHomeUrlButton, &QPushButton::clicked, - this, &StartupSettingsPage::selectHomeUrl); + connect(selectHomeUrlButton, &QPushButton::clicked, this, &StartupSettingsPage::selectHomeUrl); m_buttonBoxLayoutContainer = new QWidget(this); - QHBoxLayout* buttonBoxLayout = new QHBoxLayout(m_buttonBoxLayoutContainer); + QHBoxLayout *buttonBoxLayout = new QHBoxLayout(m_buttonBoxLayoutContainer); buttonBoxLayout->setContentsMargins(0, 0, 0, 0); - QPushButton* useCurrentButton = new QPushButton(i18nc("@action:button", "Use Current Location")); + QPushButton *useCurrentButton = new QPushButton(i18nc("@action:button", "Use Current Location")); buttonBoxLayout->addWidget(useCurrentButton); - connect(useCurrentButton, &QPushButton::clicked, - this, &StartupSettingsPage::useCurrentLocation); - QPushButton* useDefaultButton = new QPushButton(i18nc("@action:button", "Use Default Location")); + connect(useCurrentButton, &QPushButton::clicked, this, &StartupSettingsPage::useCurrentLocation); + QPushButton *useDefaultButton = new QPushButton(i18nc("@action:button", "Use Default Location")); buttonBoxLayout->addWidget(useDefaultButton); - connect(useDefaultButton, &QPushButton::clicked, - this, &StartupSettingsPage::useDefaultLocation); + connect(useDefaultButton, &QPushButton::clicked, this, &StartupSettingsPage::useDefaultLocation); - QGridLayout* startInLocationLayout = new QGridLayout(); + QGridLayout *startInLocationLayout = new QGridLayout(); startInLocationLayout->setHorizontalSpacing(0); startInLocationLayout->setContentsMargins(0, 0, 0, 0); startInLocationLayout->addWidget(m_homeUrlRadioButton, 0, 0); @@ -94,7 +90,6 @@ StartupSettingsPage::StartupSettingsPage(const QUrl& url, QWidget* parent) : topLayout->addRow(i18nc("@label:textbox", "Show on startup:"), m_rememberOpenedTabsRadioButton); topLayout->addRow(QString(), startInLocationLayout); - topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed)); m_splitView = new QCheckBox(i18nc("@option:check Startup Settings", "Begin in split view mode")); @@ -121,9 +116,9 @@ StartupSettingsPage::StartupSettingsPage(const QUrl& url, QWidget* parent) : connect(m_rememberOpenedTabsRadioButton, &QRadioButton::toggled, this, &StartupSettingsPage::slotSettingsChanged); connect(m_homeUrlRadioButton, &QRadioButton::toggled, this, &StartupSettingsPage::slotSettingsChanged); - connect(m_splitView, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); - connect(m_editableUrl, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); - connect(m_filterBar, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); + connect(m_splitView, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); + connect(m_editableUrl, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); + connect(m_filterBar, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); connect(m_openExternallyCalledFolderInNewTab, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); connect(m_showFullPath, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged); @@ -136,13 +131,13 @@ StartupSettingsPage::~StartupSettingsPage() void StartupSettingsPage::applySettings() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); const QUrl url(QUrl::fromUserInput(m_homeUrl->text(), QString(), QUrl::AssumeLocalFile)); if (url.isValid() && KProtocolManager::supportsListing(url)) { - KIO::StatJob* job = KIO::statDetails(url, KIO::StatJob::SourceSide, KIO::StatDetail::StatBasic, KIO::JobFlag::HideProgressInfo); - connect(job, &KJob::result, this, [this, settings, url](KJob* job) { - if (job->error() == 0 && qobject_cast(job)->statResult().isDir()) { + KIO::StatJob *job = KIO::statDetails(url, KIO::StatJob::SourceSide, KIO::StatDetail::StatBasic, KIO::JobFlag::HideProgressInfo); + connect(job, &KJob::result, this, [this, settings, url](KJob *job) { + if (job->error() == 0 && qobject_cast(job)->statResult().isDir()) { settings->setHomeUrl(url.toDisplayString(QUrl::PreferLocalFile)); } else { showSetDefaultDirectoryError(); @@ -172,7 +167,7 @@ void StartupSettingsPage::applySettings() void StartupSettingsPage::restoreDefaults() { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->useDefaults(true); loadSettings(); settings->useDefaults(false); diff --git a/src/settings/startup/startupsettingspage.h b/src/settings/startup/startupsettingspage.h index 51e7e90c95..b1cf387fa9 100644 --- a/src/settings/startup/startupsettingspage.h +++ b/src/settings/startup/startupsettingspage.h @@ -25,7 +25,7 @@ class StartupSettingsPage : public SettingsPageBase Q_OBJECT public: - StartupSettingsPage(const QUrl& url, QWidget* parent); + StartupSettingsPage(const QUrl &url, QWidget *parent); ~StartupSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -47,18 +47,18 @@ private: private: QUrl m_url; - QLineEdit* m_homeUrl; - QWidget* m_homeUrlBoxLayoutContainer; - QWidget* m_buttonBoxLayoutContainer; - QRadioButton* m_rememberOpenedTabsRadioButton; - QRadioButton* m_homeUrlRadioButton; + QLineEdit *m_homeUrl; + QWidget *m_homeUrlBoxLayoutContainer; + QWidget *m_buttonBoxLayoutContainer; + QRadioButton *m_rememberOpenedTabsRadioButton; + QRadioButton *m_homeUrlRadioButton; - QCheckBox* m_splitView; - QCheckBox* m_editableUrl; - QCheckBox* m_showFullPath; - QCheckBox* m_filterBar; - QCheckBox* m_showFullPathInTitlebar; - QCheckBox* m_openExternallyCalledFolderInNewTab; + QCheckBox *m_splitView; + QCheckBox *m_editableUrl; + QCheckBox *m_showFullPath; + QCheckBox *m_filterBar; + QCheckBox *m_showFullPathInTitlebar; + QCheckBox *m_openExternallyCalledFolderInNewTab; }; #endif diff --git a/src/settings/trash/trashsettingspage.cpp b/src/settings/trash/trashsettingspage.cpp index 734762adac..511d6b3535 100644 --- a/src/settings/trash/trashsettingspage.cpp +++ b/src/settings/trash/trashsettingspage.cpp @@ -11,10 +11,10 @@ #include -TrashSettingsPage::TrashSettingsPage(QWidget* parent) : - SettingsPageBase(parent) +TrashSettingsPage::TrashSettingsPage(QWidget *parent) + : SettingsPageBase(parent) { - QFormLayout* topLayout = new QFormLayout(this); + QFormLayout *topLayout = new QFormLayout(this); m_proxy = new KCModuleProxy(KPluginMetaData(QStringLiteral("kcm_trash"))); topLayout->addRow(m_proxy); @@ -42,4 +42,3 @@ void TrashSettingsPage::loadSettings() { m_proxy->load(); } - diff --git a/src/settings/trash/trashsettingspage.h b/src/settings/trash/trashsettingspage.h index 0a158fb089..b0e48a018d 100644 --- a/src/settings/trash/trashsettingspage.h +++ b/src/settings/trash/trashsettingspage.h @@ -18,7 +18,7 @@ class TrashSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit TrashSettingsPage(QWidget* parent); + explicit TrashSettingsPage(QWidget *parent); ~TrashSettingsPage() override; /** @see SettingsPageBase::applySettings() */ diff --git a/src/settings/userfeedback/userfeedbacksettingspage.cpp b/src/settings/userfeedback/userfeedbacksettingspage.cpp index 479c462265..e51f2e41a8 100644 --- a/src/settings/userfeedback/userfeedbacksettingspage.cpp +++ b/src/settings/userfeedback/userfeedbacksettingspage.cpp @@ -12,8 +12,8 @@ #include -UserFeedbackSettingsPage::UserFeedbackSettingsPage(QWidget* parent) : - SettingsPageBase(parent) +UserFeedbackSettingsPage::UserFeedbackSettingsPage(QWidget *parent) + : SettingsPageBase(parent) { auto layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); @@ -43,5 +43,3 @@ void UserFeedbackSettingsPage::restoreDefaults() feedbackProvider->setTelemetryMode(KUserFeedback::Provider::NoTelemetry); feedbackProvider->setSurveyInterval(-1); } - - diff --git a/src/settings/userfeedback/userfeedbacksettingspage.h b/src/settings/userfeedback/userfeedbacksettingspage.h index d9b6086152..b990652ff2 100644 --- a/src/settings/userfeedback/userfeedbacksettingspage.h +++ b/src/settings/userfeedback/userfeedbacksettingspage.h @@ -9,7 +9,8 @@ #include "settings/settingspagebase.h" -namespace KUserFeedback { +namespace KUserFeedback +{ class FeedbackConfigWidget; } @@ -21,7 +22,7 @@ class UserFeedbackSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit UserFeedbackSettingsPage(QWidget* parent); + explicit UserFeedbackSettingsPage(QWidget *parent); ~UserFeedbackSettingsPage() override; /** @see SettingsPageBase::applySettings() */ diff --git a/src/settings/viewmodes/dolphinfontrequester.cpp b/src/settings/viewmodes/dolphinfontrequester.cpp index a4663e94a3..68ffa4f001 100644 --- a/src/settings/viewmodes/dolphinfontrequester.cpp +++ b/src/settings/viewmodes/dolphinfontrequester.cpp @@ -14,25 +14,23 @@ #include #include -DolphinFontRequester::DolphinFontRequester(QWidget* parent) : - QWidget(parent), - m_modeCombo(nullptr), - m_chooseFontButton(nullptr), - m_mode(SystemFont), - m_customFont() +DolphinFontRequester::DolphinFontRequester(QWidget *parent) + : QWidget(parent) + , m_modeCombo(nullptr) + , m_chooseFontButton(nullptr) + , m_mode(SystemFont) + , m_customFont() { - QHBoxLayout* topLayout = new QHBoxLayout(this); + QHBoxLayout *topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); m_modeCombo = new QComboBox(this); m_modeCombo->addItem(i18nc("@item:inlistbox Font", "System Font")); m_modeCombo->addItem(i18nc("@item:inlistbox Font", "Custom Font")); - connect(m_modeCombo, &QComboBox::activated, - this, &DolphinFontRequester::changeMode); + connect(m_modeCombo, &QComboBox::activated, this, &DolphinFontRequester::changeMode); m_chooseFontButton = new QPushButton(i18nc("@action:button Choose font", "Choose..."), this); - connect(m_chooseFontButton, &QPushButton::clicked, - this, &DolphinFontRequester::openFontDialog); + connect(m_chooseFontButton, &QPushButton::clicked, this, &DolphinFontRequester::openFontDialog); changeMode(m_modeCombo->currentIndex()); @@ -61,7 +59,7 @@ QFont DolphinFontRequester::currentFont() const return (m_mode == CustomFont) ? m_customFont : QFontDatabase::systemFont(QFontDatabase::GeneralFont); } -void DolphinFontRequester::setCustomFont(const QFont& font) +void DolphinFontRequester::setCustomFont(const QFont &font) { m_customFont = font; } @@ -87,4 +85,3 @@ void DolphinFontRequester::changeMode(int index) setMode((index == CustomFont) ? CustomFont : SystemFont); Q_EMIT changed(); } - diff --git a/src/settings/viewmodes/dolphinfontrequester.h b/src/settings/viewmodes/dolphinfontrequester.h index 56b28f9b60..10587d774a 100644 --- a/src/settings/viewmodes/dolphinfontrequester.h +++ b/src/settings/viewmodes/dolphinfontrequester.h @@ -21,13 +21,9 @@ class DolphinFontRequester : public QWidget Q_OBJECT public: - enum Mode - { - SystemFont = 0, - CustomFont = 1 - }; + enum Mode { SystemFont = 0, CustomFont = 1 }; - explicit DolphinFontRequester(QWidget* parent); + explicit DolphinFontRequester(QWidget *parent); ~DolphinFontRequester() override; void setMode(Mode mode); @@ -40,7 +36,7 @@ public: */ QFont currentFont() const; - void setCustomFont(const QFont& font); + void setCustomFont(const QFont &font); QFont customFont() const; Q_SIGNALS: @@ -52,8 +48,8 @@ private Q_SLOTS: void changeMode(int index); private: - QComboBox* m_modeCombo; - QPushButton* m_chooseFontButton; + QComboBox *m_modeCombo; + QPushButton *m_chooseFontButton; Mode m_mode; QFont m_customFont; diff --git a/src/settings/viewmodes/viewmodesettings.cpp b/src/settings/viewmodes/viewmodesettings.cpp index 5936e29701..0cfc0634d1 100644 --- a/src/settings/viewmodes/viewmodesettings.cpp +++ b/src/settings/viewmodes/viewmodesettings.cpp @@ -51,9 +51,15 @@ ViewModeSettings::ViewModeSettings(DolphinView::Mode mode) : ViewModeSettings() { switch (mode) { - case DolphinView::IconsView: m_viewModeSettingsVariant = IconsModeSettings::self(); return; - case DolphinView::CompactView: m_viewModeSettingsVariant = CompactModeSettings::self(); return; - case DolphinView::DetailsView: m_viewModeSettingsVariant = DetailsModeSettings::self(); return; + case DolphinView::IconsView: + m_viewModeSettingsVariant = IconsModeSettings::self(); + return; + case DolphinView::CompactView: + m_viewModeSettingsVariant = CompactModeSettings::self(); + return; + case DolphinView::DetailsView: + m_viewModeSettingsVariant = DetailsModeSettings::self(); + return; default: Q_UNREACHABLE(); } @@ -63,9 +69,15 @@ ViewModeSettings::ViewModeSettings(ViewSettingsTab::Mode mode) : ViewModeSettings() { switch (mode) { - case ViewSettingsTab::IconsMode: m_viewModeSettingsVariant = IconsModeSettings::self(); return; - case ViewSettingsTab::CompactMode: m_viewModeSettingsVariant = CompactModeSettings::self(); return; - case ViewSettingsTab::DetailsMode: m_viewModeSettingsVariant = DetailsModeSettings::self(); return; + case ViewSettingsTab::IconsMode: + m_viewModeSettingsVariant = IconsModeSettings::self(); + return; + case ViewSettingsTab::CompactMode: + m_viewModeSettingsVariant = CompactModeSettings::self(); + return; + case ViewSettingsTab::DetailsMode: + m_viewModeSettingsVariant = DetailsModeSettings::self(); + return; default: Q_UNREACHABLE(); } @@ -75,9 +87,15 @@ ViewModeSettings::ViewModeSettings(KStandardItemListView::ItemLayout itemLayout) : ViewModeSettings() { switch (itemLayout) { - case KStandardItemListView::IconsLayout: m_viewModeSettingsVariant = IconsModeSettings::self(); return; - case KStandardItemListView::CompactLayout: m_viewModeSettingsVariant = CompactModeSettings::self(); return; - case KStandardItemListView::DetailsLayout: m_viewModeSettingsVariant = DetailsModeSettings::self(); return; + case KStandardItemListView::IconsLayout: + m_viewModeSettingsVariant = IconsModeSettings::self(); + return; + case KStandardItemListView::CompactLayout: + m_viewModeSettingsVariant = CompactModeSettings::self(); + return; + case KStandardItemListView::DetailsLayout: + m_viewModeSettingsVariant = DetailsModeSettings::self(); + return; default: Q_UNREACHABLE(); } @@ -85,77 +103,99 @@ ViewModeSettings::ViewModeSettings(KStandardItemListView::ItemLayout itemLayout) void ViewModeSettings::setIconSize(int iconSize) { - std::visit([iconSize](auto &&v) { - v->setIconSize(iconSize); - }, m_viewModeSettingsVariant); + std::visit( + [iconSize](auto &&v) { + v->setIconSize(iconSize); + }, + m_viewModeSettingsVariant); } int ViewModeSettings::iconSize() const { - return std::visit([](auto &&v) { - return v->iconSize(); - }, m_viewModeSettingsVariant); + return std::visit( + [](auto &&v) { + return v->iconSize(); + }, + m_viewModeSettingsVariant); } void ViewModeSettings::setPreviewSize(int previewSize) { - std::visit([previewSize](auto &&v) { - v->setPreviewSize(previewSize); - }, m_viewModeSettingsVariant); + std::visit( + [previewSize](auto &&v) { + v->setPreviewSize(previewSize); + }, + m_viewModeSettingsVariant); } int ViewModeSettings::previewSize() const { - return std::visit([](auto &&v) { - return v->previewSize(); - }, m_viewModeSettingsVariant); + return std::visit( + [](auto &&v) { + return v->previewSize(); + }, + m_viewModeSettingsVariant); } void ViewModeSettings::setUseSystemFont(bool useSystemFont) { - std::visit([useSystemFont](auto &&v) { - v->setUseSystemFont(useSystemFont); - }, m_viewModeSettingsVariant); + std::visit( + [useSystemFont](auto &&v) { + v->setUseSystemFont(useSystemFont); + }, + m_viewModeSettingsVariant); } bool ViewModeSettings::useSystemFont() const { - return std::visit([](auto &&v) { - return v->useSystemFont(); - }, m_viewModeSettingsVariant); + return std::visit( + [](auto &&v) { + return v->useSystemFont(); + }, + m_viewModeSettingsVariant); } void ViewModeSettings::setViewFont(const QFont &font) { - std::visit([&font](auto &&v) { - v->setViewFont(font); - }, m_viewModeSettingsVariant); + std::visit( + [&font](auto &&v) { + v->setViewFont(font); + }, + m_viewModeSettingsVariant); } QFont ViewModeSettings::viewFont() const { - return std::visit([](auto &&v) { - return v->viewFont(); - }, m_viewModeSettingsVariant); + return std::visit( + [](auto &&v) { + return v->viewFont(); + }, + m_viewModeSettingsVariant); } void ViewModeSettings::useDefaults(bool useDefaults) { - std::visit([useDefaults](auto &&v) { - v->useDefaults(useDefaults); - }, m_viewModeSettingsVariant); + std::visit( + [useDefaults](auto &&v) { + v->useDefaults(useDefaults); + }, + m_viewModeSettingsVariant); } void ViewModeSettings::readConfig() { - std::visit([](auto &&v) { - v->load(); - }, m_viewModeSettingsVariant); + std::visit( + [](auto &&v) { + v->load(); + }, + m_viewModeSettingsVariant); } void ViewModeSettings::save() { - std::visit([](auto &&v) { - return v->save(); - }, m_viewModeSettingsVariant); + std::visit( + [](auto &&v) { + return v->save(); + }, + m_viewModeSettingsVariant); } diff --git a/src/settings/viewmodes/viewmodesettings.h b/src/settings/viewmodes/viewmodesettings.h index d50c1cfb3e..6193c9526e 100644 --- a/src/settings/viewmodes/viewmodesettings.h +++ b/src/settings/viewmodes/viewmodesettings.h @@ -8,8 +8,8 @@ #define VIEWMODESETTINGS_H #include "kitemviews/kstandarditemlistview.h" -#include "viewsettingstab.h" #include "views/dolphinview.h" +#include "viewsettingstab.h" #include diff --git a/src/settings/viewmodes/viewsettingspage.cpp b/src/settings/viewmodes/viewsettingspage.cpp index 2e8c5b7dac..cb0b5ecee2 100644 --- a/src/settings/viewmodes/viewsettingspage.cpp +++ b/src/settings/viewmodes/viewsettingspage.cpp @@ -14,27 +14,27 @@ #include #include -ViewSettingsPage::ViewSettingsPage(QWidget* parent) : - SettingsPageBase(parent), - m_tabs() +ViewSettingsPage::ViewSettingsPage(QWidget *parent) + : SettingsPageBase(parent) + , m_tabs() { - QVBoxLayout* topLayout = new QVBoxLayout(this); + QVBoxLayout *topLayout = new QVBoxLayout(this); topLayout->setContentsMargins(0, 0, 0, 0); - QTabWidget* tabWidget = new QTabWidget(this); + QTabWidget *tabWidget = new QTabWidget(this); // Initialize 'Icons' tab - ViewSettingsTab* iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget); + ViewSettingsTab *iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget); tabWidget->addTab(iconsTab, QIcon::fromTheme(QStringLiteral("view-list-icons")), i18nc("@title:tab", "Icons")); connect(iconsTab, &ViewSettingsTab::changed, this, &ViewSettingsPage::changed); // Initialize 'Compact' tab - ViewSettingsTab* compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget); + ViewSettingsTab *compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget); tabWidget->addTab(compactTab, QIcon::fromTheme(QStringLiteral("view-list-details")), i18nc("@title:tab", "Compact")); connect(compactTab, &ViewSettingsTab::changed, this, &ViewSettingsPage::changed); // Initialize 'Details' tab - ViewSettingsTab* detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget); + ViewSettingsTab *detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget); tabWidget->addTab(detailsTab, QIcon::fromTheme(QStringLiteral("view-list-tree")), i18nc("@title:tab", "Details")); connect(detailsTab, &ViewSettingsTab::changed, this, &ViewSettingsPage::changed); @@ -51,15 +51,14 @@ ViewSettingsPage::~ViewSettingsPage() void ViewSettingsPage::applySettings() { - for (ViewSettingsTab* tab : qAsConst(m_tabs)) { + for (ViewSettingsTab *tab : qAsConst(m_tabs)) { tab->applySettings(); } } void ViewSettingsPage::restoreDefaults() { - for (ViewSettingsTab* tab : qAsConst(m_tabs)) { + for (ViewSettingsTab *tab : qAsConst(m_tabs)) { tab->restoreDefaultSettings(); } } - diff --git a/src/settings/viewmodes/viewsettingspage.h b/src/settings/viewmodes/viewsettingspage.h index 1016527e03..797c0b7120 100644 --- a/src/settings/viewmodes/viewsettingspage.h +++ b/src/settings/viewmodes/viewsettingspage.h @@ -22,7 +22,7 @@ class ViewSettingsPage : public SettingsPageBase Q_OBJECT public: - explicit ViewSettingsPage(QWidget* parent); + explicit ViewSettingsPage(QWidget *parent); ~ViewSettingsPage() override; /** @see SettingsPageBase::applySettings() */ @@ -32,7 +32,7 @@ public: void restoreDefaults() override; private: - QList m_tabs; + QList m_tabs; }; #endif diff --git a/src/settings/viewmodes/viewsettingstab.cpp b/src/settings/viewmodes/viewsettingstab.cpp index 6ac280e7be..bc465c02f7 100644 --- a/src/settings/viewmodes/viewsettingstab.cpp +++ b/src/settings/viewmodes/viewsettingstab.cpp @@ -14,8 +14,8 @@ #include "settings/viewmodes/viewmodesettings.h" #include "views/zoomlevelinfo.h" -#include #include +#include #include #include @@ -26,20 +26,20 @@ #include #include -ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget* parent) : - QWidget(parent), - m_mode(mode), - m_defaultSizeSlider(nullptr), - m_previewSizeSlider(nullptr), - m_fontRequester(nullptr), - m_widthBox(nullptr), - m_maxLinesBox(nullptr), - m_expandableFolders(nullptr), - m_recursiveDirectorySizeLimit(nullptr), - m_useRelatetiveDates(nullptr), - m_useShortDates(nullptr) +ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget *parent) + : QWidget(parent) + , m_mode(mode) + , m_defaultSizeSlider(nullptr) + , m_previewSizeSlider(nullptr) + , m_fontRequester(nullptr) + , m_widthBox(nullptr) + , m_maxLinesBox(nullptr) + , m_expandableFolders(nullptr) + , m_recursiveDirectorySizeLimit(nullptr) + , m_useRelatetiveDates(nullptr) + , m_useShortDates(nullptr) { - QFormLayout* topLayout = new QFormLayout(this); + QFormLayout *topLayout = new QFormLayout(this); // Create "Icon Size" section const int minRange = ZoomLevelInfo::minimumLevel(); @@ -49,22 +49,18 @@ ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget* parent) : m_defaultSizeSlider->setPageStep(1); m_defaultSizeSlider->setTickPosition(QSlider::TicksBelow); m_defaultSizeSlider->setRange(minRange, maxRange); - connect(m_defaultSizeSlider, &QSlider::valueChanged, - this, &ViewSettingsTab::slotDefaultSliderMoved); + connect(m_defaultSizeSlider, &QSlider::valueChanged, this, &ViewSettingsTab::slotDefaultSliderMoved); topLayout->addRow(i18nc("@label:listbox", "Default icon size:"), m_defaultSizeSlider); m_previewSizeSlider = new QSlider(Qt::Horizontal); m_previewSizeSlider->setPageStep(1); m_previewSizeSlider->setTickPosition(QSlider::TicksBelow); m_previewSizeSlider->setRange(minRange, maxRange); - connect(m_previewSizeSlider, &QSlider::valueChanged, - this, &ViewSettingsTab::slotPreviewSliderMoved); + connect(m_previewSizeSlider, &QSlider::valueChanged, this, &ViewSettingsTab::slotPreviewSliderMoved); topLayout->addRow(i18nc("@label:listbox", "Preview icon size:"), m_previewSizeSlider); - topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed)); - // Create "Label" section m_fontRequester = new DolphinFontRequester(this); topLayout->addRow(i18nc("@label:listbox", "Label font:"), m_fontRequester); @@ -109,17 +105,18 @@ ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget* parent) : itemActivationAreaGroup->addButton(m_entireRow); itemActivationAreaGroup->addButton(m_iconAndNameOnly); + // clang-format off // i18n: Users can choose here if items are opened by clicking on their name/icon or by clicking in the row. topLayout->addRow(i18nc("@title:group", "Open files and folders:"), m_entireRow); + // clang-format on topLayout->addRow(QString(), m_iconAndNameOnly); - #ifndef Q_OS_WIN // Sorting properties m_numberOfItems = new QRadioButton(i18nc("option:radio", "Number of items")); m_sizeOfContents = new QRadioButton(i18nc("option:radio", "Size of contents, up to ")); - QButtonGroup* sortingModeGroup = new QButtonGroup(this); + QButtonGroup *sortingModeGroup = new QButtonGroup(this); sortingModeGroup->addButton(m_numberOfItems); sortingModeGroup->addButton(m_sizeOfContents); @@ -142,14 +139,12 @@ ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget* parent) : QLocale local; KFormat formatter(local); - m_useRelatetiveDates = new QRadioButton(i18nc( - "option:radio as in relative date", "Relative (e.g. '%1')", formatter.formatRelativeDateTime(thirtyMinutesAgo, QLocale::ShortFormat)) - ); - m_useShortDates = new QRadioButton( - i18nc("option:radio as in absolute date", "Absolute (e.g. '%1')", local.toString(thirtyMinutesAgo, QLocale::ShortFormat)) - ); + m_useRelatetiveDates = new QRadioButton( + i18nc("option:radio as in relative date", "Relative (e.g. '%1')", formatter.formatRelativeDateTime(thirtyMinutesAgo, QLocale::ShortFormat))); + m_useShortDates = + new QRadioButton(i18nc("option:radio as in absolute date", "Absolute (e.g. '%1')", local.toString(thirtyMinutesAgo, QLocale::ShortFormat))); - QButtonGroup* dateFormatGroup = new QButtonGroup(this); + QButtonGroup *dateFormatGroup = new QButtonGroup(this); dateFormatGroup->addButton(m_useRelatetiveDates); dateFormatGroup->addButton(m_useShortDates); @@ -271,16 +266,16 @@ void ViewSettingsTab::loadSettings() m_entireRow->setChecked(DetailsModeSettings::highlightEntireRow()); m_iconAndNameOnly->setChecked(!m_entireRow->isChecked()); m_expandableFolders->setChecked(DetailsModeSettings::expandableFolders()); - #ifndef Q_OS_WIN - if (DetailsModeSettings::directorySizeCount()) { - m_numberOfItems->setChecked(true); - m_recursiveDirectorySizeLimit->setEnabled(false); - } else { - m_sizeOfContents->setChecked(true); - m_recursiveDirectorySizeLimit->setEnabled(true); - } - m_recursiveDirectorySizeLimit->setValue(DetailsModeSettings::recursiveDirectorySizeLimit()); - #endif +#ifndef Q_OS_WIN + if (DetailsModeSettings::directorySizeCount()) { + m_numberOfItems->setChecked(true); + m_recursiveDirectorySizeLimit->setEnabled(false); + } else { + m_sizeOfContents->setChecked(true); + m_recursiveDirectorySizeLimit->setEnabled(true); + } + m_recursiveDirectorySizeLimit->setValue(DetailsModeSettings::recursiveDirectorySizeLimit()); +#endif m_useRelatetiveDates->setChecked(DetailsModeSettings::useShortRelativeDates()); m_useShortDates->setChecked(!DetailsModeSettings::useShortRelativeDates()); break; @@ -296,9 +291,7 @@ void ViewSettingsTab::loadSettings() const QSize previewSize(settings.previewSize(), settings.previewSize()); m_previewSizeSlider->setValue(ZoomLevelInfo::zoomLevelForIconSize(previewSize)); - m_fontRequester->setMode(settings.useSystemFont() - ? DolphinFontRequester::SystemFont - : DolphinFontRequester::CustomFont); + m_fontRequester->setMode(settings.useSystemFont() ? DolphinFontRequester::SystemFont : DolphinFontRequester::CustomFont); QFont font(settings.viewFont()); m_fontRequester->setCustomFont(font); @@ -314,7 +307,7 @@ void ViewSettingsTab::slotPreviewSliderMoved(int value) showToolTip(m_previewSizeSlider, value); } -void ViewSettingsTab::showToolTip(QSlider* slider, int value) +void ViewSettingsTab::showToolTip(QSlider *slider, int value) { const int size = ZoomLevelInfo::iconSizeForZoomLevel(value); slider->setToolTip(i18ncp("@info:tooltip", "Size: 1 pixel", "Size: %1 pixels", size)); @@ -326,4 +319,3 @@ void ViewSettingsTab::showToolTip(QSlider* slider, int value) QHelpEvent toolTipEvent(QEvent::ToolTip, QPoint(0, 0), slider->mapToGlobal(global)); QApplication::sendEvent(slider, &toolTipEvent); } - diff --git a/src/settings/viewmodes/viewsettingstab.h b/src/settings/viewmodes/viewsettingstab.h index 4a4dc5694d..88bdd944b9 100644 --- a/src/settings/viewmodes/viewsettingstab.h +++ b/src/settings/viewmodes/viewsettingstab.h @@ -24,14 +24,9 @@ class ViewSettingsTab : public QWidget Q_OBJECT public: - enum Mode - { - IconsMode, - CompactMode, - DetailsMode - }; + enum Mode { IconsMode, CompactMode, DetailsMode }; - explicit ViewSettingsTab(Mode mode, QWidget* parent = nullptr); + explicit ViewSettingsTab(Mode mode, QWidget *parent = nullptr); ~ViewSettingsTab() override; void applySettings(); @@ -44,26 +39,27 @@ private Q_SLOTS: void slotDefaultSliderMoved(int value); void slotPreviewSliderMoved(int value); + private: void loadSettings(); - void showToolTip(QSlider* slider, int value); + void showToolTip(QSlider *slider, int value); private: Mode m_mode; - QSlider* m_defaultSizeSlider; - QSlider* m_previewSizeSlider; + QSlider *m_defaultSizeSlider; + QSlider *m_previewSizeSlider; - DolphinFontRequester* m_fontRequester; - QComboBox* m_widthBox; - QComboBox* m_maxLinesBox; - QRadioButton* m_entireRow; - QRadioButton* m_iconAndNameOnly; - QCheckBox* m_expandableFolders; - QRadioButton* m_numberOfItems; - QRadioButton* m_sizeOfContents; - QSpinBox* m_recursiveDirectorySizeLimit; - QRadioButton* m_useRelatetiveDates; - QRadioButton* m_useShortDates; + DolphinFontRequester *m_fontRequester; + QComboBox *m_widthBox; + QComboBox *m_maxLinesBox; + QRadioButton *m_entireRow; + QRadioButton *m_iconAndNameOnly; + QCheckBox *m_expandableFolders; + QRadioButton *m_numberOfItems; + QRadioButton *m_sizeOfContents; + QSpinBox *m_recursiveDirectorySizeLimit; + QRadioButton *m_useRelatetiveDates; + QRadioButton *m_useShortDates; }; #endif diff --git a/src/settings/viewpropertiesdialog.cpp b/src/settings/viewpropertiesdialog.cpp index 30995f1f72..d0828422f4 100644 --- a/src/settings/viewpropertiesdialog.cpp +++ b/src/settings/viewpropertiesdialog.cpp @@ -21,7 +21,7 @@ #include #if HAVE_BALOO - #include +#include #endif #include @@ -36,30 +36,30 @@ #include -ViewPropertiesDialog::ViewPropertiesDialog(DolphinView* dolphinView) : - QDialog(dolphinView), - m_isDirty(false), - m_dolphinView(dolphinView), - m_viewProps(nullptr), - m_viewMode(nullptr), - m_sortOrder(nullptr), - m_sorting(nullptr), - m_sortFoldersFirst(nullptr), - m_sortHiddenLast(nullptr), - m_previewsShown(nullptr), - m_showInGroups(nullptr), - m_showHiddenFiles(nullptr), - m_applyToCurrentFolder(nullptr), - m_applyToSubFolders(nullptr), - m_applyToAllFolders(nullptr), - m_useAsDefault(nullptr) +ViewPropertiesDialog::ViewPropertiesDialog(DolphinView *dolphinView) + : QDialog(dolphinView) + , m_isDirty(false) + , m_dolphinView(dolphinView) + , m_viewProps(nullptr) + , m_viewMode(nullptr) + , m_sortOrder(nullptr) + , m_sorting(nullptr) + , m_sortFoldersFirst(nullptr) + , m_sortHiddenLast(nullptr) + , m_previewsShown(nullptr) + , m_showInGroups(nullptr) + , m_showHiddenFiles(nullptr) + , m_applyToCurrentFolder(nullptr) + , m_applyToSubFolders(nullptr) + , m_applyToAllFolders(nullptr) + , m_useAsDefault(nullptr) { Q_ASSERT(dolphinView); const bool useGlobalViewProps = GeneralSettings::globalViewProps(); setWindowTitle(i18nc("@title:window", "View Display Style")); - const QUrl& url = dolphinView->url(); + const QUrl &url = dolphinView->url(); m_viewProps = new ViewProperties(url); m_viewProps->setAutoSaveEnabled(false); @@ -79,7 +79,7 @@ ViewPropertiesDialog::ViewPropertiesDialog(DolphinView* dolphinView) : m_sorting = new QComboBox(); const QList rolesInfo = KFileItemModel::rolesInformation(); - for (const KFileItemModel::RoleInfo& info : rolesInfo) { + for (const KFileItemModel::RoleInfo &info : rolesInfo) { m_sorting->addItem(info.translation, info.role); } @@ -118,24 +118,23 @@ ViewPropertiesDialog::ViewPropertiesDialog(DolphinView* dolphinView) : connect(m_listWidget, &QListWidget::itemChanged, this, &ViewPropertiesDialog::slotItemChanged); m_listWidget->setSelectionMode(QAbstractItemView::NoSelection); const QList rolesInfo = KFileItemModel::rolesInformation(); - for (const KFileItemModel::RoleInfo& info : rolesInfo) { - QListWidgetItem* item = new QListWidgetItem(info.translation, m_listWidget); + for (const KFileItemModel::RoleInfo &info : rolesInfo) { + QListWidgetItem *item = new QListWidgetItem(info.translation, m_listWidget); item->setCheckState(visibleRoles.contains(info.role) ? Qt::Checked : Qt::Unchecked); - const bool enable = ((!info.requiresBaloo && !info.requiresIndexer) || - (info.requiresBaloo) || - (info.requiresIndexer && indexingEnabled)) && info.role != "text"; + const bool enable = + ((!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled)) && info.role != "text"; if (!enable) { item->setFlags(item->flags() & ~Qt::ItemIsEnabled); } } - QLabel* additionalViewOptionsLabel = new QLabel(i18n("Choose what to see on each file or folder:")); + QLabel *additionalViewOptionsLabel = new QLabel(i18n("Choose what to see on each file or folder:")); innerLayout->addWidget(additionalViewOptionsLabel); innerLayout->addWidget(m_listWidget); } - QHBoxLayout* sortingLayout = new QHBoxLayout(); + QHBoxLayout *sortingLayout = new QHBoxLayout(); sortingLayout->setContentsMargins(0, 0, 0, 0); sortingLayout->addWidget(m_sortOrder); sortingLayout->addWidget(m_sorting); @@ -151,36 +150,25 @@ ViewPropertiesDialog::ViewPropertiesDialog(DolphinView* dolphinView) : layout->addRow(QString(), m_showHiddenFiles); layout->addRow(QString(), m_sortHiddenLast); - connect(m_viewMode, &QComboBox::currentIndexChanged, - this, &ViewPropertiesDialog::slotViewModeChanged); - connect(m_sorting, &QComboBox::currentIndexChanged, - this, &ViewPropertiesDialog::slotSortingChanged); - connect(m_sortOrder, &QComboBox::currentIndexChanged, - this, &ViewPropertiesDialog::slotSortOrderChanged); - connect(m_sortFoldersFirst, &QCheckBox::clicked, - this, &ViewPropertiesDialog::slotSortFoldersFirstChanged); - connect(m_sortHiddenLast, &QCheckBox::clicked, - this, &ViewPropertiesDialog::slotSortHiddenLastChanged); - connect(m_previewsShown, &QCheckBox::clicked, - this, &ViewPropertiesDialog::slotShowPreviewChanged); - connect(m_showInGroups, &QCheckBox::clicked, - this, &ViewPropertiesDialog::slotGroupedSortingChanged); - connect(m_showHiddenFiles, &QCheckBox::clicked, - this, &ViewPropertiesDialog::slotShowHiddenFilesChanged); + connect(m_viewMode, &QComboBox::currentIndexChanged, this, &ViewPropertiesDialog::slotViewModeChanged); + connect(m_sorting, &QComboBox::currentIndexChanged, this, &ViewPropertiesDialog::slotSortingChanged); + connect(m_sortOrder, &QComboBox::currentIndexChanged, this, &ViewPropertiesDialog::slotSortOrderChanged); + connect(m_sortFoldersFirst, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotSortFoldersFirstChanged); + connect(m_sortHiddenLast, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotSortHiddenLastChanged); + connect(m_previewsShown, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotShowPreviewChanged); + connect(m_showInGroups, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotGroupedSortingChanged); + connect(m_showHiddenFiles, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotShowHiddenFilesChanged); // Only show the following settings if the view properties are remembered // for each directory: if (!useGlobalViewProps) { // create 'Apply View Properties To' group - m_applyToCurrentFolder = new QRadioButton(i18nc("@option:radio Apply View Properties To", - "Current folder")); + m_applyToCurrentFolder = new QRadioButton(i18nc("@option:radio Apply View Properties To", "Current folder")); m_applyToCurrentFolder->setChecked(true); - m_applyToSubFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To", - "Current folder and sub-folders")); - m_applyToAllFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To", - "All folders")); + m_applyToSubFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To", "Current folder and sub-folders")); + m_applyToAllFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To", "All folders")); - QButtonGroup* applyGroup = new QButtonGroup(this); + QButtonGroup *applyGroup = new QButtonGroup(this); applyGroup->addButton(m_applyToCurrentFolder); applyGroup->addButton(m_applyToSubFolders); applyGroup->addButton(m_applyToAllFolders); @@ -195,14 +183,10 @@ ViewPropertiesDialog::ViewPropertiesDialog(DolphinView* dolphinView) : m_useAsDefault = new QCheckBox(i18nc("@option:check", "Use as default view settings"), this); layout->addRow(QString(), m_useAsDefault); - connect(m_applyToCurrentFolder, &QRadioButton::clicked, - this, &ViewPropertiesDialog::markAsDirty); - connect(m_applyToSubFolders, &QRadioButton::clicked, - this, &ViewPropertiesDialog::markAsDirty); - connect(m_applyToAllFolders, &QRadioButton::clicked, - this, &ViewPropertiesDialog::markAsDirty); - connect(m_useAsDefault, &QCheckBox::clicked, - this, &ViewPropertiesDialog::markAsDirty); + connect(m_applyToCurrentFolder, &QRadioButton::clicked, this, &ViewPropertiesDialog::markAsDirty); + connect(m_applyToSubFolders, &QRadioButton::clicked, this, &ViewPropertiesDialog::markAsDirty); + connect(m_applyToAllFolders, &QRadioButton::clicked, this, &ViewPropertiesDialog::markAsDirty); + connect(m_useAsDefault, &QCheckBox::clicked, this, &ViewPropertiesDialog::markAsDirty); } layout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed)); @@ -335,9 +319,9 @@ void ViewPropertiesDialog::applyViewProperties() QList visibleRoles; int index = 0; const QList rolesInfo = KFileItemModel::rolesInformation(); - for (const KFileItemModel::RoleInfo& info : rolesInfo) { - const QListWidgetItem* item = m_listWidget->item(index); - if (item->checkState() == Qt::Checked) { + for (const KFileItemModel::RoleInfo &info : rolesInfo) { + const QListWidgetItem *item = m_listWidget->item(index); + if (item->checkState() == Qt::Checked) { visibleRoles.append(info.role); } ++index; @@ -350,20 +334,14 @@ void ViewPropertiesDialog::applyViewProperties() if (applyToSubFolders) { const QString text(i18nc("@info", "The view properties of all sub-folders will be changed. Do you want to continue?")); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - if (KMessageBox::questionTwoActions(this, text, {}, - KStandardGuiItem::cont(), - KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) { + if (KMessageBox::questionTwoActions(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) { #else - if (KMessageBox::questionYesNo(this, text, {}, - KStandardGuiItem::cont(), - KStandardGuiItem::cancel()) == KMessageBox::No) { + if (KMessageBox::questionYesNo(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::No) { #endif return; } - ViewPropsProgressInfo* info = new ViewPropsProgressInfo(m_dolphinView, - m_dolphinView->url(), - *m_viewProps); + ViewPropsProgressInfo *info = new ViewPropsProgressInfo(m_dolphinView, m_dolphinView->url(), *m_viewProps); info->setAttribute(Qt::WA_DeleteOnClose); info->setWindowModality(Qt::NonModal); info->show(); @@ -390,20 +368,16 @@ void ViewPropertiesDialog::applyViewProperties() if (applyToAllFolders) { const QString text(i18nc("@info", "The view properties of all folders will be changed. Do you want to continue?")); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - if (KMessageBox::questionTwoActions(this, text, {}, - KStandardGuiItem::cont(), - KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) { + if (KMessageBox::questionTwoActions(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) { #else - if (KMessageBox::questionYesNo(this, text, {}, - KStandardGuiItem::cont(), - KStandardGuiItem::cancel()) == KMessageBox::No) { + if (KMessageBox::questionYesNo(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::No) { #endif return; } // Updating the global view properties time stamp in the general settings makes // all existing viewproperties invalid, as they have a smaller time stamp. - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); settings->setViewPropsTimestamp(QDateTime::currentDateTime()); settings->save(); } @@ -427,10 +401,17 @@ void ViewPropertiesDialog::loadSettings() { // Load view mode switch (m_viewProps->viewMode()) { - case DolphinView::IconsView: m_viewMode->setCurrentIndex(0); break; - case DolphinView::CompactView: m_viewMode->setCurrentIndex(1); break; - case DolphinView::DetailsView: m_viewMode->setCurrentIndex(2); break; - default: break; + case DolphinView::IconsView: + m_viewMode->setCurrentIndex(0); + break; + case DolphinView::CompactView: + m_viewMode->setCurrentIndex(1); + break; + case DolphinView::DetailsView: + m_viewMode->setCurrentIndex(2); + break; + default: + break; } // Load sort order and sorting @@ -456,4 +437,3 @@ void ViewPropertiesDialog::loadSettings() m_showHiddenFiles->setChecked(m_viewProps->hiddenFilesShown()); markAsDirty(false); } - diff --git a/src/settings/viewpropertiesdialog.h b/src/settings/viewpropertiesdialog.h index c58fda5c00..d1f056fbbf 100644 --- a/src/settings/viewpropertiesdialog.h +++ b/src/settings/viewpropertiesdialog.h @@ -33,7 +33,7 @@ class DOLPHIN_EXPORT ViewPropertiesDialog : public QDialog Q_OBJECT public: - explicit ViewPropertiesDialog(DolphinView* dolphinView); + explicit ViewPropertiesDialog(DolphinView *dolphinView); ~ViewPropertiesDialog() override; public Q_SLOTS: @@ -61,22 +61,22 @@ private: private: bool m_isDirty; - DolphinView* m_dolphinView; - ViewProperties* m_viewProps; + DolphinView *m_dolphinView; + ViewProperties *m_viewProps; - QComboBox* m_viewMode; - QComboBox* m_sortOrder; - QComboBox* m_sorting; - QCheckBox* m_sortFoldersFirst; - QCheckBox* m_sortHiddenLast; - QCheckBox* m_previewsShown; - QCheckBox* m_showInGroups; - QCheckBox* m_showHiddenFiles; - QRadioButton* m_applyToCurrentFolder; - QRadioButton* m_applyToSubFolders; - QRadioButton* m_applyToAllFolders; - QCheckBox* m_useAsDefault; - QListWidget* m_listWidget; + QComboBox *m_viewMode; + QComboBox *m_sortOrder; + QComboBox *m_sorting; + QCheckBox *m_sortFoldersFirst; + QCheckBox *m_sortHiddenLast; + QCheckBox *m_previewsShown; + QCheckBox *m_showInGroups; + QCheckBox *m_showHiddenFiles; + QRadioButton *m_applyToCurrentFolder; + QRadioButton *m_applyToSubFolders; + QRadioButton *m_applyToAllFolders; + QCheckBox *m_useAsDefault; + QListWidget *m_listWidget; }; #endif diff --git a/src/settings/viewpropsprogressinfo.cpp b/src/settings/viewpropsprogressinfo.cpp index 894e7ff641..a3692be51f 100644 --- a/src/settings/viewpropsprogressinfo.cpp +++ b/src/settings/viewpropsprogressinfo.cpp @@ -18,17 +18,15 @@ #include #include -ViewPropsProgressInfo::ViewPropsProgressInfo(QWidget* parent, - const QUrl& dir, - const ViewProperties& viewProps) : - QDialog(parent), - m_dir(dir), - m_viewProps(nullptr), - m_label(nullptr), - m_progressBar(nullptr), - m_dirSizeJob(nullptr), - m_applyViewPropsJob(nullptr), - m_timer(nullptr) +ViewPropsProgressInfo::ViewPropsProgressInfo(QWidget *parent, const QUrl &dir, const ViewProperties &viewProps) + : QDialog(parent) + , m_dir(dir) + , m_viewProps(nullptr) + , m_label(nullptr) + , m_progressBar(nullptr) + , m_dirSizeJob(nullptr) + , m_applyViewPropsJob(nullptr) + , m_timer(nullptr) { const QSize minSize = minimumSize(); setMinimumSize(QSize(320, minSize.height())); @@ -64,15 +62,13 @@ ViewPropsProgressInfo::ViewPropsProgressInfo(QWidget* parent, // allows to give a progress indication for the user when applying the view // properties later. m_dirSizeJob = KIO::directorySize(dir); - connect(m_dirSizeJob, &KIO::DirectorySizeJob::result, - this, &ViewPropsProgressInfo::applyViewProperties); + connect(m_dirSizeJob, &KIO::DirectorySizeJob::result, this, &ViewPropsProgressInfo::applyViewProperties); // The directory size job cannot emit any progress signal, as it is not aware // about the total number of directories. Therefor a timer is triggered, which // periodically updates the current directory count. m_timer = new QTimer(this); - connect(m_timer, &QTimer::timeout, - this, &ViewPropsProgressInfo::updateProgress); + connect(m_timer, &QTimer::timeout, this, &ViewPropsProgressInfo::updateProgress); m_timer->start(300); } @@ -82,7 +78,7 @@ ViewPropsProgressInfo::~ViewPropsProgressInfo() m_viewProps = nullptr; } -void ViewPropsProgressInfo::closeEvent(QCloseEvent* event) +void ViewPropsProgressInfo::closeEvent(QCloseEvent *event) { m_timer->stop(); m_applyViewPropsJob = nullptr; @@ -130,7 +126,5 @@ void ViewPropsProgressInfo::applyViewProperties() m_dirSizeJob = nullptr; m_applyViewPropsJob = new ApplyViewPropsJob(m_dir, *m_viewProps); - connect(m_applyViewPropsJob, &ApplyViewPropsJob::result, - this, &ViewPropsProgressInfo::close); + connect(m_applyViewPropsJob, &ApplyViewPropsJob::result, this, &ViewPropsProgressInfo::close); } - diff --git a/src/settings/viewpropsprogressinfo.h b/src/settings/viewpropsprogressinfo.h index 61c358f390..5771788707 100644 --- a/src/settings/viewpropsprogressinfo.h +++ b/src/settings/viewpropsprogressinfo.h @@ -36,14 +36,12 @@ public: * @param viewProps View properties for the directory \a dir including its * sub directories. */ - ViewPropsProgressInfo(QWidget* parent, - const QUrl& dir, - const ViewProperties& viewProps); + ViewPropsProgressInfo(QWidget *parent, const QUrl &dir, const ViewProperties &viewProps); ~ViewPropsProgressInfo() override; protected: - void closeEvent(QCloseEvent* event) override; + void closeEvent(QCloseEvent *event) override; public Q_SLOTS: void reject() override; @@ -54,14 +52,14 @@ private Q_SLOTS: private: QUrl m_dir; - ViewProperties* m_viewProps; + ViewProperties *m_viewProps; - QLabel* m_label; - QProgressBar* m_progressBar; + QLabel *m_label; + QProgressBar *m_progressBar; - KIO::DirectorySizeJob* m_dirSizeJob; - ApplyViewPropsJob* m_applyViewPropsJob; - QTimer* m_timer; + KIO::DirectorySizeJob *m_dirSizeJob; + ApplyViewPropsJob *m_applyViewPropsJob; + QTimer *m_timer; }; #endif diff --git a/src/statusbar/dolphinstatusbar.cpp b/src/statusbar/dolphinstatusbar.cpp index 70ebe0c3cd..42ce58f644 100644 --- a/src/statusbar/dolphinstatusbar.cpp +++ b/src/statusbar/dolphinstatusbar.cpp @@ -24,24 +24,25 @@ #include #include -namespace { - const int UpdateDelay = 50; +namespace +{ +const int UpdateDelay = 50; } -DolphinStatusBar::DolphinStatusBar(QWidget* parent) : - QWidget(parent), - m_text(), - m_defaultText(), - m_label(nullptr), - m_zoomLabel(nullptr), - m_spaceInfo(nullptr), - m_zoomSlider(nullptr), - m_progressBar(nullptr), - m_stopButton(nullptr), - m_progress(100), - m_showProgressBarTimer(nullptr), - m_delayUpdateTimer(nullptr), - m_textTimestamp() +DolphinStatusBar::DolphinStatusBar(QWidget *parent) + : QWidget(parent) + , m_text() + , m_defaultText() + , m_label(nullptr) + , m_zoomLabel(nullptr) + , m_spaceInfo(nullptr) + , m_zoomSlider(nullptr) + , m_progressBar(nullptr) + , m_stopButton(nullptr) + , m_progress(100) + , m_showProgressBarTimer(nullptr) + , m_delayUpdateTimer(nullptr) + , m_textTimestamp() { // Initialize text label m_label = new KSqueezedTextLabel(m_text, this); @@ -49,7 +50,7 @@ DolphinStatusBar::DolphinStatusBar(QWidget* parent) : m_label->setTextFormat(Qt::PlainText); // Initialize zoom slider's explanatory label - m_zoomLabel = new QLabel(i18nc("Used as a noun, i.e. 'Here is the zoom level:'","Zoom:"), this); + m_zoomLabel = new QLabel(i18nc("Used as a noun, i.e. 'Here is the zoom level:'", "Zoom:"), this); // Initialize zoom widget m_zoomSlider = new QSlider(Qt::Horizontal, this); @@ -89,8 +90,7 @@ DolphinStatusBar::DolphinStatusBar(QWidget* parent) : m_delayUpdateTimer = new QTimer(this); m_delayUpdateTimer->setInterval(UpdateDelay); m_delayUpdateTimer->setSingleShot(true); - connect(m_delayUpdateTimer, &QTimer::timeout, - this, &DolphinStatusBar::updateLabelText); + connect(m_delayUpdateTimer, &QTimer::timeout, this, &DolphinStatusBar::updateLabelText); // Initialize top layout and size policies const int fontHeight = QFontMetrics(m_label->font()).height(); @@ -112,7 +112,7 @@ DolphinStatusBar::DolphinStatusBar(QWidget* parent) : m_progressBar->setFixedHeight(zoomSliderHeight); m_progressBar->setMaximumWidth(fontMetrics.averageCharWidth() * 20); - QHBoxLayout* topLayout = new QHBoxLayout(this); + QHBoxLayout *topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(2, 0, 2, 0); topLayout->setSpacing(4); topLayout->addWidget(m_label, 1); @@ -125,22 +125,23 @@ DolphinStatusBar::DolphinStatusBar(QWidget* parent) : setVisible(GeneralSettings::showStatusBar()); setExtensionsVisible(true); - setWhatsThis(xi18nc("@info:whatsthis Statusbar", "This is " - "the Statusbar. It contains three elements " - "by default (left to right):A text field" - " that displays the size of selected items. If only " - "one item is selected the name and type is shown as well." - "A zoom slider that allows you " - "to adjust the size of the icons in the view." - "Space information about the " - "current storage device.")); + setWhatsThis(xi18nc("@info:whatsthis Statusbar", + "This is " + "the Statusbar. It contains three elements " + "by default (left to right):A text field" + " that displays the size of selected items. If only " + "one item is selected the name and type is shown as well." + "A zoom slider that allows you " + "to adjust the size of the icons in the view." + "Space information about the " + "current storage device.")); } DolphinStatusBar::~DolphinStatusBar() { } -void DolphinStatusBar::setText(const QString& text) +void DolphinStatusBar::setText(const QString &text) { if (m_text == text) { return; @@ -158,7 +159,7 @@ QString DolphinStatusBar::text() const return m_text; } -void DolphinStatusBar::setProgressText(const QString& text) +void DolphinStatusBar::setProgressText(const QString &text) { m_progressTextLabel->setText(text); } @@ -208,7 +209,7 @@ void DolphinStatusBar::resetToDefaultText() } } -void DolphinStatusBar::setDefaultText(const QString& text) +void DolphinStatusBar::setDefaultText(const QString &text) { m_defaultText = text; updateLabelText(); @@ -219,7 +220,7 @@ QString DolphinStatusBar::defaultText() const return m_defaultText; } -void DolphinStatusBar::setUrl(const QUrl& url) +void DolphinStatusBar::setUrl(const QUrl &url) { if (GeneralSettings::showSpaceInfo()) { m_spaceInfo->setUrl(url); @@ -254,21 +255,21 @@ void DolphinStatusBar::updateSpaceInfo() m_spaceInfo->update(); } -void DolphinStatusBar::contextMenuEvent(QContextMenuEvent* event) +void DolphinStatusBar::contextMenuEvent(QContextMenuEvent *event) { Q_UNUSED(event) QMenu menu(this); - QAction* showZoomSliderAction = menu.addAction(i18nc("@action:inmenu", "Show Zoom Slider")); + QAction *showZoomSliderAction = menu.addAction(i18nc("@action:inmenu", "Show Zoom Slider")); showZoomSliderAction->setCheckable(true); showZoomSliderAction->setChecked(GeneralSettings::showZoomSlider()); - QAction* showSpaceInfoAction = menu.addAction(i18nc("@action:inmenu", "Show Space Information")); + QAction *showSpaceInfoAction = menu.addAction(i18nc("@action:inmenu", "Show Space Information")); showSpaceInfoAction->setCheckable(true); showSpaceInfoAction->setChecked(GeneralSettings::showSpaceInfo()); - const QAction* action = menu.exec(QCursor::pos()); + const QAction *action = menu.exec(QCursor::pos()); if (action == showZoomSliderAction) { const bool visible = showZoomSliderAction->isChecked(); GeneralSettings::setShowZoomSlider(visible); @@ -334,4 +335,3 @@ void DolphinStatusBar::setExtensionsVisible(bool visible) m_zoomSlider->setVisible(showZoomSlider); m_zoomLabel->setVisible(showZoomSlider); } - diff --git a/src/statusbar/dolphinstatusbar.h b/src/statusbar/dolphinstatusbar.h index 7b4434539c..c3773d4389 100644 --- a/src/statusbar/dolphinstatusbar.h +++ b/src/statusbar/dolphinstatusbar.h @@ -30,7 +30,7 @@ class DolphinStatusBar : public QWidget Q_OBJECT public: - explicit DolphinStatusBar(QWidget* parent); + explicit DolphinStatusBar(QWidget *parent); ~DolphinStatusBar() override; QString text() const; @@ -40,7 +40,7 @@ public: * DolphinStatusBar::setProgress() should be invoked * afterwards each time the progress changes. */ - void setProgressText(const QString& text); + void setProgressText(const QString &text); QString progressText() const; /** @@ -63,7 +63,7 @@ public: * Sets the default text, which is shown if the status bar * is rest by DolphinStatusBar::resetToDefaultText(). */ - void setDefaultText(const QString& text); + void setDefaultText(const QString &text); QString defaultText() const; QUrl url() const; @@ -80,8 +80,8 @@ public: void updateSpaceInfo(); public Q_SLOTS: - void setText(const QString& text); - void setUrl(const QUrl& url); + void setText(const QString &text); + void setUrl(const QUrl &url); void setZoomLevel(int zoomLevel); Q_SIGNALS: @@ -93,7 +93,7 @@ Q_SIGNALS: void zoomLevelChanged(int zoomLevel); protected: - void contextMenuEvent(QContextMenuEvent* event) override; + void contextMenuEvent(QContextMenuEvent *event) override; private Q_SLOTS: void showZoomSliderToolTip(int zoomLevel); @@ -123,19 +123,19 @@ private: private: QString m_text; QString m_defaultText; - KSqueezedTextLabel* m_label; - QLabel* m_zoomLabel; - StatusBarSpaceInfo* m_spaceInfo; + KSqueezedTextLabel *m_label; + QLabel *m_zoomLabel; + StatusBarSpaceInfo *m_spaceInfo; - QSlider* m_zoomSlider; + QSlider *m_zoomSlider; - QLabel* m_progressTextLabel; - QProgressBar* m_progressBar; - QToolButton* m_stopButton; + QLabel *m_progressTextLabel; + QProgressBar *m_progressBar; + QToolButton *m_stopButton; int m_progress; - QTimer* m_showProgressBarTimer; + QTimer *m_showProgressBarTimer; - QTimer* m_delayUpdateTimer; + QTimer *m_delayUpdateTimer; QTime m_textTimestamp; }; diff --git a/src/statusbar/mountpointobserver.cpp b/src/statusbar/mountpointobserver.cpp index 7dbe631b53..c24e9e2449 100644 --- a/src/statusbar/mountpointobserver.cpp +++ b/src/statusbar/mountpointobserver.cpp @@ -10,16 +10,16 @@ #include -MountPointObserver::MountPointObserver(const QUrl& url, QObject* parent) : - QObject(parent), - m_url(url), - m_referenceCount(0) +MountPointObserver::MountPointObserver(const QUrl &url, QObject *parent) + : QObject(parent) + , m_url(url) + , m_referenceCount(0) { } -MountPointObserver* MountPointObserver::observerForUrl(const QUrl& url) +MountPointObserver *MountPointObserver::observerForUrl(const QUrl &url) { - MountPointObserver* observer = MountPointObserverCache::instance()->observerForUrl(url); + MountPointObserver *observer = MountPointObserverCache::instance()->observerForUrl(url); return observer; } @@ -28,12 +28,12 @@ void MountPointObserver::update() if (m_referenceCount == 0) { delete this; } else { - KIO::FileSystemFreeSpaceJob* job = KIO::fileSystemFreeSpace(m_url); + KIO::FileSystemFreeSpaceJob *job = KIO::fileSystemFreeSpace(m_url); connect(job, &KIO::FileSystemFreeSpaceJob::result, this, &MountPointObserver::freeSpaceResult); } } -void MountPointObserver::freeSpaceResult(KIO::Job* job, KIO::filesize_t size, KIO::filesize_t available) +void MountPointObserver::freeSpaceResult(KIO::Job *job, KIO::filesize_t size, KIO::filesize_t available) { if (!job->error()) { Q_EMIT spaceInfoChanged(size, available); diff --git a/src/statusbar/mountpointobserver.h b/src/statusbar/mountpointobserver.h index 9f5346d496..d26a0e7dea 100644 --- a/src/statusbar/mountpointobserver.h +++ b/src/statusbar/mountpointobserver.h @@ -40,8 +40,10 @@ class MountPointObserver : public QObject { Q_OBJECT - explicit MountPointObserver(const QUrl& url, QObject* parent = nullptr); - ~MountPointObserver() override {} + explicit MountPointObserver(const QUrl &url, QObject *parent = nullptr); + ~MountPointObserver() override + { + } public: /** @@ -49,7 +51,10 @@ public: * internal reference count is increased then. When the observer is not needed any more, * deref() should be called, which decreases the reference count again. */ - void ref() { ++m_referenceCount; } + void ref() + { + ++m_referenceCount; + } /** * This function can be used to indicate that the caller does not need this MountPointObserver @@ -66,7 +71,7 @@ public: * Returns a MountPointObserver for the given \a url. If the caller intends to continue using * the returned object, it must call its ref() method. */ - static MountPointObserver* observerForUrl(const QUrl& url); + static MountPointObserver *observerForUrl(const QUrl &url); Q_SIGNALS: /** @@ -82,7 +87,7 @@ public Q_SLOTS: void update(); private Q_SLOTS: - void freeSpaceResult(KIO::Job* job, KIO::filesize_t size, KIO::filesize_t available); + void freeSpaceResult(KIO::Job *job, KIO::filesize_t size, KIO::filesize_t available); private: const QUrl m_url; diff --git a/src/statusbar/mountpointobservercache.cpp b/src/statusbar/mountpointobservercache.cpp index 9bab3d5f28..b0675d1f59 100644 --- a/src/statusbar/mountpointobservercache.cpp +++ b/src/statusbar/mountpointobservercache.cpp @@ -19,11 +19,10 @@ public: }; Q_GLOBAL_STATIC(MountPointObserverCacheSingleton, s_MountPointObserverCache) - -MountPointObserverCache::MountPointObserverCache() : - m_observerForMountPoint(), - m_mountPointForObserver(), - m_updateTimer(nullptr) +MountPointObserverCache::MountPointObserverCache() + : m_observerForMountPoint() + , m_mountPointForObserver() + , m_updateTimer(nullptr) { m_updateTimer = new QTimer(this); } @@ -32,12 +31,12 @@ MountPointObserverCache::~MountPointObserverCache() { } -MountPointObserverCache* MountPointObserverCache::instance() +MountPointObserverCache *MountPointObserverCache::instance() { return &s_MountPointObserverCache->instance; } -MountPointObserver* MountPointObserverCache::observerForUrl(const QUrl& url) +MountPointObserver *MountPointObserverCache::observerForUrl(const QUrl &url) { QUrl cachedObserverUrl; // If the url is a local path we can extract the root dir by checking the mount points. @@ -55,7 +54,7 @@ MountPointObserver* MountPointObserverCache::observerForUrl(const QUrl& url) cachedObserverUrl = url; } - MountPointObserver* observer = m_observerForMountPoint.value(cachedObserverUrl); + MountPointObserver *observer = m_observerForMountPoint.value(cachedObserverUrl); if (!observer) { observer = new MountPointObserver(cachedObserverUrl, this); m_observerForMountPoint.insert(cachedObserverUrl, observer); @@ -74,10 +73,10 @@ MountPointObserver* MountPointObserverCache::observerForUrl(const QUrl& url) return observer; } -void MountPointObserverCache::slotObserverDestroyed(QObject* observer) +void MountPointObserverCache::slotObserverDestroyed(QObject *observer) { Q_ASSERT(m_mountPointForObserver.contains(observer)); - const QUrl& url = m_mountPointForObserver.value(observer); + const QUrl &url = m_mountPointForObserver.value(observer); Q_ASSERT(m_observerForMountPoint.contains(url)); m_observerForMountPoint.remove(url); m_mountPointForObserver.remove(observer); diff --git a/src/statusbar/mountpointobservercache.h b/src/statusbar/mountpointobservercache.h index ab16fa760b..92e1b6be37 100644 --- a/src/statusbar/mountpointobservercache.h +++ b/src/statusbar/mountpointobservercache.h @@ -21,23 +21,23 @@ class MountPointObserverCache : public QObject ~MountPointObserverCache() override; public: - static MountPointObserverCache* instance(); + static MountPointObserverCache *instance(); /** * Returns a MountPointObserver for the given \a url. A new observer is created if necessary. */ - MountPointObserver* observerForUrl(const QUrl& url); + MountPointObserver *observerForUrl(const QUrl &url); private Q_SLOTS: /** * Removes the given \a observer from the cache. */ - void slotObserverDestroyed(QObject* observer); + void slotObserverDestroyed(QObject *observer); private: - QHash m_observerForMountPoint; - QHash m_mountPointForObserver; - QTimer* m_updateTimer; + QHash m_observerForMountPoint; + QHash m_mountPointForObserver; + QTimer *m_updateTimer; friend class MountPointObserverCacheSingleton; }; diff --git a/src/statusbar/spaceinfoobserver.cpp b/src/statusbar/spaceinfoobserver.cpp index 457fe12aea..2963712556 100644 --- a/src/statusbar/spaceinfoobserver.cpp +++ b/src/statusbar/spaceinfoobserver.cpp @@ -8,12 +8,12 @@ #include "mountpointobserver.h" -SpaceInfoObserver::SpaceInfoObserver(const QUrl& url, QObject* parent) : - QObject(parent), - m_mountPointObserver(nullptr), - m_hasData(false), - m_dataSize(0), - m_dataAvailable(0) +SpaceInfoObserver::SpaceInfoObserver(const QUrl &url, QObject *parent) + : QObject(parent) + , m_mountPointObserver(nullptr) + , m_hasData(false) + , m_dataSize(0) + , m_dataAvailable(0) { m_mountPointObserver = MountPointObserver::observerForUrl(url); m_mountPointObserver->ref(); @@ -39,9 +39,9 @@ quint64 SpaceInfoObserver::available() const return m_dataAvailable; } -void SpaceInfoObserver::setUrl(const QUrl& url) +void SpaceInfoObserver::setUrl(const QUrl &url) { - MountPointObserver* newObserver = MountPointObserver::observerForUrl(url); + MountPointObserver *newObserver = MountPointObserver::observerForUrl(url); if (newObserver != m_mountPointObserver) { if (m_mountPointObserver) { disconnect(m_mountPointObserver, &MountPointObserver::spaceInfoChanged, this, &SpaceInfoObserver::spaceInfoChanged); @@ -53,7 +53,7 @@ void SpaceInfoObserver::setUrl(const QUrl& url) m_mountPointObserver->ref(); connect(m_mountPointObserver, &MountPointObserver::spaceInfoChanged, this, &SpaceInfoObserver::spaceInfoChanged); - // If newObserver is cached it won't call update until the next timer update, + // If newObserver is cached it won't call update until the next timer update, // so update the observer now. m_mountPointObserver->update(); } diff --git a/src/statusbar/spaceinfoobserver.h b/src/statusbar/spaceinfoobserver.h index 6c77316b1a..f46c6cd6f6 100644 --- a/src/statusbar/spaceinfoobserver.h +++ b/src/statusbar/spaceinfoobserver.h @@ -17,13 +17,13 @@ class SpaceInfoObserver : public QObject Q_OBJECT public: - explicit SpaceInfoObserver(const QUrl& url, QObject* parent = nullptr); + explicit SpaceInfoObserver(const QUrl &url, QObject *parent = nullptr); ~SpaceInfoObserver() override; quint64 size() const; quint64 available() const; - void setUrl(const QUrl& url); + void setUrl(const QUrl &url); public Q_SLOTS: void update(); @@ -38,9 +38,9 @@ private Q_SLOTS: void spaceInfoChanged(quint64 size, quint64 available); private: - MountPointObserver* m_mountPointObserver; + MountPointObserver *m_mountPointObserver; - bool m_hasData; + bool m_hasData; quint64 m_dataSize; quint64 m_dataAvailable; }; diff --git a/src/statusbar/statusbarspaceinfo.cpp b/src/statusbar/statusbarspaceinfo.cpp index 1debaec297..309e9d5359 100644 --- a/src/statusbar/statusbarspaceinfo.cpp +++ b/src/statusbar/statusbarspaceinfo.cpp @@ -14,9 +14,9 @@ #include #include -StatusBarSpaceInfo::StatusBarSpaceInfo(QWidget* parent) : - KCapacityBar(KCapacityBar::DrawTextInline, parent), - m_observer(nullptr) +StatusBarSpaceInfo::StatusBarSpaceInfo(QWidget *parent) + : KCapacityBar(KCapacityBar::DrawTextInline, parent) + , m_observer(nullptr) { setCursor(Qt::PointingHandCursor); } @@ -34,7 +34,7 @@ void StatusBarSpaceInfo::setShown(bool shown) } } -void StatusBarSpaceInfo::setUrl(const QUrl& url) +void StatusBarSpaceInfo::setUrl(const QUrl &url) { if (m_url != url) { m_url = url; @@ -58,7 +58,7 @@ void StatusBarSpaceInfo::update() } } -void StatusBarSpaceInfo::showEvent(QShowEvent* event) +void StatusBarSpaceInfo::showEvent(QShowEvent *event) { if (m_shown) { if (m_ready) { @@ -72,7 +72,7 @@ void StatusBarSpaceInfo::showEvent(QShowEvent* event) } } -void StatusBarSpaceInfo::hideEvent(QHideEvent* event) +void StatusBarSpaceInfo::hideEvent(QHideEvent *event) { if (m_ready) { m_observer.reset(); @@ -81,7 +81,7 @@ void StatusBarSpaceInfo::hideEvent(QHideEvent* event) KCapacityBar::hideEvent(event); } -void StatusBarSpaceInfo::mousePressEvent(QMouseEvent* event) +void StatusBarSpaceInfo::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { // Creates a menu with tools that help to find out more about free @@ -91,8 +91,7 @@ void StatusBarSpaceInfo::mousePressEvent(QMouseEvent* event) // the "Configure..." dialog KMoreToolsMenuFactory menuFactory(QStringLiteral("dolphin/statusbar-diskspace-menu")); menuFactory.setParentWidget(this); - auto menu = menuFactory.createMenuFromGroupingNames( - { "disk-usage", "more:", "disk-partitions" }, m_url); + auto menu = menuFactory.createMenuFromGroupingNames({"disk-usage", "more:", "disk-partitions"}, m_url); menu->exec(QCursor::pos()); } @@ -126,4 +125,3 @@ void StatusBarSpaceInfo::slotValuesChanged() update(); } } - diff --git a/src/statusbar/statusbarspaceinfo.h b/src/statusbar/statusbarspaceinfo.h index 5b16942a40..932f09b7b7 100644 --- a/src/statusbar/statusbarspaceinfo.h +++ b/src/statusbar/statusbarspaceinfo.h @@ -25,22 +25,22 @@ class StatusBarSpaceInfo : public KCapacityBar Q_OBJECT public: - explicit StatusBarSpaceInfo(QWidget* parent = nullptr); + explicit StatusBarSpaceInfo(QWidget *parent = nullptr); ~StatusBarSpaceInfo() override; /** * Use this to set the widget visibility as it can hide itself */ void setShown(bool); - void setUrl(const QUrl& url); + void setUrl(const QUrl &url); QUrl url() const; void update(); protected: - void showEvent(QShowEvent* event) override; - void hideEvent(QHideEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; private Q_SLOTS: void slotValuesChanged(); diff --git a/src/tests/dolphinmainwindowtest.cpp b/src/tests/dolphinmainwindowtest.cpp index eefca42049..e849c49373 100644 --- a/src/tests/dolphinmainwindowtest.cpp +++ b/src/tests/dolphinmainwindowtest.cpp @@ -40,7 +40,6 @@ private Q_SLOTS: void testGoActions(); void cleanupTestCase(); - private: QScopedPointer m_mainWindow; }; @@ -58,13 +57,13 @@ void DolphinMainWindowTest::init() // See https://bugs.kde.org/show_bug.cgi?id=379135 void DolphinMainWindowTest::testClosingTabsWithSearchBoxVisible() { - m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false); + m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false); m_mainWindow->show(); // Without this call the searchbox doesn't get FocusIn events. QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); - auto tabWidget = m_mainWindow->findChild("tabWidget"); + auto tabWidget = m_mainWindow->findChild("tabWidget"); QVERIFY(tabWidget); // Show search box on first tab. @@ -88,12 +87,12 @@ void DolphinMainWindowTest::testActiveViewAfterClosingSplitView_data() void DolphinMainWindowTest::testActiveViewAfterClosingSplitView() { - m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false); + m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false); m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); - auto tabWidget = m_mainWindow->findChild("tabWidget"); + auto tabWidget = m_mainWindow->findChild("tabWidget"); QVERIFY(tabWidget); QVERIFY(tabWidget->currentTabPage()->primaryViewContainer()); QVERIFY(!tabWidget->currentTabPage()->secondaryViewContainer()); @@ -133,12 +132,12 @@ void DolphinMainWindowTest::testActiveViewAfterClosingSplitView() // Test case for bug #385111 void DolphinMainWindowTest::testUpdateWindowTitleAfterClosingSplitView() { - m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false); + m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false); m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); - auto tabWidget = m_mainWindow->findChild("tabWidget"); + auto tabWidget = m_mainWindow->findChild("tabWidget"); QVERIFY(tabWidget); QVERIFY(tabWidget->currentTabPage()->primaryViewContainer()); QVERIFY(!tabWidget->currentTabPage()->secondaryViewContainer()); @@ -174,12 +173,12 @@ void DolphinMainWindowTest::testUpdateWindowTitleAfterClosingSplitView() // Test case for bug #402641 void DolphinMainWindowTest::testUpdateWindowTitleAfterChangingSplitView() { - m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false); + m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false); m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); - auto tabWidget = m_mainWindow->findChild("tabWidget"); + auto tabWidget = m_mainWindow->findChild("tabWidget"); QVERIFY(tabWidget); // Open split view. @@ -204,12 +203,12 @@ void DolphinMainWindowTest::testUpdateWindowTitleAfterChangingSplitView() // Test case for bug #397910 void DolphinMainWindowTest::testOpenInNewTabTitle() { - m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false); + m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false); m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); - auto tabWidget = m_mainWindow->findChild("tabWidget"); + auto tabWidget = m_mainWindow->findChild("tabWidget"); QVERIFY(tabWidget); tabWidget->openNewTab(QUrl::fromLocalFile(QDir::tempPath())); @@ -234,12 +233,12 @@ void DolphinMainWindowTest::testNewFileMenuEnabled_data() void DolphinMainWindowTest::testNewFileMenuEnabled() { QFETCH(QUrl, activeViewUrl); - m_mainWindow->openDirectories({ activeViewUrl }, false); + m_mainWindow->openDirectories({activeViewUrl}, false); m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); - auto newFileMenu = m_mainWindow->findChild("new_menu"); + auto newFileMenu = m_mainWindow->findChild("new_menu"); QVERIFY(newFileMenu); QFETCH(bool, expectedEnabled); @@ -260,7 +259,7 @@ void DolphinMainWindowTest::testWindowTitle_data() void DolphinMainWindowTest::testWindowTitle() { QFETCH(QUrl, activeViewUrl); - m_mainWindow->openDirectories({ activeViewUrl }, false); + m_mainWindow->openDirectories({activeViewUrl}, false); m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); @@ -275,14 +274,19 @@ void DolphinMainWindowTest::testWindowTitle() */ void DolphinMainWindowTest::testPlacesPanelWidthResistance() { - m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false); + m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false); m_mainWindow->show(); m_mainWindow->resize(800, m_mainWindow->height()); // make sure the size is sufficient so a places panel resize shouldn't be necessary. QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); QWidget *placesPanel = reinterpret_cast(m_mainWindow->m_placesPanel); - QVERIFY2(QTest::qWaitFor([&](){ return placesPanel && placesPanel->isVisible() && placesPanel->width() > 0; }, 5000), "The test couldn't be initialised properly. The places panel should be visible."); + QVERIFY2(QTest::qWaitFor( + [&]() { + return placesPanel && placesPanel->isVisible() && placesPanel->width() > 0; + }, + 5000), + "The test couldn't be initialised properly. The places panel should be visible."); QTest::qWait(100); const int initialPlacesPanelWidth = placesPanel->width(); @@ -296,7 +300,8 @@ void DolphinMainWindowTest::testPlacesPanelWidthResistance() // Make all selection mode bars appear and test for each that this doesn't affect the places panel's width. // One of the bottom bars (SelectionMode::BottomBar::GeneralContents) only shows up when at least one item is selected so we do that before we begin iterating. m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::SelectAll))->trigger(); - for (int selectionModeStates = SelectionMode::BottomBar::CopyContents; selectionModeStates != SelectionMode::BottomBar::RenameContents; selectionModeStates++) { + for (int selectionModeStates = SelectionMode::BottomBar::CopyContents; selectionModeStates != SelectionMode::BottomBar::RenameContents; + selectionModeStates++) { const auto contents = static_cast(selectionModeStates); m_mainWindow->slotSetSelectionMode(true, contents); QTest::qWait(20); // give time for a paint/resize @@ -345,7 +350,7 @@ void DolphinMainWindowTest::testGoActions() testDir->createFile("b/b-2"); testDir->createDir("c"); QUrl childDirUrl(QDir::cleanPath(testDir->url().toString() + "/b")); - m_mainWindow->openDirectories({ childDirUrl }, false); // Open "b" dir + m_mainWindow->openDirectories({childDirUrl}, false); // Open "b" dir m_mainWindow->show(); QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data())); QVERIFY(m_mainWindow->isVisible()); @@ -358,7 +363,9 @@ void DolphinMainWindowTest::testGoActions() */ QSignalSpy spyDirectoryLoadingCompleted(m_mainWindow->m_activeViewContainer->view(), &DolphinView::directoryLoadingCompleted); QVERIFY(spyDirectoryLoadingCompleted.wait()); - QVERIFY(QTest::qWaitFor([&](){ return !m_mainWindow->actionCollection()->action(QStringLiteral("stop"))->isEnabled(); })); // "Stop" command should be disabled because it finished loading + QVERIFY(QTest::qWaitFor([&]() { + return !m_mainWindow->actionCollection()->action(QStringLiteral("stop"))->isEnabled(); + })); // "Stop" command should be disabled because it finished loading QTest::qWait(500); // Somehow the item we emerged from doesn't have keyboard focus yet if we don't wait a split second. const QUrl parentDirUrl = m_mainWindow->activeViewContainer()->url(); QVERIFY(parentDirUrl != childDirUrl); @@ -429,7 +436,6 @@ void DolphinMainWindowTest::cleanupTestCase() m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Quit))->trigger(); } - QTEST_MAIN(DolphinMainWindowTest) #include "dolphinmainwindowtest.moc" diff --git a/src/tests/dolphinquerytest.cpp b/src/tests/dolphinquerytest.cpp index 2b025eed74..b6feab686f 100644 --- a/src/tests/dolphinquerytest.cpp +++ b/src/tests/dolphinquerytest.cpp @@ -10,8 +10,8 @@ #include #include -#include #include +#include #include #include @@ -28,11 +28,9 @@ private Q_SLOTS: /** * Helper function to compose the baloo query URL used for searching */ -QUrl balooQueryUrl(const QString& searchString) +QUrl balooQueryUrl(const QString &searchString) { - const QJsonObject jsonObject { - {"searchString", searchString} - }; + const QJsonObject jsonObject{{"searchString", searchString}}; const QJsonDocument doc(jsonObject); const QString queryString = QString::fromUtf8(doc.toJson(QJsonDocument::Compact)); @@ -57,7 +55,6 @@ void DolphinQueryTest::initTestCase() */ void DolphinQueryTest::testBalooSearchParsing_data() { - QTest::addColumn("searchUrl"); QTest::addColumn("expectedText"); QTest::addColumn("expectedTerms"); @@ -78,81 +75,76 @@ void DolphinQueryTest::testBalooSearchParsing_data() const QString modified = QStringLiteral("modified>=2019-08-07"); const QString tag = QStringLiteral("tag:tagA"); - const QString tagS = QStringLiteral("tag:\"tagB with spaces\""); // in search url - const QString tagR = QStringLiteral("tag:tagB with spaces"); // in result term + const QString tagS = QStringLiteral("tag:\"tagB with spaces\""); // in search url + const QString tagR = QStringLiteral("tag:tagB with spaces"); // in result term // Test for "Content" - QTest::newRow("content") << balooQueryUrl(text) << text << QStringList() << true << false; - QTest::newRow("content/space") << balooQueryUrl(textS) << textS << QStringList() << true << false; - QTest::newRow("content/quoted") << balooQueryUrl(textQ) << textS << QStringList() << true << false; - QTest::newRow("content/empty") << balooQueryUrl("") << "" << QStringList() << false << false; - QTest::newRow("content/single_quote") << balooQueryUrl("\"") << "\"" << QStringList() << true << false; - QTest::newRow("content/double_quote") << balooQueryUrl("\"\"") << "" << QStringList() << false << false; + QTest::newRow("content") << balooQueryUrl(text) << text << QStringList() << true << false; + QTest::newRow("content/space") << balooQueryUrl(textS) << textS << QStringList() << true << false; + QTest::newRow("content/quoted") << balooQueryUrl(textQ) << textS << QStringList() << true << false; + QTest::newRow("content/empty") << balooQueryUrl("") << "" << QStringList() << false << false; + QTest::newRow("content/single_quote") << balooQueryUrl("\"") << "\"" << QStringList() << true << false; + QTest::newRow("content/double_quote") << balooQueryUrl("\"\"") << "" << QStringList() << false << false; // Test for "FileName" - QTest::newRow("filename") << balooQueryUrl(filename) << text << QStringList() << false << true; - QTest::newRow("filename/space") << balooQueryUrl(filenameS) << textS << QStringList() << false << true; - QTest::newRow("filename/quoted") << balooQueryUrl(filenameQ) << textQ << QStringList() << false << true; - QTest::newRow("filename/mixed") << balooQueryUrl(filenameM) << textM << QStringList() << false << true; - QTest::newRow("filename/empty") << balooQueryUrl("filename:") << "" << QStringList() << false << false; - QTest::newRow("filename/single_quote") << balooQueryUrl("filename:\"") << "\"" << QStringList() << false << true; - QTest::newRow("filename/double_quote") << balooQueryUrl("filename:\"\"") << "" << QStringList() << false << false; + QTest::newRow("filename") << balooQueryUrl(filename) << text << QStringList() << false << true; + QTest::newRow("filename/space") << balooQueryUrl(filenameS) << textS << QStringList() << false << true; + QTest::newRow("filename/quoted") << balooQueryUrl(filenameQ) << textQ << QStringList() << false << true; + QTest::newRow("filename/mixed") << balooQueryUrl(filenameM) << textM << QStringList() << false << true; + QTest::newRow("filename/empty") << balooQueryUrl("filename:") << "" << QStringList() << false << false; + QTest::newRow("filename/single_quote") << balooQueryUrl("filename:\"") << "\"" << QStringList() << false << true; + QTest::newRow("filename/double_quote") << balooQueryUrl("filename:\"\"") << "" << QStringList() << false << false; // Combined content and filename search - QTest::newRow("content+filename") - << balooQueryUrl(text + " " + filename) - << text + " " + filename << QStringList() << true << true; + QTest::newRow("content+filename") << balooQueryUrl(text + " " + filename) << text + " " + filename << QStringList() << true << true; - QTest::newRow("content+filename/quoted") - << balooQueryUrl(textQ + " " + filenameQ) - << textS + " " + filenameQ << QStringList() << true << true; + QTest::newRow("content+filename/quoted") << balooQueryUrl(textQ + " " + filenameQ) << textS + " " + filenameQ << QStringList() << true << true; // Test for rating - QTest::newRow("rating") << balooQueryUrl(rating) << "" << QStringList({rating}) << false << false; - QTest::newRow("rating+content") << balooQueryUrl(rating + " " + text) << text << QStringList({rating}) << true << false; + QTest::newRow("rating") << balooQueryUrl(rating) << "" << QStringList({rating}) << false << false; + QTest::newRow("rating+content") << balooQueryUrl(rating + " " + text) << text << QStringList({rating}) << true << false; QTest::newRow("rating+filename") << balooQueryUrl(rating + " " + filename) << text << QStringList({rating}) << false << true; // Test for modified date - QTest::newRow("modified") << balooQueryUrl(modified) << "" << QStringList({modified}) << false << false; - QTest::newRow("modified+content") << balooQueryUrl(modified + " " + text) << text << QStringList({modified}) << true << false; + QTest::newRow("modified") << balooQueryUrl(modified) << "" << QStringList({modified}) << false << false; + QTest::newRow("modified+content") << balooQueryUrl(modified + " " + text) << text << QStringList({modified}) << true << false; QTest::newRow("modified+filename") << balooQueryUrl(modified + " " + filename) << text << QStringList({modified}) << false << true; // Test for tags - QTest::newRow("tag") << balooQueryUrl(tag) << "" << QStringList({tag}) << false << false; - QTest::newRow("tag/space" ) << balooQueryUrl(tagS) << "" << QStringList({tagR}) << false << false; - QTest::newRow("tag/double") << balooQueryUrl(tag + " " + tagS) << "" << QStringList({tag, tagR}) << false << false; - QTest::newRow("tag+content") << balooQueryUrl(tag + " " + text) << text << QStringList({tag}) << true << false; - QTest::newRow("tag+filename") << balooQueryUrl(tag + " " + filename) << text << QStringList({tag}) << false << true; + QTest::newRow("tag") << balooQueryUrl(tag) << "" << QStringList({tag}) << false << false; + QTest::newRow("tag/space") << balooQueryUrl(tagS) << "" << QStringList({tagR}) << false << false; + QTest::newRow("tag/double") << balooQueryUrl(tag + " " + tagS) << "" << QStringList({tag, tagR}) << false << false; + QTest::newRow("tag+content") << balooQueryUrl(tag + " " + text) << text << QStringList({tag}) << true << false; + QTest::newRow("tag+filename") << balooQueryUrl(tag + " " + filename) << text << QStringList({tag}) << false << true; // Combined search terms - QTest::newRow("searchTerms") - << balooQueryUrl(rating + " AND " + modified + " AND " + tag + " AND " + tagS) - << "" << QStringList({modified, rating, tag, tagR}) << false << false; + QTest::newRow("searchTerms") << balooQueryUrl(rating + " AND " + modified + " AND " + tag + " AND " + tagS) << "" + << QStringList({modified, rating, tag, tagR}) << false << false; - QTest::newRow("searchTerms+content") - << balooQueryUrl(rating + " AND " + modified + " " + text + " " + tag + " AND " + tagS) - << text << QStringList({modified, rating, tag, tagR}) << true << false; + QTest::newRow("searchTerms+content") << balooQueryUrl(rating + " AND " + modified + " " + text + " " + tag + " AND " + tagS) << text + << QStringList({modified, rating, tag, tagR}) << true << false; - QTest::newRow("searchTerms+filename") - << balooQueryUrl(rating + " AND " + modified + " " + filename + " " + tag + " AND " + tagS) - << text << QStringList({modified, rating, tag, tagR}) << false << true; + QTest::newRow("searchTerms+filename") << balooQueryUrl(rating + " AND " + modified + " " + filename + " " + tag + " AND " + tagS) << text + << QStringList({modified, rating, tag, tagR}) << false << true; - QTest::newRow("allTerms") - << balooQueryUrl(text + " " + filename + " " + rating + " AND " + modified + " AND " + tag) - << text + " " + filename << QStringList({modified, rating, tag}) << true << true; + QTest::newRow("allTerms") << balooQueryUrl(text + " " + filename + " " + rating + " AND " + modified + " AND " + tag) << text + " " + filename + << QStringList({modified, rating, tag}) << true << true; - QTest::newRow("allTerms/space") - << balooQueryUrl(textS + " " + filenameS + " " + rating + " AND " + modified + " AND " + tagS) - << textS + " " + filenameS << QStringList({modified, rating, tagR}) << true << true; + QTest::newRow("allTerms/space") << balooQueryUrl(textS + " " + filenameS + " " + rating + " AND " + modified + " AND " + tagS) << textS + " " + filenameS + << QStringList({modified, rating, tagR}) << true << true; // Test tags:/ URL scheme - const auto tagUrl = [](const QString &tag) { return QUrl(QStringLiteral("tags:/%1/").arg(tag)); }; - const auto tagTerms = [](const QString &tag) { return QStringList{QStringLiteral("tag:%1").arg(tag)}; }; + const auto tagUrl = [](const QString &tag) { + return QUrl(QStringLiteral("tags:/%1/").arg(tag)); + }; + const auto tagTerms = [](const QString &tag) { + return QStringList{QStringLiteral("tag:%1").arg(tag)}; + }; - QTest::newRow("tagsUrl") << tagUrl("tagA") << "" << tagTerms("tagA") << false << false; + QTest::newRow("tagsUrl") << tagUrl("tagA") << "" << tagTerms("tagA") << false << false; QTest::newRow("tagsUrl/space") << tagUrl("tagB with spaces") << "" << tagTerms("tagB with spaces") << false << false; - QTest::newRow("tagsUrl/hash") << tagUrl("tagC#hash") << "" << tagTerms("tagC#hash") << false << false; - QTest::newRow("tagsUrl/slash") << tagUrl("tagD/with/slash") << "" << tagTerms("tagD/with/slash") << false << false; + QTest::newRow("tagsUrl/hash") << tagUrl("tagC#hash") << "" << tagTerms("tagC#hash") << false << false; + QTest::newRow("tagsUrl/slash") << tagUrl("tagD/with/slash") << "" << tagTerms("tagD/with/slash") << false << false; } /** diff --git a/src/tests/dolphinsearchboxtest.cpp b/src/tests/dolphinsearchboxtest.cpp index 56420e56e9..4bfdff76d5 100644 --- a/src/tests/dolphinsearchboxtest.cpp +++ b/src/tests/dolphinsearchboxtest.cpp @@ -21,7 +21,7 @@ private Q_SLOTS: void testTextClearing(); private: - DolphinSearchBox* m_searchBox; + DolphinSearchBox *m_searchBox; }; void DolphinSearchBoxTest::initTestCase() diff --git a/src/tests/draganddrophelpertest.cpp b/src/tests/draganddrophelpertest.cpp index a82e75c7b8..f2c75fef0d 100644 --- a/src/tests/draganddrophelpertest.cpp +++ b/src/tests/draganddrophelpertest.cpp @@ -29,35 +29,18 @@ void DragAndDropHelperTest::testUrlListMatchesUrl_data() QTest::addColumn("url"); QTest::addColumn("expected"); - QTest::newRow("test_equal") - << QList {QUrl::fromLocalFile("/root")} - << QUrl::fromLocalFile("/root") - << true; + QTest::newRow("test_equal") << QList{QUrl::fromLocalFile("/root")} << QUrl::fromLocalFile("/root") << true; - QTest::newRow("test_trailing_slash") - << QList {QUrl::fromLocalFile("/root/")} - << QUrl::fromLocalFile("/root") - << true; + QTest::newRow("test_trailing_slash") << QList{QUrl::fromLocalFile("/root/")} << QUrl::fromLocalFile("/root") << true; - QTest::newRow("test_ftp_scheme") - << QList {QUrl("ftp://server:2211/dir")} - << QUrl("ftp://server:2211/dir") - << true; + QTest::newRow("test_ftp_scheme") << QList{QUrl("ftp://server:2211/dir")} << QUrl("ftp://server:2211/dir") << true; - QTest::newRow("test_not_matched") - << QList {QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")} - << QUrl::fromLocalFile("/usr/bin") - << false; + QTest::newRow("test_not_matched") << QList{QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")} + << QUrl::fromLocalFile("/usr/bin") << false; - QTest::newRow("test_empty_target") - << QList {QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")} - << QUrl() - << false; + QTest::newRow("test_empty_target") << QList{QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")} << QUrl() << false; - QTest::newRow("test_empty_list") - << QList() - << QUrl::fromLocalFile("/usr/bin") - << false; + QTest::newRow("test_empty_list") << QList() << QUrl::fromLocalFile("/usr/bin") << false; } void DragAndDropHelperTest::testUrlListMatchesUrl() @@ -69,7 +52,6 @@ void DragAndDropHelperTest::testUrlListMatchesUrl() QCOMPARE(DragAndDropHelper::urlListMatchesUrl(urlList, url), expected); } - QTEST_MAIN(DragAndDropHelperTest) #include "draganddrophelpertest.moc" diff --git a/src/tests/kfileitemlistviewtest.cpp b/src/tests/kfileitemlistviewtest.cpp index 22d5d3a01a..42dc4fc77e 100644 --- a/src/tests/kfileitemlistviewtest.cpp +++ b/src/tests/kfileitemlistviewtest.cpp @@ -11,9 +11,9 @@ #include #include -#include #include #include +#include class KFileItemListViewTest : public QObject { @@ -26,10 +26,10 @@ private Q_SLOTS: void testGroupedItemChanges(); private: - KFileItemListView* m_listView; - KFileItemModel* m_model; - TestDir* m_testDir; - QGraphicsView* m_graphicsView; + KFileItemListView *m_listView; + KFileItemModel *m_model; + TestDir *m_testDir; + QGraphicsView *m_graphicsView; }; void KFileItemListViewTest::initTestCase() diff --git a/src/tests/kfileitemmodelbenchmark.cpp b/src/tests/kfileitemmodelbenchmark.cpp index 8e307e2a15..0daf4abd0c 100644 --- a/src/tests/kfileitemmodelbenchmark.cpp +++ b/src/tests/kfileitemmodelbenchmark.cpp @@ -5,16 +5,16 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ -#include #include #include +#include #include #include "kitemviews/kfileitemmodel.h" #include "kitemviews/private/kfileitemmodelsortalgorithm.h" -void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) +void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { Q_UNUSED(context) @@ -30,7 +30,7 @@ void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QS fprintf(stderr, "Fatal: %s\n", msg.toLocal8Bit().data()); abort(); default: - break; + break; } } @@ -50,7 +50,7 @@ private Q_SLOTS: void insertAndRemoveManyItems(); private: - static KFileItemList createFileItemList(const QStringList& fileNames, const QString& urlPrefix = QLatin1String("file:///")); + static KFileItemList createFileItemList(const QStringList &fileNames, const QString &urlPrefix = QLatin1String("file:///")); }; KFileItemModelBenchmark::KFileItemModelBenchmark() @@ -198,13 +198,13 @@ void KFileItemModelBenchmark::insertAndRemoveManyItems() } } -KFileItemList KFileItemModelBenchmark::createFileItemList(const QStringList& fileNames, const QString& prefix) +KFileItemList KFileItemModelBenchmark::createFileItemList(const QStringList &fileNames, const QString &prefix) { // Suppress 'file does not exist anymore' messages from KFileItemPrivate::init(). qInstallMessageHandler(myMessageOutput); KFileItemList result; - for (const QString& name : fileNames) { + for (const QString &name : fileNames) { const KFileItem item(QUrl::fromLocalFile(prefix + name), QString(), KFileItem::Unknown); result << item; } diff --git a/src/tests/kfileitemmodeltest.cpp b/src/tests/kfileitemmodeltest.cpp index fef8bd5812..38d2544aaf 100644 --- a/src/tests/kfileitemmodeltest.cpp +++ b/src/tests/kfileitemmodeltest.cpp @@ -5,22 +5,21 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ +#include #include -#include #include #include +#include #include -#include #include #include #include - #include "kitemviews/kfileitemmodel.h" #include "testdir.h" -void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) +void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { Q_UNUSED(context) @@ -36,7 +35,7 @@ void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QS fprintf(stderr, "Fatal: %s\n", msg.toLocal8Bit().data()); abort(); default: - break; + break; } } @@ -99,8 +98,8 @@ private: QStringList itemsInModel() const; private: - KFileItemModel* m_model; - TestDir* m_testDir; + KFileItemModel *m_model; + TestDir *m_testDir; }; void KFileItemModelTest::initTestCase() @@ -283,11 +282,11 @@ void KFileItemModelTest::testSetDataWithModifiedSortRole_data() // Index 2 = rating 6 QTest::newRow("Index 0: Rating 3") << 0 << 3 << false << 3 << 4 << 6; - QTest::newRow("Index 0: Rating 5") << 0 << 5 << true << 4 << 5 << 6; - QTest::newRow("Index 0: Rating 8") << 0 << 8 << true << 4 << 6 << 8; + QTest::newRow("Index 0: Rating 5") << 0 << 5 << true << 4 << 5 << 6; + QTest::newRow("Index 0: Rating 8") << 0 << 8 << true << 4 << 6 << 8; - QTest::newRow("Index 2: Rating 1") << 2 << 1 << true << 1 << 2 << 4; - QTest::newRow("Index 2: Rating 3") << 2 << 3 << true << 2 << 3 << 4; + QTest::newRow("Index 2: Rating 1") << 2 << 1 << true << 1 << 2 << 4; + QTest::newRow("Index 2: Rating 3") << 2 << 3 << true << 2 << 3 << 4; QTest::newRow("Index 2: Rating 5") << 2 << 5 << false << 2 << 4 << 5; } @@ -365,7 +364,10 @@ void KFileItemModelTest::testChangeSortRole() m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.jpg" << "c.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.jpg" + << "c.txt"); // Simulate that KFileItemModelRolesUpdater determines the mime type. // Resorting the files by 'type' will only work immediately if their @@ -382,10 +384,14 @@ void KFileItemModelTest::testChangeSortRole() // The actual order of the files might depend on the translation of the // result of KFileItem::mimeComment() in the user's language. QStringList version1; - version1 << "b.jpg" << "a.txt" << "c.txt"; + version1 << "b.jpg" + << "a.txt" + << "c.txt"; QStringList version2; - version2 << "a.txt" << "c.txt" << "b.jpg"; + version2 << "a.txt" + << "c.txt" + << "b.jpg"; const bool ok1 = (itemsInModel() == version1); const bool ok2 = (itemsInModel() == version2); @@ -407,7 +413,10 @@ void KFileItemModelTest::testResortAfterChangingName() m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.txt"); // We rename a.txt to d.txt. Even though the size has not changed at all, // the model must re-sort the items. @@ -416,7 +425,10 @@ void KFileItemModelTest::testResortAfterChangingName() m_model->setData(0, data); QVERIFY(itemsMovedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "c.txt" << "d.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "b.txt" + << "c.txt" + << "d.txt"); // We rename d.txt back to a.txt using the dir lister's refreshItems() signal. const KFileItem fileItemD = m_model->fileItem(2); @@ -428,7 +440,10 @@ void KFileItemModelTest::testResortAfterChangingName() m_model->slotRefreshItems({qMakePair(fileItemD, fileItemA)}); QVERIFY(itemsMovedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.txt"); } void KFileItemModelTest::testModelConsistencyWhenInsertingItems() @@ -528,15 +543,16 @@ void KFileItemModelTest::testExpandItems() // first three characters. QSet originalModelRoles = m_model->roles(); QSet modelRoles = originalModelRoles; - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a/a/1", "a/a-1/1"}); // Store the URLs of all folders in a set. QSet allFolders; - allFolders << QUrl::fromLocalFile(m_testDir->path() + "/a") - << QUrl::fromLocalFile(m_testDir->path() + "/a/a") + allFolders << QUrl::fromLocalFile(m_testDir->path() + "/a") << QUrl::fromLocalFile(m_testDir->path() + "/a/a") << QUrl::fromLocalFile(m_testDir->path() + "/a/a-1"); m_model->loadDirectory(m_testDir->url()); @@ -572,9 +588,8 @@ void KFileItemModelTest::testExpandItems() m_model->setExpanded(1, true); QVERIFY(m_model->isExpanded(1)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(m_model->count(), 4); // 4 items: "a/", "a/a/", "a/a/1", "a/a-1/" - QCOMPARE(m_model->expandedDirectories(), QSet() << QUrl::fromLocalFile(m_testDir->path() + "/a") - << QUrl::fromLocalFile(m_testDir->path() + "/a/a")); + QCOMPARE(m_model->count(), 4); // 4 items: "a/", "a/a/", "a/a/1", "a/a-1/" + QCOMPARE(m_model->expandedDirectories(), QSet() << QUrl::fromLocalFile(m_testDir->path() + "/a") << QUrl::fromLocalFile(m_testDir->path() + "/a/a")); QCOMPARE(itemsInsertedSpy.count(), 1); itemRangeList = itemsInsertedSpy.takeFirst().at(0).value(); @@ -587,7 +602,7 @@ void KFileItemModelTest::testExpandItems() m_model->setExpanded(3, true); QVERIFY(m_model->isExpanded(3)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1" + QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1" QCOMPARE(m_model->expandedDirectories(), allFolders); QCOMPARE(itemsInsertedSpy.count(), 1); @@ -616,7 +631,7 @@ void KFileItemModelTest::testExpandItems() m_model->loadDirectory(m_testDir->url()); m_model->restoreExpandedDirectories(allFolders); QVERIFY(loadingCompletedSpy.wait()); - QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1" + QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1" QVERIFY(m_model->isExpanded(0)); QVERIFY(m_model->isExpanded(1)); QVERIFY(!m_model->isExpanded(2)); @@ -629,11 +644,11 @@ void KFileItemModelTest::testExpandItems() // This is how DolphinView restores the expanded folders when navigating in history. m_model->loadDirectory(QUrl::fromLocalFile(m_testDir->path() + "/a/a/")); QVERIFY(loadingCompletedSpy.wait()); - QCOMPARE(m_model->count(), 1); // 1 item: "1" + QCOMPARE(m_model->count(), 1); // 1 item: "1" m_model->restoreExpandedDirectories(allFolders); m_model->loadDirectory(m_testDir->url()); QVERIFY(loadingCompletedSpy.wait()); - QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1" + QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1" QCOMPARE(m_model->expandedDirectories(), allFolders); // Remove all expanded items by changing the roles @@ -664,7 +679,9 @@ void KFileItemModelTest::testExpandParentItems() // a2/b2/c2/ // a2/b2/c2/d2/ QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a 1/b1/c1/file.txt", "a2/b2/c2/d2/file.txt"}); @@ -736,7 +753,9 @@ void KFileItemModelTest::testMakeExpandedItemHidden() QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"1a/2a/3a", "1a/2a/3b", "1a/2b", "1b"}); @@ -759,7 +778,7 @@ void KFileItemModelTest::testMakeExpandedItemHidden() const QUrl oldUrl = QUrl::fromLocalFile(m_model->fileItem(0).url().path() + "/2a"); const QUrl newUrl = QUrl::fromLocalFile(m_model->fileItem(0).url().path() + "/.2a"); - KIO::SimpleJob* job = KIO::rename(oldUrl, newUrl, KIO::HideProgressInfo); + KIO::SimpleJob *job = KIO::rename(oldUrl, newUrl, KIO::HideProgressInfo); bool ok = job->exec(); QVERIFY(ok); QVERIFY(itemsRemovedSpy.wait()); @@ -770,7 +789,6 @@ void KFileItemModelTest::testMakeExpandedItemHidden() m_model->setExpanded(0, false); QCOMPARE(m_model->count(), 2); - } void KFileItemModelTest::testRemoveFilteredExpandedItems() @@ -779,7 +797,9 @@ void KFileItemModelTest::testRemoveFilteredExpandedItems() QSet originalModelRoles = m_model->roles(); QSet modelRoles = originalModelRoles; - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"folder/child", "file"}); @@ -793,17 +813,24 @@ void KFileItemModelTest::testRemoveFilteredExpandedItems() QVERIFY(!m_model->isExpandable(1)); QVERIFY(!m_model->isExpanded(0)); QVERIFY(!m_model->isExpanded(1)); - QCOMPARE(itemsInModel(), QStringList() << "folder" << "file"); + QCOMPARE(itemsInModel(), + QStringList() << "folder" + << "file"); // Expand "folder" -> "folder/child" becomes visible. m_model->setExpanded(0, true); QVERIFY(m_model->isExpanded(0)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "folder" << "child" << "file"); + QCOMPARE(itemsInModel(), + QStringList() << "folder" + << "child" + << "file"); // Add a name filter. m_model->setNameFilter("f"); - QCOMPARE(itemsInModel(), QStringList() << "folder" << "file"); + QCOMPARE(itemsInModel(), + QStringList() << "folder" + << "file"); m_model->setNameFilter("fo"); QCOMPARE(itemsInModel(), QStringList() << "folder"); @@ -815,7 +842,9 @@ void KFileItemModelTest::testRemoveFilteredExpandedItems() // Remove the name filter and verify that "folder/child" does not reappear. m_model->setNameFilter(QString()); - QCOMPARE(itemsInModel(), QStringList() << "folder" << "file"); + QCOMPARE(itemsInModel(), + QStringList() << "folder" + << "file"); } void KFileItemModelTest::testSorting() @@ -884,83 +913,155 @@ void KFileItemModelTest::testSorting() QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); QVERIFY(m_model->sortDirectoriesFirst()); QVERIFY(!m_model->showHiddenFiles()); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "d" << "e"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "a" + << "b" + << "d" + << "e"); // Sort by Name, ascending, 'Sort Folders First' disabled m_model->setSortDirectoriesFirst(false); QCOMPARE(m_model->sortRole(), QByteArray("text")); QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c" << "c-1" << "c-2" << "c-3" << "d" << "e"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "c" + << "c-1" + << "c-2" + << "c-3" + << "d" + << "e"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(0, 6)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 2 << 4 << 5 << 3 << 0 << 1); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 2 << 4 << 5 << 3 << 0 << 1); // Sort by Name, descending m_model->setSortDirectoriesFirst(true); m_model->setSortOrder(Qt::DescendingOrder); QCOMPARE(m_model->sortRole(), QByteArray("text")); QCOMPARE(m_model->sortOrder(), Qt::DescendingOrder); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "e" << "d" << "b" << "a"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "e" + << "d" + << "b" + << "a"); QCOMPARE(itemsMovedSpy.count(), 2); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(0, 6)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 4 << 5 << 0 << 3 << 1 << 2); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 4 << 5 << 0 << 3 << 1 << 2); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 4)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 7 << 6 << 5 << 4); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 7 << 6 << 5 << 4); // Sort by Date, descending m_model->setSortDirectoriesFirst(true); m_model->setSortRole("modificationtime"); QCOMPARE(m_model->sortRole(), QByteArray("modificationtime")); QCOMPARE(m_model->sortOrder(), Qt::DescendingOrder); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "b" << "d" << "a" << "e"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "b" + << "d" + << "a" + << "e"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 4)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 7 << 5 << 4 << 6); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 7 << 5 << 4 << 6); // Sort by Date, ascending m_model->setSortOrder(Qt::AscendingOrder); QCOMPARE(m_model->sortRole(), QByteArray("modificationtime")); QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "e" << "a" << "d" << "b"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "e" + << "a" + << "d" + << "b"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 4)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 7 << 6 << 5 << 4); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 7 << 6 << 5 << 4); // Sort by Date, ascending, 'Sort Folders First' disabled m_model->setSortDirectoriesFirst(false); QCOMPARE(m_model->sortRole(), QByteArray("modificationtime")); QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); QVERIFY(!m_model->sortDirectoriesFirst()); - QCOMPARE(itemsInModel(), QStringList() << "e" << "a" << "c" << "c-1" << "c-2" << "c-3" << "d" << "b"); + QCOMPARE(itemsInModel(), + QStringList() << "e" + << "a" + << "c" + << "c-1" + << "c-2" + << "c-3" + << "d" + << "b"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(0, 6)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 2 << 4 << 5 << 3 << 0 << 1); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 2 << 4 << 5 << 3 << 0 << 1); // Sort by Name, ascending, 'Sort Folders First' disabled m_model->setSortRole("text"); QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); QVERIFY(!m_model->sortDirectoriesFirst()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c" << "c-1" << "c-2" << "c-3" << "d" << "e"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "c" + << "c-1" + << "c-2" + << "c-3" + << "d" + << "e"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(0, 8)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 7 << 0 << 2 << 3 << 4 << 5 << 6 << 1); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 7 << 0 << 2 << 3 << 4 << 5 << 6 << 1); // Sort by Size, ascending, 'Sort Folders First' disabled m_model->setSortRole("size"); QCOMPARE(m_model->sortRole(), QByteArray("size")); QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); QVERIFY(!m_model->sortDirectoriesFirst()); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "e" << "d"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "a" + << "b" + << "e" + << "d"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(0, 8)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 4 << 5 << 0 << 3 << 1 << 2 << 7 << 6); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 4 << 5 << 0 << 3 << 1 << 2 << 7 << 6); // In 'Sort by Size' mode, folders are always first -> changing 'Sort Folders First' does not resort the model m_model->setSortDirectoriesFirst(true); QCOMPARE(m_model->sortRole(), QByteArray("size")); QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder); QVERIFY(m_model->sortDirectoriesFirst()); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "e" << "d"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "a" + << "b" + << "e" + << "d"); QCOMPARE(itemsMovedSpy.count(), 0); // Sort by Size, descending, 'Sort Folders First' enabled @@ -968,16 +1069,34 @@ void KFileItemModelTest::testSorting() QCOMPARE(m_model->sortRole(), QByteArray("size")); QCOMPARE(m_model->sortOrder(), Qt::DescendingOrder); QVERIFY(m_model->sortDirectoriesFirst()); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "d" << "e" << "b" << "a"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "d" + << "e" + << "b" + << "a"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 4)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 7 << 6 << 5 << 4); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 7 << 6 << 5 << 4); // 'Show Hidden Files' enabled m_model->setShowHiddenFiles(true); QVERIFY(m_model->showHiddenFiles()); QVERIFY(!m_model->sortHiddenLast()); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << ".g" << "d" << "e" << "b" << "a" << ".f"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << ".g" + << "d" + << "e" + << "b" + << "a" + << ".f"); QCOMPARE(itemsMovedSpy.count(), 0); QCOMPARE(itemsInsertedSpy.count(), 1); QCOMPARE(itemsInsertedSpy.takeFirst().at(0).value(), KItemRangeList() << KItemRange(4, 1) << KItemRange(8, 1)); @@ -985,34 +1104,73 @@ void KFileItemModelTest::testSorting() // 'Sort Hidden Files Last' enabled m_model->setSortHiddenLast(true); QVERIFY(m_model->sortHiddenLast()); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "d" << "e" << "b" << "a" << ".g" << ".f"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "d" + << "e" + << "b" + << "a" + << ".g" + << ".f"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsInsertedSpy.count(), 0); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 5)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 8 << 4 << 5 << 6 << 7); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 8 << 4 << 5 << 6 << 7); // Sort by Name m_model->setSortRole("text"); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "e" << "d" << "b" << "a" << ".g" << ".f"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "e" + << "d" + << "b" + << "a" + << ".g" + << ".f"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 2)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 5 << 4); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 5 << 4); // Sort ascending m_model->setSortOrder(Qt::AscendingOrder); - QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "d" << "e" << ".g" << ".f"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "c-2" + << "c-3" + << "c-1" + << "a" + << "b" + << "d" + << "e" + << ".g" + << ".f"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(4, 4)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 7 << 6 << 5 << 4); + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 7 << 6 << 5 << 4); // 'Sort Folders First' disabled m_model->setSortDirectoriesFirst(false); QVERIFY(!m_model->sortDirectoriesFirst()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c" << "c-1" << "c-2" << "c-3" << "d" << "e" << ".f" << ".g"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "c" + << "c-1" + << "c-2" + << "c-3" + << "d" + << "e" + << ".f" + << ".g"); QCOMPARE(itemsMovedSpy.count(), 1); QCOMPARE(itemsMovedSpy.first().at(0).value(), KItemRange(0, 10)); - QCOMPARE(itemsMovedSpy.takeFirst().at(1).value >(), QList() << 2 << 4 << 5 << 3 << 0 << 1 << 6 << 7 << 9 << 8); - + QCOMPARE(itemsMovedSpy.takeFirst().at(1).value>(), QList() << 2 << 4 << 5 << 3 << 0 << 1 << 6 << 7 << 9 << 8); } void KFileItemModelTest::testIndexForKeyboardSearch() @@ -1129,7 +1287,9 @@ void KFileItemModelTest::testRefreshExpandedItem() QVERIFY(itemsChangedSpy.isValid()); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a/1", "a/2", "3", "4"}); @@ -1160,7 +1320,9 @@ void KFileItemModelTest::testAddItemToFilteredExpandedFolder() QSignalSpy fileItemsChangedSpy(m_model, &KFileItemModel::fileItemsChanged); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFile("a/b/file"); @@ -1171,7 +1333,7 @@ void KFileItemModelTest::testAddItemToFilteredExpandedFolder() // Expand "a/". m_model->setExpanded(0, true); - QVERIFY(itemsInsertedSpy.wait()); + QVERIFY(itemsInsertedSpy.wait()); // Expand "a/b/". m_model->setExpanded(1, true); @@ -1190,7 +1352,10 @@ void KFileItemModelTest::testAddItemToFilteredExpandedFolder() // Entire parental chain should now be shown QCOMPARE(m_model->count(), 3); // 3 items: "a/", "a/b/", "a/b/newItem.txt" - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "newItem.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "newItem.txt"); // Items should be indented in hierarchy QCOMPARE(m_model->expandedParentsCount(0), 0); @@ -1206,9 +1371,11 @@ void KFileItemModelTest::testDeleteItemsWithExpandedFolderWithFilter() { QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted); QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved); - + QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFile("a/b/file"); @@ -1219,7 +1386,7 @@ void KFileItemModelTest::testDeleteItemsWithExpandedFolderWithFilter() // Expand "a/". m_model->setExpanded(0, true); - QVERIFY(itemsInsertedSpy.wait()); + QVERIFY(itemsInsertedSpy.wait()); // Expand "a/b/". m_model->setExpanded(1, true); @@ -1263,7 +1430,10 @@ void KFileItemModelTest::testRefreshItemsWithFilter() // Set a filter that matches ".txt" extension m_model->setNameFilter("*.txt"); QCOMPARE(m_model->count(), 3); // Still all items are shown - QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "c.txt" << "d.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "b.txt" + << "c.txt" + << "d.txt"); // Objects used to rename const KFileItem fileItemC_txt = m_model->fileItem(1); @@ -1293,22 +1463,28 @@ void KFileItemModelTest::testRefreshItemsWithFilter() QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(1, 1)); // Re-sorting is done asynchronously: - QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "a.txt"); // Files should still be in the incorrect order + QCOMPARE(itemsInModel(), + QStringList() << "b.txt" + << "a.txt"); // Files should still be in the incorrect order QVERIFY(itemsMovedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt"); // Files were re-sorted and should now be in the correct order + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt"); // Files were re-sorted and should now be in the correct order } - /** * Verifies that parental chains are hidden and shown as needed while their children get filtered/unfiltered due to renaming. * Also verifies that the "isExpanded" and "expandedParentsCount" values are kept for expanded folders that get refreshed. */ -void KFileItemModelTest::testRefreshExpandedFolderWithFilter() { +void KFileItemModelTest::testRefreshExpandedFolderWithFilter() +{ QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted); QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFile("a/b/someFolder/someFile"); @@ -1320,7 +1496,7 @@ void KFileItemModelTest::testRefreshExpandedFolderWithFilter() { // Expand "a/". m_model->setExpanded(0, true); - QVERIFY(itemsInsertedSpy.wait()); + QVERIFY(itemsInsertedSpy.wait()); // Expand "a/b/". m_model->setExpanded(1, true); @@ -1338,7 +1514,7 @@ void KFileItemModelTest::testRefreshExpandedFolderWithFilter() { // Objects used to rename const KFileItem fileItemA = m_model->fileItem(0); KFileItem fileItemARenamed = fileItemA; - fileItemARenamed.setUrl(QUrl("a_renamed")); + fileItemARenamed.setUrl(QUrl("a_renamed")); const KFileItem fileItemSomeFolder = m_model->fileItem(2); KFileItem fileItemRenamedFolder = fileItemSomeFolder; @@ -1348,7 +1524,10 @@ void KFileItemModelTest::testRefreshExpandedFolderWithFilter() { // This way we test if the algorithm is sane as to NOT hide "a_renamed" since it will have visible children m_model->slotRefreshItems({qMakePair(fileItemA, fileItemARenamed)}); QCOMPARE(m_model->count(), 3); // Entire parental chain must still be shown - QCOMPARE(itemsInModel(), QStringList() << "a_renamed" << "b" << "someFolder"); + QCOMPARE(itemsInModel(), + QStringList() << "a_renamed" + << "b" + << "someFolder"); // Rename "a_renamed" back to "a"; and "someFolder" to "renamedFolder" m_model->slotRefreshItems({qMakePair(fileItemARenamed, fileItemA), qMakePair(fileItemSomeFolder, fileItemRenamedFolder)}); @@ -1357,7 +1536,10 @@ void KFileItemModelTest::testRefreshExpandedFolderWithFilter() { // Rename "renamedFolder" back to "someFolder". Filter is passing again m_model->slotRefreshItems({qMakePair(fileItemRenamedFolder, fileItemSomeFolder)}); QCOMPARE(m_model->count(), 3); // Entire parental chain is shown again - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "someFolder"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "someFolder"); // slotRefreshItems() should preserve "isExpanded" and "expandedParentsCount" values explicitly in this case QCOMPARE(m_model->m_itemData.at(2)->values.value("isExpanded").toBool(), true); @@ -1382,21 +1564,41 @@ void KFileItemModelTest::testRemoveHiddenItems() m_model->setShowHiddenFiles(true); m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << ".a" << ".b" << "c" << "d" <<".f" << ".g" << "h" << "i"); + QCOMPARE(itemsInModel(), + QStringList() << ".a" + << ".b" + << "c" + << "d" + << ".f" + << ".g" + << "h" + << "i"); QCOMPARE(itemsInsertedSpy.count(), 1); QCOMPARE(itemsRemovedSpy.count(), 0); KItemRangeList itemRangeList = itemsInsertedSpy.takeFirst().at(0).value(); QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(0, 8)); m_model->setShowHiddenFiles(false); - QCOMPARE(itemsInModel(), QStringList() << "c" << "d" << "h" << "i"); + QCOMPARE(itemsInModel(), + QStringList() << "c" + << "d" + << "h" + << "i"); QCOMPARE(itemsInsertedSpy.count(), 0); QCOMPARE(itemsRemovedSpy.count(), 1); itemRangeList = itemsRemovedSpy.takeFirst().at(0).value(); QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(0, 2) << KItemRange(4, 2)); m_model->setShowHiddenFiles(true); - QCOMPARE(itemsInModel(), QStringList() << ".a" << ".b" << "c" << "d" <<".f" << ".g" << "h" << "i"); + QCOMPARE(itemsInModel(), + QStringList() << ".a" + << ".b" + << "c" + << "d" + << ".f" + << ".g" + << "h" + << "i"); QCOMPARE(itemsInsertedSpy.count(), 1); QCOMPARE(itemsRemovedSpy.count(), 0); itemRangeList = itemsInsertedSpy.takeFirst().at(0).value(); @@ -1423,7 +1625,9 @@ void KFileItemModelTest::collapseParentOfHiddenItems() QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a/1", "a/b/1", "a/b/c/1", "a/b/c/d/1"}); @@ -1480,7 +1684,9 @@ void KFileItemModelTest::removeParentOfHiddenItems() QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a/1", "a/b/1", "a/b/c/1", "a/b/c/d/1"}); @@ -1514,7 +1720,10 @@ void KFileItemModelTest::removeParentOfHiddenItems() m_model->setNameFilter("c"); QCOMPARE(itemsRemovedSpy.count(), 1); // nothing was removed, itemsRemovedSpy count will remain the same: QCOMPARE(m_model->count(), 3); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "c"); // Simulate the deletion of the directory "a/b/". m_model->slotItemsDeleted(KFileItemList() << m_model->fileItem(1)); @@ -1524,7 +1733,9 @@ void KFileItemModelTest::removeParentOfHiddenItems() // Remove the filter -> only the file "a/1" should appear. m_model->setNameFilter(QString()); QCOMPARE(m_model->count(), 2); - QCOMPARE(itemsInModel(), QStringList() << "a" << "1"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "1"); } /** @@ -1538,31 +1749,53 @@ void KFileItemModelTest::testGeneralParentChildRelationships() QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"parent1/realChild1/realGrandChild1", "parent2/realChild2/realGrandChild2"}); m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "parent2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "parent2"); // Expand all folders. m_model->setExpanded(0, true); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "parent2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "parent2"); m_model->setExpanded(1, true); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "parent2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "realGrandChild1" + << "parent2"); m_model->setExpanded(3, true); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "parent2" << "realChild2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "realGrandChild1" + << "parent2" + << "realChild2"); m_model->setExpanded(4, true); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "parent2" << "realChild2" << "realGrandChild2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "realGrandChild1" + << "parent2" + << "realChild2" + << "realGrandChild2"); // Add some more children and grand-children. const QUrl parent1 = m_model->fileItem(0).url(); @@ -1572,19 +1805,53 @@ void KFileItemModelTest::testGeneralParentChildRelationships() m_model->slotItemsAdded(parent1, KFileItemList() << KFileItem(QUrl("child1"), QString(), KFileItem::Unknown)); m_model->slotCompleted(); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "realGrandChild2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "realGrandChild1" + << "child1" + << "parent2" + << "realChild2" + << "realGrandChild2"); m_model->slotItemsAdded(parent2, KFileItemList() << KFileItem(QUrl("child2"), QString(), KFileItem::Unknown)); m_model->slotCompleted(); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "realGrandChild2" << "child2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "realGrandChild1" + << "child1" + << "parent2" + << "realChild2" + << "realGrandChild2" + << "child2"); m_model->slotItemsAdded(realChild1, KFileItemList() << KFileItem(QUrl("grandChild1"), QString(), KFileItem::Unknown)); m_model->slotCompleted(); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "grandChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "realGrandChild2" << "child2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "grandChild1" + << "realGrandChild1" + << "child1" + << "parent2" + << "realChild2" + << "realGrandChild2" + << "child2"); m_model->slotItemsAdded(realChild2, KFileItemList() << KFileItem(QUrl("grandChild2"), QString(), KFileItem::Unknown)); m_model->slotCompleted(); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "grandChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "grandChild2" << "realGrandChild2" << "child2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "grandChild1" + << "realGrandChild1" + << "child1" + << "parent2" + << "realChild2" + << "grandChild2" + << "realGrandChild2" + << "child2"); // Set a name filter that matches nothing -> nothing will remain. m_model->setNameFilter("xyz"); @@ -1596,12 +1863,19 @@ void KFileItemModelTest::testGeneralParentChildRelationships() // Set a name filter that matches only "realChild". Their prarents should still show. m_model->setNameFilter("realChild"); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "parent2" << "realChild2"); - QCOMPARE(itemsRemovedSpy.count(), 0); // nothing was removed, itemsRemovedSpy will not be called this time + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "realChild1" + << "parent2" + << "realChild2"); + QCOMPARE(itemsRemovedSpy.count(), 0); // nothing was removed, itemsRemovedSpy will not be called this time // Collapse "parent1". m_model->setExpanded(0, false); - QCOMPARE(itemsInModel(), QStringList() << "parent1" << "parent2" << "realChild2"); + QCOMPARE(itemsInModel(), + QStringList() << "parent1" + << "parent2" + << "realChild2"); QCOMPARE(itemsRemovedSpy.count(), 1); arguments = itemsRemovedSpy.takeFirst(); itemRangeList = arguments.at(0).value(); @@ -1633,9 +1907,13 @@ void KFileItemModelTest::testNameRoleGroups() m_model->setGroupedSorting(true); m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "c.txt" << "d.txt" << "e.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "b.txt" + << "c.txt" + << "d.txt" + << "e.txt"); - QList > expectedGroups; + QList> expectedGroups; expectedGroups << QPair(0, QLatin1String("B")); expectedGroups << QPair(1, QLatin1String("C")); expectedGroups << QPair(2, QLatin1String("D")); @@ -1647,7 +1925,11 @@ void KFileItemModelTest::testNameRoleGroups() data.insert("text", "a.txt"); m_model->setData(2, data); QVERIFY(itemsMovedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt" << "e.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.txt" + << "e.txt"); expectedGroups.clear(); expectedGroups << QPair(0, QLatin1String("A")); @@ -1660,7 +1942,11 @@ void KFileItemModelTest::testNameRoleGroups() data.insert("text", "d.txt"); m_model->setData(2, data); QVERIFY(groupsChangedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "d.txt" << "e.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "d.txt" + << "e.txt"); expectedGroups.clear(); expectedGroups << QPair(0, QLatin1String("A")); @@ -1678,7 +1964,11 @@ void KFileItemModelTest::testNameRoleGroups() m_model->slotRefreshItems({qMakePair(fileItemD, fileItemC)}); QVERIFY(groupsChangedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt" << "e.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.txt" + << "e.txt"); expectedGroups.clear(); expectedGroups << QPair(0, QLatin1String("A")); @@ -1693,7 +1983,9 @@ void KFileItemModelTest::testNameRoleGroupsWithExpandedItems() QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a/b.txt", "a/c.txt", "d/e.txt", "d/f.txt"}); @@ -1701,9 +1993,11 @@ void KFileItemModelTest::testNameRoleGroupsWithExpandedItems() m_model->setGroupedSorting(true); m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "d"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "d"); - QList > expectedGroups; + QList> expectedGroups; expectedGroups << QPair(0, QLatin1String("A")); expectedGroups << QPair(1, QLatin1String("D")); QCOMPARE(m_model->groups(), expectedGroups); @@ -1716,13 +2010,23 @@ void KFileItemModelTest::testNameRoleGroupsWithExpandedItems() m_model->setExpanded(0, true); QVERIFY(m_model->isExpanded(0)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b.txt" << "c.txt" << "d"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b.txt" + << "c.txt" + << "d"); QCOMPARE(m_model->groups(), expectedGroups); m_model->setExpanded(3, true); QVERIFY(m_model->isExpanded(3)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b.txt" << "c.txt" << "d" << "e.txt" << "f.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b.txt" + << "c.txt" + << "d" + << "e.txt" + << "f.txt"); QCOMPARE(m_model->groups(), expectedGroups); } @@ -1731,7 +2035,9 @@ void KFileItemModelTest::testInconsistentModel() QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFiles({"a/b/c1.txt", "a/b/c2.txt"}); @@ -1744,12 +2050,18 @@ void KFileItemModelTest::testInconsistentModel() m_model->setExpanded(0, true); QVERIFY(m_model->isExpanded(0)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b"); m_model->setExpanded(1, true); QVERIFY(m_model->isExpanded(1)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c1.txt" << "c2.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "c1.txt" + << "c2.txt"); // Add the files "c1.txt" and "c2.txt" to the model also as top-level items. // Such a thing can in principle happen when performing a search, and there @@ -1767,19 +2079,29 @@ void KFileItemModelTest::testInconsistentModel() items << newItem << m_model->fileItem(2) << m_model->fileItem(3); m_model->slotItemsAdded(m_model->directory(), items); m_model->slotCompleted(); - QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c1.txt" << "c2.txt" << "a2" << "c1.txt" << "c2.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "b" + << "c1.txt" + << "c2.txt" + << "a2" + << "c1.txt" + << "c2.txt"); m_model->setExpanded(0, false); // Test that the right items have been removed, see // https://bugs.kde.org/show_bug.cgi?id=324371 - QCOMPARE(itemsInModel(), QStringList() << "a" << "a2" << "c1.txt" << "c2.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "a2" + << "c1.txt" + << "c2.txt"); // Test that resorting does not cause a crash, see // https://bugs.kde.org/show_bug.cgi?id=325359 // The crash is not 100% reproducible, but Valgrind will report an invalid memory access. m_model->resortAllItems(); - } void KFileItemModelTest::testChangeRolesForFilteredItems() @@ -1794,7 +2116,10 @@ void KFileItemModelTest::testChangeRolesForFilteredItems() m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "aa.txt" << "aaa.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "aa.txt" + << "aaa.txt"); for (int index = 0; index < m_model->count(); ++index) { // All items should have the "text" and "owner" roles, but not "group". @@ -1813,7 +2138,9 @@ void KFileItemModelTest::testChangeRolesForFilteredItems() // Modify the filter, such that "aa.txt" reappears, and verify that all items have the expected roles. m_model->setNameFilter("aa"); - QCOMPARE(itemsInModel(), QStringList() << "aa.txt" << "aaa.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "aa.txt" + << "aaa.txt"); for (int index = 0; index < m_model->count(); ++index) { // All items should have the "text", "owner", and "group" roles. @@ -1828,7 +2155,10 @@ void KFileItemModelTest::testChangeRolesForFilteredItems() // Clear the filter, and verify that all items have the expected roles m_model->setNameFilter(QString()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "aa.txt" << "aaa.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "aa.txt" + << "aaa.txt"); for (int index = 0; index < m_model->count(); ++index) { // All items should have the "text" and "group" roles, but now "owner". @@ -1854,7 +2184,7 @@ void KFileItemModelTest::testChangeSortRoleWhileFiltering() entry[2].fastInsert(KIO::UDSEntry::UDS_USER, "user-a"); for (int i = 0; i < 3; ++i) { - entry[i].fastInsert(KIO::UDSEntry::UDS_FILE_TYPE, 0100000); // S_IFREG might not be defined on non-Unix platforms. + entry[i].fastInsert(KIO::UDSEntry::UDS_FILE_TYPE, 0100000); // S_IFREG might not be defined on non-Unix platforms. entry[i].fastInsert(KIO::UDSEntry::UDS_ACCESS, 07777); entry[i].fastInsert(KIO::UDSEntry::UDS_SIZE, 0); entry[i].fastInsert(KIO::UDSEntry::UDS_MODIFICATION_TIME, 0); @@ -1866,7 +2196,10 @@ void KFileItemModelTest::testChangeSortRoleWhileFiltering() m_model->slotItemsAdded(m_testDir->url(), items); m_model->slotCompleted(); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.txt"); // Add a filter. m_model->setNameFilter("a"); @@ -1877,7 +2210,10 @@ void KFileItemModelTest::testChangeSortRoleWhileFiltering() // Clear the filter, and verify that the items are sorted correctly. m_model->setNameFilter(QString()); - QCOMPARE(itemsInModel(), QStringList() << "c.txt" << "a.txt" << "b.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "c.txt" + << "a.txt" + << "b.txt"); } void KFileItemModelTest::testRefreshFilteredItems() @@ -1888,13 +2224,19 @@ void KFileItemModelTest::testRefreshFilteredItems() m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.jpg" << "d.jpg"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.jpg" + << "d.jpg"); const KFileItem fileItemC = m_model->fileItem(2); // Show only the .txt files. m_model->setNameFilter(".txt"); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt"); // Rename one of the .jpg files. KFileItem fileItemE = fileItemC; @@ -1906,7 +2248,11 @@ void KFileItemModelTest::testRefreshFilteredItems() // Show all files again, and verify that the model has updated the file name. m_model->setNameFilter(QString()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "d.jpg" << "e.jpg"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "d.jpg" + << "e.jpg"); } void KFileItemModelTest::testCreateMimeData() @@ -1914,7 +2260,9 @@ void KFileItemModelTest::testCreateMimeData() QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFile("a/1"); @@ -1926,13 +2274,15 @@ void KFileItemModelTest::testCreateMimeData() // Expand "a/". m_model->setExpanded(0, true); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a" << "1"); + QCOMPARE(itemsInModel(), + QStringList() << "a" + << "1"); // Verify that creating the MIME data for a child of an expanded folder does // not cause a crash, see https://bugs.kde.org/show_bug.cgi?id=329119 KItemSet selection; selection.insert(1); - QMimeData* mimeData = m_model->createMimeData(selection); + QMimeData *mimeData = m_model->createMimeData(selection); delete mimeData; } @@ -1941,7 +2291,9 @@ void KFileItemModelTest::testCollapseFolderWhileLoading() QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted); QSet modelRoles = m_model->roles(); - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFile("a2/b/c1.txt"); @@ -1954,13 +2306,18 @@ void KFileItemModelTest::testCollapseFolderWhileLoading() m_model->setExpanded(0, true); QVERIFY(m_model->isExpanded(0)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a2" << "b"); + QCOMPARE(itemsInModel(), + QStringList() << "a2" + << "b"); // Expand "a2/b/". m_model->setExpanded(1, true); QVERIFY(m_model->isExpanded(1)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a2" << "b" << "c1.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a2" + << "b" + << "c1.txt"); // Simulate that a new item "c2.txt" appears, but that the dir lister's completed() // signal is not emitted yet. @@ -1973,7 +2330,10 @@ void KFileItemModelTest::testCollapseFolderWhileLoading() const QUrl urlB = m_model->fileItem(1).url(); m_model->slotItemsAdded(urlB, KFileItemList() << fileItemC2); - QCOMPARE(itemsInModel(), QStringList() << "a2" << "b" << "c1.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a2" + << "b" + << "c1.txt"); // Collapse "a2/". This should also remove all its (indirect) children from // the model and from the model's m_pendingItemsToInsert member. @@ -1992,7 +2352,9 @@ void KFileItemModelTest::testCollapseFolderWhileLoading() m_model->setExpanded(0, true); QVERIFY(m_model->isExpanded(0)); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a2" << "b"); + QCOMPARE(itemsInModel(), + QStringList() << "a2" + << "b"); // Now simulate that a new folder "a1/" is appears, but that the dir lister's // completed() signal is not emitted yet. @@ -2003,13 +2365,17 @@ void KFileItemModelTest::testCollapseFolderWhileLoading() fileItemA1.setUrl(urlA1); m_model->slotItemsAdded(m_model->directory(), KFileItemList() << fileItemA1); - QCOMPARE(itemsInModel(), QStringList() << "a2" << "b"); + QCOMPARE(itemsInModel(), + QStringList() << "a2" + << "b"); // Collapse "a2/". Note that this will cause "a1/" to be added to the model, // i.e., the index of "a2/" will change from 0 to 1. Check that this does not // confuse the code which collapses the folder. m_model->setExpanded(0, false); - QCOMPARE(itemsInModel(), QStringList() << "a1" << "a2"); + QCOMPARE(itemsInModel(), + QStringList() << "a1" + << "a2"); QVERIFY(!m_model->isExpanded(0)); QVERIFY(!m_model->isExpanded(1)); } @@ -2022,7 +2388,11 @@ void KFileItemModelTest::testDeleteFileMoreThanOnce() m_model->loadDirectory(m_testDir->url()); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt" << "d.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "b.txt" + << "c.txt" + << "d.txt"); const KFileItem fileItemB = m_model->fileItem(1); @@ -2032,7 +2402,10 @@ void KFileItemModelTest::testDeleteFileMoreThanOnce() m_model->slotItemsDeleted(list); QVERIFY(m_model->isConsistent()); - QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "c.txt" << "d.txt"); + QCOMPARE(itemsInModel(), + QStringList() << "a.txt" + << "c.txt" + << "d.txt"); } void KFileItemModelTest::testInsertAfterExpand() @@ -2049,7 +2422,9 @@ void KFileItemModelTest::testInsertAfterExpand() // Test expanding subfolders in a folder with the items "a/", "a/a/" QSet originalModelRoles = m_model->roles(); QSet modelRoles = originalModelRoles; - modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount"; + modelRoles << "isExpanded" + << "isExpandable" + << "expandedParentsCount"; m_model->setRoles(modelRoles); m_testDir->createFile("a/b/1"); @@ -2068,7 +2443,6 @@ void KFileItemModelTest::testInsertAfterExpand() KItemRangeList itemRangeList = itemsInsertedSpy.takeFirst().at(0).value(); QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(0, 1)); // 1 new item "a/" with index 0 QCOMPARE(m_model->expandedParentsCount(0), 0); - } itemsInsertedSpy.clear(); @@ -2084,15 +2458,13 @@ void KFileItemModelTest::testInsertAfterExpand() KItemRangeList itemRangeList = itemsInsertedSpy.takeFirst().at(0).value(); QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(1, 1)); // 1 new item "a/b" with index 1 QCOMPARE(m_model->expandedParentsCount(1), 1); - } itemsInsertedSpy.clear(); // Expand "a/b" -> "a/b/1" becomes visible m_model->setExpanded(1, true); QVERIFY(itemsInsertedSpy.wait()); - QCOMPARE(m_model->expandedDirectories(), QSet({QUrl::fromLocalFile(m_testDir->path() + "/a"), - QUrl::fromLocalFile(m_testDir->path() + "/a/b")})); + QCOMPARE(m_model->expandedDirectories(), QSet({QUrl::fromLocalFile(m_testDir->path() + "/a"), QUrl::fromLocalFile(m_testDir->path() + "/a/b")})); QCOMPARE(itemsInsertedSpy.count(), 1); { @@ -2107,22 +2479,22 @@ void KFileItemModelTest::testInsertAfterExpand() // Insert additional files into "a/b/" m_testDir->createFile("a/b/2"); - #if KIO_VERSION < QT_VERSION_CHECK(5, 92, 0) - QEXPECT_FAIL("", "Requires new API from frameworks", Abort); - #endif +#if KIO_VERSION < QT_VERSION_CHECK(5, 92, 0) + QEXPECT_FAIL("", "Requires new API from frameworks", Abort); +#endif QVERIFY(!itemsInsertedSpy.wait(5000)); QCOMPARE(itemsInModel(), {"a"}); - m_model->setExpanded(0, true);; + m_model->setExpanded(0, true); + ; QTRY_COMPARE(itemsInModel(), QStringList({"a", "b", "1", "2"})); QCOMPARE(m_model->expandedParentsCount(0), 0); // a QCOMPARE(m_model->expandedParentsCount(1), 1); // a/b QCOMPARE(m_model->expandedParentsCount(2), 2); // a/b/1 - QCOMPARE(m_model->expandedParentsCount(3), 2) ;// a/b/2 - + QCOMPARE(m_model->expandedParentsCount(3), 2); // a/b/2 } void KFileItemModelTest::testCurrentDirRemoved() diff --git a/src/tests/kitemlistcontrollertest.cpp b/src/tests/kitemlistcontrollertest.cpp index 6fb1b72f91..a7842475a2 100644 --- a/src/tests/kitemlistcontrollertest.cpp +++ b/src/tests/kitemlistcontrollertest.cpp @@ -4,19 +4,19 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ -#include "kitemviews/kitemlistcontainer.h" +#include "kitemviews/kitemlistcontroller.h" #include "kitemviews/kfileitemlistview.h" #include "kitemviews/kfileitemmodel.h" -#include "kitemviews/kitemlistcontroller.h" +#include "kitemviews/kitemlistcontainer.h" #include "kitemviews/kitemlistselectionmanager.h" #include "kitemviews/private/kitemlistviewlayouter.h" #include "testdir.h" -#include #include -#include #include +#include #include +#include /** * \class KItemListControllerTestStyle is a proxy style for testing the @@ -27,9 +27,9 @@ class KItemListControllerTestStyle : public QProxyStyle { Q_OBJECT public: - KItemListControllerTestStyle(QStyle* style) : - QProxyStyle(style), - m_activateItemOnSingleClick((bool)style->styleHint(SH_ItemView_ActivateItemOnSingleClick)) + KItemListControllerTestStyle(QStyle *style) + : QProxyStyle(style) + , m_activateItemOnSingleClick((bool)style->styleHint(SH_ItemView_ActivateItemOnSingleClick)) { } @@ -43,10 +43,7 @@ public: return m_activateItemOnSingleClick; } - int styleHint(StyleHint hint, - const QStyleOption* option = nullptr, - const QWidget* widget = nullptr, - QStyleHintReturn* returnData = nullptr) const override + int styleHint(StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override { switch (hint) { case QStyle::SH_ItemView_ActivateItemOnSingleClick: @@ -88,13 +85,13 @@ private: void adjustGeometryForColumnCount(int count); private: - KFileItemListView* m_view; - KItemListController* m_controller; - KItemListSelectionManager* m_selectionManager; - KFileItemModel* m_model; - TestDir* m_testDir; - KItemListContainer* m_container; - KItemListControllerTestStyle* m_testStyle; + KFileItemListView *m_view; + KItemListController *m_controller; + KItemListSelectionManager *m_selectionManager; + KFileItemModel *m_model; + TestDir *m_testDir; + KItemListContainer *m_container; + KItemListControllerTestStyle *m_testStyle; }; /** @@ -119,12 +116,26 @@ void KItemListControllerTest::initTestCase() m_view->setStyle(m_testStyle); QStringList files; - files - << "a1" << "a2" << "a3" - << "b1" - << "c1" << "c2" << "c3" << "c4" << "c5" - << "d1" << "d2" << "d3" << "d4" - << "e" << "e 2" << "e 3" << "e 4" << "e 5" << "e 6" << "e 7"; + files << "a1" + << "a2" + << "a3" + << "b1" + << "c1" + << "c2" + << "c3" + << "c4" + << "c5" + << "d1" + << "d2" + << "d3" + << "d4" + << "e" + << "e 2" + << "e 3" + << "e 4" + << "e 5" + << "e 6" + << "e 7"; m_testDir->createFiles(files); m_model->loadDirectory(m_testDir->url()); @@ -167,11 +178,11 @@ void KItemListControllerTest::cleanup() * including the key and the keyboard modifiers. */ struct KeyPress { - - KeyPress(Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier) : - m_key(key), - m_modifier(modifier) - {} + KeyPress(Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier) + : m_key(key) + , m_modifier(modifier) + { + } Qt::Key m_key; Qt::KeyboardModifiers m_modifier; @@ -185,12 +196,12 @@ struct KeyPress { * key press. */ struct ViewState { - - ViewState(int current, const KItemSet &selection, bool activated = false) : - m_current(current), - m_selection(selection), - m_activated(activated) - {} + ViewState(int current, const KItemSet &selection, bool activated = false) + : m_current(current) + , m_selection(selection) + , m_activated(activated) + { + } int m_current; KItemSet m_selection; @@ -216,7 +227,7 @@ void KItemListControllerTest::testKeyboardNavigation_data() QTest::addColumn("columnCount"); QTest::addColumn("selectionBehavior"); QTest::addColumn("groupingEnabled"); - QTest::addColumn > >("testList"); + QTest::addColumn>>("testList"); QList layoutList; QHash layoutNames; @@ -243,7 +254,7 @@ void KItemListControllerTest::testKeyboardNavigation_data() groupingEnabledList.append(true); groupingEnabledNames[true] = "grouping enabled"; - for (const KFileItemListView::ItemLayout& layout : layoutList) { + for (const KFileItemListView::ItemLayout &layout : layoutList) { // The following settings depend on the layout. // Note that 'columns' are actually 'rows' in // Compact layout. @@ -282,61 +293,59 @@ void KItemListControllerTest::testKeyboardNavigation_data() } for (int columnCount : qAsConst(columnCountList)) { - for (const KItemListController::SelectionBehavior& selectionBehavior : qAsConst(selectionBehaviorList)) { + for (const KItemListController::SelectionBehavior &selectionBehavior : qAsConst(selectionBehaviorList)) { for (bool groupingEnabled : qAsConst(groupingEnabledList)) { - QList > testList; + QList> testList; // First, key presses which should have the same effect // for any layout and any number of columns. - testList - << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1)) - << qMakePair(KeyPress(Qt::Key_Return), ViewState(1, KItemSet() << 1, true)) - << qMakePair(KeyPress(Qt::Key_Enter), ViewState(1, KItemSet() << 1, true)) - << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2)) - << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3)) - << qMakePair(KeyPress(Qt::Key_Return), ViewState(3, KItemSet() << 2 << 3, true)) - << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 2)) - << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 2 << 3)) - << qMakePair(KeyPress(Qt::Key_Return), ViewState(4, KItemSet() << 2 << 3, true)) - << qMakePair(KeyPress(previousItemKey), ViewState(3, KItemSet() << 3)) - << qMakePair(KeyPress(Qt::Key_Home, Qt::ShiftModifier), ViewState(0, KItemSet() << 0 << 1 << 2 << 3)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3)) - << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 2 << 3)) - << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3)) - << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19)) - << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(18, KItemSet() << 18 << 19)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)) - << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet())) - << qMakePair(KeyPress(Qt::Key_Enter), ViewState(0, KItemSet(), true)) - << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet() << 0)) - << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet())) - << qMakePair(KeyPress(Qt::Key_Space), ViewState(0, KItemSet())) // This used to select, but we are now using it to trigger either - // selection mode or "QuickLook". Ctrl+Space still works for selecting as expected. - << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13)) - << qMakePair(KeyPress(Qt::Key_Space), ViewState(14, KItemSet() << 14)) - << qMakePair(KeyPress(Qt::Key_3), ViewState(15, KItemSet() << 15)) - << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet())) - << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13)) - << qMakePair(KeyPress(Qt::Key_E), ViewState(14, KItemSet() << 14)) - << qMakePair(KeyPress(Qt::Key_E), ViewState(15, KItemSet() << 15)) - << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet())) - << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)) - << qMakePair(KeyPress(Qt::Key_Escape), ViewState(0, KItemSet())); + testList << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1)) + << qMakePair(KeyPress(Qt::Key_Return), ViewState(1, KItemSet() << 1, true)) + << qMakePair(KeyPress(Qt::Key_Enter), ViewState(1, KItemSet() << 1, true)) + << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2)) + << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3)) + << qMakePair(KeyPress(Qt::Key_Return), ViewState(3, KItemSet() << 2 << 3, true)) + << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 2)) + << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 2 << 3)) + << qMakePair(KeyPress(Qt::Key_Return), ViewState(4, KItemSet() << 2 << 3, true)) + << qMakePair(KeyPress(previousItemKey), ViewState(3, KItemSet() << 3)) + << qMakePair(KeyPress(Qt::Key_Home, Qt::ShiftModifier), ViewState(0, KItemSet() << 0 << 1 << 2 << 3)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3)) + << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 2 << 3)) + << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3)) + << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19)) + << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(18, KItemSet() << 18 << 19)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)) + << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet())) + << qMakePair(KeyPress(Qt::Key_Enter), ViewState(0, KItemSet(), true)) + << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet() << 0)) + << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet())) + << qMakePair(KeyPress(Qt::Key_Space), ViewState(0, KItemSet())) // This used to select, but we are now using it to trigger either + // selection mode or "QuickLook". Ctrl+Space still works for selecting as expected. + << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13)) + << qMakePair(KeyPress(Qt::Key_Space), ViewState(14, KItemSet() << 14)) + << qMakePair(KeyPress(Qt::Key_3), ViewState(15, KItemSet() << 15)) + << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet())) + << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13)) + << qMakePair(KeyPress(Qt::Key_E), ViewState(14, KItemSet() << 14)) + << qMakePair(KeyPress(Qt::Key_E), ViewState(15, KItemSet() << 15)) + << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet())) + << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)) + << qMakePair(KeyPress(Qt::Key_Escape), ViewState(0, KItemSet())); // Next, we test combinations of key presses which only work for a // particular number of columns and either enabled or disabled grouping. // One column. if (columnCount == 1) { - testList - << qMakePair(KeyPress(nextRowKey), ViewState(1, KItemSet() << 1)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 1 << 2)) - << qMakePair(KeyPress(nextRowKey, Qt::ControlModifier), ViewState(3, KItemSet() << 1 << 2)) - << qMakePair(KeyPress(previousRowKey), ViewState(2, KItemSet() << 2)) - << qMakePair(KeyPress(previousItemKey), ViewState(1, KItemSet() << 1)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); + testList << qMakePair(KeyPress(nextRowKey), ViewState(1, KItemSet() << 1)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 1 << 2)) + << qMakePair(KeyPress(nextRowKey, Qt::ControlModifier), ViewState(3, KItemSet() << 1 << 2)) + << qMakePair(KeyPress(previousRowKey), ViewState(2, KItemSet() << 2)) + << qMakePair(KeyPress(previousItemKey), ViewState(1, KItemSet() << 1)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); } // Multiple columns: we test both 3 and 5 columns with grouping @@ -354,27 +363,26 @@ void KItemListControllerTest::testKeyboardNavigation_data() // d4 e1 e2 | 12 13 14 // e3 e4 e5 | 15 16 17 // e6 e7 | 18 19 - testList - << qMakePair(KeyPress(nextRowKey), ViewState(3, KItemSet() << 3)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 3)) - << qMakePair(KeyPress(nextRowKey), ViewState(7, KItemSet() << 7)) - << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8)) - << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(9, KItemSet() << 7 << 8 << 9)) - << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8)) - << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7)) - << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7)) - << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 5 << 6 << 7)) - << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7)) - << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7)) - << qMakePair(KeyPress(nextRowKey), ViewState(10, KItemSet() << 10)) - << qMakePair(KeyPress(nextItemKey), ViewState(11, KItemSet() << 11)) - << qMakePair(KeyPress(nextRowKey), ViewState(14, KItemSet() << 14)) - << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17)) - << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19)) - << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17)) - << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19)) - << qMakePair(KeyPress(previousRowKey), ViewState(16, KItemSet() << 16)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); + testList << qMakePair(KeyPress(nextRowKey), ViewState(3, KItemSet() << 3)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 3)) + << qMakePair(KeyPress(nextRowKey), ViewState(7, KItemSet() << 7)) + << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8)) + << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(9, KItemSet() << 7 << 8 << 9)) + << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8)) + << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7)) + << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7)) + << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 5 << 6 << 7)) + << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7)) + << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7)) + << qMakePair(KeyPress(nextRowKey), ViewState(10, KItemSet() << 10)) + << qMakePair(KeyPress(nextItemKey), ViewState(11, KItemSet() << 11)) + << qMakePair(KeyPress(nextRowKey), ViewState(14, KItemSet() << 14)) + << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17)) + << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19)) + << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17)) + << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19)) + << qMakePair(KeyPress(previousRowKey), ViewState(16, KItemSet() << 16)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); } if (columnCount == 5 && !groupingEnabled) { @@ -384,18 +392,17 @@ void KItemListControllerTest::testKeyboardNavigation_data() // c2 c3 c4 c5 d1 | 5 6 7 8 9 // d2 d3 d4 e1 e2 | 10 11 12 13 14 // e3 e4 e5 e6 e7 | 15 16 17 18 19 - testList - << qMakePair(KeyPress(nextRowKey), ViewState(5, KItemSet() << 5)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(6, KItemSet() << 5)) - << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11)) - << qMakePair(KeyPress(nextItemKey), ViewState(12, KItemSet() << 12)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(17, KItemSet() << 12 << 13 << 14 << 15 << 16 << 17)) - << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12)) - << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7 << 8 << 9 << 10 << 11 << 12)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12)) - << qMakePair(KeyPress(Qt::Key_End, Qt::ControlModifier), ViewState(19, KItemSet() << 12)) - << qMakePair(KeyPress(previousRowKey), ViewState(14, KItemSet() << 14)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); + testList << qMakePair(KeyPress(nextRowKey), ViewState(5, KItemSet() << 5)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(6, KItemSet() << 5)) + << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11)) + << qMakePair(KeyPress(nextItemKey), ViewState(12, KItemSet() << 12)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(17, KItemSet() << 12 << 13 << 14 << 15 << 16 << 17)) + << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12)) + << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7 << 8 << 9 << 10 << 11 << 12)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12)) + << qMakePair(KeyPress(Qt::Key_End, Qt::ControlModifier), ViewState(19, KItemSet() << 12)) + << qMakePair(KeyPress(previousRowKey), ViewState(14, KItemSet() << 14)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); } if (columnCount == 3 && groupingEnabled) { @@ -410,20 +417,19 @@ void KItemListControllerTest::testKeyboardNavigation_data() // e1 e2 e3 | 13 14 15 // e4 e5 e6 | 16 17 18 // e7 | 19 - testList - << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1)) - << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 2 << 3 << 4 << 5 << 6)) - << qMakePair(KeyPress(nextRowKey), ViewState(8, KItemSet() << 8)) - << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(12, KItemSet() << 11)) - << qMakePair(KeyPress(nextRowKey), ViewState(13, KItemSet() << 13)) - << qMakePair(KeyPress(nextRowKey), ViewState(16, KItemSet() << 16)) - << qMakePair(KeyPress(nextItemKey), ViewState(17, KItemSet() << 17)) - << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19)) - << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); + testList << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1)) + << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 2 << 3 << 4 << 5 << 6)) + << qMakePair(KeyPress(nextRowKey), ViewState(8, KItemSet() << 8)) + << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(12, KItemSet() << 11)) + << qMakePair(KeyPress(nextRowKey), ViewState(13, KItemSet() << 13)) + << qMakePair(KeyPress(nextRowKey), ViewState(16, KItemSet() << 16)) + << qMakePair(KeyPress(nextItemKey), ViewState(17, KItemSet() << 17)) + << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19)) + << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); } if (columnCount == 5 && groupingEnabled) { @@ -435,37 +441,27 @@ void KItemListControllerTest::testKeyboardNavigation_data() // d1 d2 d3 d4 | 9 10 11 12 // e1 e2 e3 e4 e5 | 13 14 15 16 17 // e6 e7 | 18 19 - testList - << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 1 << 2 << 3)) - << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 1 << 2 << 3 << 4 << 5)) - << qMakePair(KeyPress(nextItemKey), ViewState(6, KItemSet() << 6)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(7, KItemSet() << 6)) - << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(8, KItemSet() << 6)) - << qMakePair(KeyPress(nextRowKey), ViewState(12, KItemSet() << 12)) - << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17)) - << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19)) - << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17)) - << qMakePair(KeyPress(Qt::Key_End, Qt::ShiftModifier), ViewState(19, KItemSet() << 17 << 18 << 19)) - << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(14, KItemSet() << 14 << 15 << 16 << 17)) - << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); + testList << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 1 << 2 << 3)) + << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 1 << 2 << 3 << 4 << 5)) + << qMakePair(KeyPress(nextItemKey), ViewState(6, KItemSet() << 6)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(7, KItemSet() << 6)) + << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(8, KItemSet() << 6)) + << qMakePair(KeyPress(nextRowKey), ViewState(12, KItemSet() << 12)) + << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17)) + << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19)) + << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17)) + << qMakePair(KeyPress(Qt::Key_End, Qt::ShiftModifier), ViewState(19, KItemSet() << 17 << 18 << 19)) + << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(14, KItemSet() << 14 << 15 << 16 << 17)) + << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0)); } - const QString testName = - layoutNames[layout] + ", " + - QString("%1 columns, ").arg(columnCount) + - selectionBehaviorNames[selectionBehavior] + ", " + - groupingEnabledNames[groupingEnabled]; + const QString testName = layoutNames[layout] + ", " + QString("%1 columns, ").arg(columnCount) + selectionBehaviorNames[selectionBehavior] + + ", " + groupingEnabledNames[groupingEnabled]; const QByteArray testNameAscii = testName.toLatin1(); - QTest::newRow(testNameAscii.data()) - << layout - << scrollOrientation - << columnCount - << selectionBehavior - << groupingEnabled - << testList; + QTest::newRow(testNameAscii.data()) << layout << scrollOrientation << columnCount << selectionBehavior << groupingEnabled << testList; } } } @@ -518,9 +514,15 @@ void KItemListControllerTest::testKeyboardNavigation() QCOMPARE(m_selectionManager->currentItem(), current); switch (selectionBehavior) { - case KItemListController::NoSelection: QVERIFY(m_selectionManager->selectedItems().isEmpty()); break; - case KItemListController::SingleSelection: QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << current); break; - case KItemListController::MultiSelection: QCOMPARE(m_selectionManager->selectedItems(), selection); break; + case KItemListController::NoSelection: + QVERIFY(m_selectionManager->selectedItems().isEmpty()); + break; + case KItemListController::SingleSelection: + QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << current); + break; + case KItemListController::MultiSelection: + QCOMPARE(m_selectionManager->selectedItems(), selection); + break; } if (activated) { diff --git a/src/tests/kitemlistkeyboardsearchmanagertest.cpp b/src/tests/kitemlistkeyboardsearchmanagertest.cpp index 686f98b514..17424c8011 100644 --- a/src/tests/kitemlistkeyboardsearchmanagertest.cpp +++ b/src/tests/kitemlistkeyboardsearchmanagertest.cpp @@ -6,9 +6,9 @@ #include "kitemviews/private/kitemlistkeyboardsearchmanager.h" -#include #include #include +#include class KItemListKeyboardSearchManagerTest : public QObject { diff --git a/src/tests/kitemlistselectionmanagertest.cpp b/src/tests/kitemlistselectionmanagertest.cpp index 7f87fdcc85..da761d9a74 100644 --- a/src/tests/kitemlistselectionmanagertest.cpp +++ b/src/tests/kitemlistselectionmanagertest.cpp @@ -5,12 +5,12 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ -#include "kitemviews/kitemmodelbase.h" #include "kitemviews/kitemlistselectionmanager.h" +#include "kitemviews/kitemmodelbase.h" -#include #include #include +#include class DummyModel : public KItemModelBase { @@ -25,9 +25,9 @@ private: int m_count; }; -DummyModel::DummyModel() : - KItemModelBase(), - m_count(100) +DummyModel::DummyModel() + : KItemModelBase() + , m_count(100) { } @@ -47,7 +47,6 @@ QHash DummyModel::data(int index) const return QHash(); } - class KItemListSelectionManagerTest : public QObject { Q_OBJECT @@ -72,10 +71,10 @@ private Q_SLOTS: void testAnchoredSelectionAfterMovingItems(); private: - void verifySelectionChange(QSignalSpy& spy, const KItemSet& currentSelection, const KItemSet& previousSelection) const; + void verifySelectionChange(QSignalSpy &spy, const KItemSet ¤tSelection, const KItemSet &previousSelection) const; - KItemListSelectionManager* m_selectionManager; - DummyModel* m_model; + KItemListSelectionManager *m_selectionManager; + DummyModel *m_model; }; void KItemListSelectionManagerTest::initTestCase() @@ -139,10 +138,7 @@ void KItemListSelectionManagerTest::testCurrentItemAnchorItem() QVERIFY(m_selectionManager->hasSelection()); // Inserting items should update current item and anchor item. - m_selectionManager->itemsInserted(KItemRangeList() << - KItemRange(0, 1) << - KItemRange(2, 2) << - KItemRange(6, 3)); + m_selectionManager->itemsInserted(KItemRangeList() << KItemRange(0, 1) << KItemRange(2, 2) << KItemRange(6, 3)); QCOMPARE(m_selectionManager->currentItem(), 5); QCOMPARE(spyCurrent.count(), 1); @@ -156,10 +152,7 @@ void KItemListSelectionManagerTest::testCurrentItemAnchorItem() QVERIFY(m_selectionManager->hasSelection()); // Removing items should update current item and anchor item. - m_selectionManager->itemsRemoved(KItemRangeList() << - KItemRange(0, 2) << - KItemRange(2, 1) << - KItemRange(9, 2)); + m_selectionManager->itemsRemoved(KItemRangeList() << KItemRange(0, 2) << KItemRange(2, 1) << KItemRange(9, 2)); QCOMPARE(m_selectionManager->currentItem(), 2); QCOMPARE(spyCurrent.count(), 1); @@ -224,10 +217,7 @@ void KItemListSelectionManagerTest::testItemsInserted() QVERIFY(selectedItems.contains(17)); // Insert 3 items between the selections - m_selectionManager->itemsInserted(KItemRangeList() << - KItemRange(15, 1) << - KItemRange(16, 1) << - KItemRange(17, 1)); + m_selectionManager->itemsInserted(KItemRangeList() << KItemRange(15, 1) << KItemRange(16, 1) << KItemRange(17, 1)); selectedItems = m_selectionManager->selectedItems(); QCOMPARE(selectedItems.count(), 3); QVERIFY(selectedItems.contains(16)); @@ -254,10 +244,7 @@ void KItemListSelectionManagerTest::testItemsRemoved() } // Remove the items 6 , 8 and 10 - m_selectionManager->itemsRemoved(KItemRangeList() << - KItemRange(6, 1) << - KItemRange(8, 1) << - KItemRange(10, 1)); + m_selectionManager->itemsRemoved(KItemRangeList() << KItemRange(6, 1) << KItemRange(8, 1) << KItemRange(10, 1)); selectedItems = m_selectionManager->selectedItems(); QCOMPARE(selectedItems.count(), 3); QVERIFY(selectedItems.contains(5)); @@ -306,15 +293,9 @@ void KItemListSelectionManagerTest::testAnchoredSelection() QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << 5 << 6 << 7 << 9 << 10); } -namespace { - enum ChangeType { - NoChange, - InsertItems, - RemoveItems, - MoveItems, - EndAnchoredSelection, - SetSelected - }; +namespace +{ +enum ChangeType { NoChange, InsertItems, RemoveItems, MoveItems, EndAnchoredSelection, SetSelected }; } Q_DECLARE_METATYPE(KItemSet) @@ -356,77 +337,38 @@ void KItemListSelectionManagerTest::testChangeSelection_data() QTest::addColumn("current"); QTest::addColumn("expectedSelection"); QTest::addColumn("changeType"); - QTest::addColumn >("data"); + QTest::addColumn>("data"); QTest::addColumn("finalSelection"); - QTest::newRow("No change") - << (KItemSet() << 5 << 6) - << 2 << 3 - << (KItemSet() << 2 << 3 << 5 << 6) - << NoChange - << QList{} - << (KItemSet() << 2 << 3 << 5 << 6); + QTest::newRow("No change") << (KItemSet() << 5 << 6) << 2 << 3 << (KItemSet() << 2 << 3 << 5 << 6) << NoChange << QList{} + << (KItemSet() << 2 << 3 << 5 << 6); - QTest::newRow("Insert Items") - << (KItemSet() << 5 << 6) - << 2 << 3 - << (KItemSet() << 2 << 3 << 5 << 6) - << InsertItems - << QList{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(5, 2) << KItemRange(10, 5))} - << (KItemSet() << 3 << 4 << 8 << 9); + QTest::newRow("Insert Items") << (KItemSet() << 5 << 6) << 2 << 3 << (KItemSet() << 2 << 3 << 5 << 6) << InsertItems + << QList{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(5, 2) << KItemRange(10, 5))} + << (KItemSet() << 3 << 4 << 8 << 9); - QTest::newRow("Remove Items") - << (KItemSet() << 5 << 6) - << 2 << 3 - << (KItemSet() << 2 << 3 << 5 << 6) - << RemoveItems - << QList{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(3, 1) << KItemRange(10, 5))} - << (KItemSet() << 1 << 2 << 3 << 4); + QTest::newRow("Remove Items") << (KItemSet() << 5 << 6) << 2 << 3 << (KItemSet() << 2 << 3 << 5 << 6) << RemoveItems + << QList{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(3, 1) << KItemRange(10, 5))} + << (KItemSet() << 1 << 2 << 3 << 4); - QTest::newRow("Empty Anchored Selection") - << KItemSet() - << 2 << 2 - << KItemSet() - << EndAnchoredSelection - << QList{} - << KItemSet(); + QTest::newRow("Empty Anchored Selection") << KItemSet() << 2 << 2 << KItemSet() << EndAnchoredSelection << QList{} << KItemSet(); - QTest::newRow("Toggle selection") - << (KItemSet() << 1 << 3 << 4) - << 6 << 8 - << (KItemSet() << 1 << 3 << 4 << 6 << 7 << 8) - << SetSelected - << QList{0, 10, QVariant::fromValue(KItemListSelectionManager::Toggle)} - << (KItemSet() << 0 << 2 << 5 << 9); + QTest::newRow("Toggle selection") << (KItemSet() << 1 << 3 << 4) << 6 << 8 << (KItemSet() << 1 << 3 << 4 << 6 << 7 << 8) << SetSelected + << QList{0, 10, QVariant::fromValue(KItemListSelectionManager::Toggle)} << (KItemSet() << 0 << 2 << 5 << 9); // Swap items 2, 3 and 4, 5 - QTest::newRow("Move items") - << (KItemSet() << 0 << 1 << 2 << 3) - << -1 << -1 - << (KItemSet() << 0 << 1 << 2 << 3) - << MoveItems - << QList{QVariant::fromValue(KItemRange(2, 4)), - QVariant::fromValue(QList{4, 5, 2, 3})} - << (KItemSet() << 0 << 1 << 4 << 5); + QTest::newRow("Move items") << (KItemSet() << 0 << 1 << 2 << 3) << -1 << -1 << (KItemSet() << 0 << 1 << 2 << 3) << MoveItems + << QList{QVariant::fromValue(KItemRange(2, 4)), QVariant::fromValue(QList{4, 5, 2, 3})} + << (KItemSet() << 0 << 1 << 4 << 5); QTest::newRow("Move items with active anchored selection") - << KItemSet() - << 0 << 3 - << (KItemSet() << 0 << 1 << 2 << 3) - << MoveItems - << QList{QVariant::fromValue(KItemRange(2, 4)), - QVariant::fromValue(QList{4, 5, 2, 3})} - << (KItemSet() << 0 << 1 << 4 << 5); + << KItemSet() << 0 << 3 << (KItemSet() << 0 << 1 << 2 << 3) << MoveItems + << QList{QVariant::fromValue(KItemRange(2, 4)), QVariant::fromValue(QList{4, 5, 2, 3})} << (KItemSet() << 0 << 1 << 4 << 5); // Revert sort order - QTest::newRow("Revert sort order") - << (KItemSet() << 0 << 1) - << 3 << 4 - << (KItemSet() << 0 << 1 << 3 << 4) - << MoveItems - << QList{QVariant::fromValue(KItemRange(0, 10)), - QVariant::fromValue(QList{9, 8, 7, 6, 5, 4, 3, 2, 1, 0})} - << (KItemSet() << 5 << 6 << 8 << 9); + QTest::newRow("Revert sort order") << (KItemSet() << 0 << 1) << 3 << 4 << (KItemSet() << 0 << 1 << 3 << 4) << MoveItems + << QList{QVariant::fromValue(KItemRange(0, 10)), QVariant::fromValue(QList{9, 8, 7, 6, 5, 4, 3, 2, 1, 0})} + << (KItemSet() << 5 << 6 << 8 << 9); } void KItemListSelectionManagerTest::testChangeSelection() @@ -470,8 +412,7 @@ void KItemListSelectionManagerTest::testChangeSelection() m_selectionManager->itemsRemoved(data.at(0).value()); break; case MoveItems: - m_selectionManager->itemsMoved(data.at(0).value(), - data.at(1).value>()); + m_selectionManager->itemsMoved(data.at(0).value(), data.at(1).value>()); break; case EndAnchoredSelection: m_selectionManager->endAnchoredSelection(); @@ -501,11 +442,11 @@ void KItemListSelectionManagerTest::testDeleteCurrentItem_data() QTest::addColumn("removeCount"); QTest::addColumn("newCurrentItemIndex"); - QTest::newRow("Remove before") << 50 << 0 << 10 << 40; - QTest::newRow("Remove after") << 50 << 51 << 10 << 50; - QTest::newRow("Remove exactly current item") << 50 << 50 << 1 << 50; - QTest::newRow("Remove around current item") << 50 << 45 << 10 << 45; - QTest::newRow("Remove all except one item") << 50 << 1 << 99 << 0; + QTest::newRow("Remove before") << 50 << 0 << 10 << 40; + QTest::newRow("Remove after") << 50 << 51 << 10 << 50; + QTest::newRow("Remove exactly current item") << 50 << 50 << 1 << 50; + QTest::newRow("Remove around current item") << 50 << 45 << 10 << 45; + QTest::newRow("Remove all except one item") << 50 << 1 << 99 << 0; } void KItemListSelectionManagerTest::testDeleteCurrentItem() @@ -540,25 +481,21 @@ void KItemListSelectionManagerTest::testAnchoredSelectionAfterMovingItems() QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << 1 << 2); } -void KItemListSelectionManagerTest::verifySelectionChange(QSignalSpy& spy, - const KItemSet& currentSelection, - const KItemSet& previousSelection) const +void KItemListSelectionManagerTest::verifySelectionChange(QSignalSpy &spy, const KItemSet ¤tSelection, const KItemSet &previousSelection) const { QCOMPARE(m_selectionManager->selectedItems(), currentSelection); QCOMPARE(m_selectionManager->hasSelection(), !currentSelection.isEmpty()); for (int index = 0; index < m_selectionManager->model()->count(); ++index) { if (currentSelection.contains(index)) { QVERIFY(m_selectionManager->isSelected(index)); - } - else { + } else { QVERIFY(!m_selectionManager->isSelected(index)); } } if (currentSelection == previousSelection) { QCOMPARE(spy.count(), 0); - } - else { + } else { QCOMPARE(spy.count(), 1); QList arguments = spy.takeFirst(); QCOMPARE(qvariant_cast(arguments.at(0)), currentSelection); diff --git a/src/tests/kitemrangetest.cpp b/src/tests/kitemrangetest.cpp index c782acee75..93e22f6bc0 100644 --- a/src/tests/kitemrangetest.cpp +++ b/src/tests/kitemrangetest.cpp @@ -29,7 +29,7 @@ void KItemRangeTest::initTestCase() void KItemRangeTest::testFromSortedContainer_data() { - QTest::addColumn >("sortedNumbers"); + QTest::addColumn>("sortedNumbers"); QTest::addColumn("expected"); QTest::newRow("empty") << QVector{} << KItemRangeList(); diff --git a/src/tests/kitemsettest.cpp b/src/tests/kitemsettest.cpp index b5e0a82cd6..e0c536c679 100644 --- a/src/tests/kitemsettest.cpp +++ b/src/tests/kitemsettest.cpp @@ -14,10 +14,10 @@ Q_DECLARE_METATYPE(KItemRangeList) /** * Converts a KItemRangeList to a KItemSet. */ -KItemSet KItemRangeList2KItemSet(const KItemRangeList& itemRanges) +KItemSet KItemRangeList2KItemSet(const KItemRangeList &itemRanges) { KItemSet result; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { for (int i = range.index; i < range.index + range.count; ++i) { result.insert(i); } @@ -28,10 +28,10 @@ KItemSet KItemRangeList2KItemSet(const KItemRangeList& itemRanges) /** * Converts a KItemRangeList to a QSet. */ -QSet KItemRangeList2QSet(const KItemRangeList& itemRanges) +QSet KItemRangeList2QSet(const KItemRangeList &itemRanges) { QSet result; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { for (int i = range.index; i < range.index + range.count; ++i) { result.insert(i); } @@ -42,10 +42,10 @@ QSet KItemRangeList2QSet(const KItemRangeList& itemRanges) /** * Converts a KItemRangeList to a QVector. */ -QVector KItemRangeList2QVector(const KItemRangeList& itemRanges) +QVector KItemRangeList2QVector(const KItemRangeList &itemRanges) { QVector result; - for (const KItemRange& range : itemRanges) { + for (const KItemRange &range : itemRanges) { for (int i = range.index; i < range.index + range.count; ++i) { result.append(i); } @@ -56,7 +56,7 @@ QVector KItemRangeList2QVector(const KItemRangeList& itemRanges) /** * Converts a KItemSet to a QSet. */ -static QSet KItemSet2QSet(const KItemSet& itemSet) +static QSet KItemSet2QSet(const KItemSet &itemSet) { QSet result; for (int i : itemSet) { @@ -77,7 +77,6 @@ static QSet KItemSet2QSet(const KItemSet& itemSet) return result; } - /** * The main test class. */ @@ -106,7 +105,7 @@ private Q_SLOTS: void testSymmetricDifference(); private: - QHash m_testCases; + QHash m_testCases; }; void KItemSetTest::initTestCase() @@ -122,7 +121,8 @@ void KItemSetTest::initTestCase() m_testCases.insert("[1, 2] [4, 5]", KItemRangeList() << KItemRange(1, 2) << KItemRange(4, 2)); m_testCases.insert("[1, 5]", KItemRangeList() << KItemRange(1, 5)); m_testCases.insert("[1, 2] [4, 5] [7] [9, 10] [13] [20, 25] [30]", - KItemRangeList() << KItemRange(1, 2) << KItemRange(4, 2) << KItemRange(7, 1) << KItemRange(9, 2) << KItemRange(20, 6) << KItemRange(30, 1)); + KItemRangeList() << KItemRange(1, 2) << KItemRange(4, 2) << KItemRange(7, 1) << KItemRange(9, 2) << KItemRange(20, 6) + << KItemRange(30, 1)); m_testCases.insert("[-10, -1]", KItemRangeList() << KItemRange(-10, 10)); m_testCases.insert("[-10, 0]", KItemRangeList() << KItemRange(-10, 11)); m_testCases.insert("[-10, 1]", KItemRangeList() << KItemRange(-10, 12)); @@ -134,8 +134,8 @@ void KItemSetTest::testConstruction_data() { QTest::addColumn("itemRanges"); - QHash::const_iterator it = m_testCases.constBegin(); - const QHash::const_iterator end = m_testCases.constEnd(); + QHash::const_iterator it = m_testCases.constBegin(); + const QHash::const_iterator end = m_testCases.constEnd(); while (it != end) { QTest::newRow(it.key()) << it.value(); @@ -170,8 +170,8 @@ void KItemSetTest::testIterators_data() { QTest::addColumn("itemRanges"); - QHash::const_iterator it = m_testCases.constBegin(); - const QHash::const_iterator end = m_testCases.constEnd(); + QHash::const_iterator it = m_testCases.constBegin(); + const QHash::const_iterator end = m_testCases.constEnd(); while (it != end) { QTest::newRow(it.key()) << it.value(); @@ -305,8 +305,8 @@ void KItemSetTest::testFind_data() { QTest::addColumn("itemRanges"); - QHash::const_iterator it = m_testCases.constBegin(); - const QHash::const_iterator end = m_testCases.constEnd(); + QHash::const_iterator it = m_testCases.constBegin(); + const QHash::const_iterator end = m_testCases.constEnd(); while (it != end) { QTest::newRow(it.key()) << it.value(); @@ -364,8 +364,8 @@ void KItemSetTest::testChangingOneItem_data() { QTest::addColumn("itemRanges"); - QHash::const_iterator it = m_testCases.constBegin(); - const QHash::const_iterator end = m_testCases.constEnd(); + QHash::const_iterator it = m_testCases.constBegin(); + const QHash::const_iterator end = m_testCases.constEnd(); while (it != end) { QTest::newRow(it.key()) << it.value(); @@ -403,7 +403,6 @@ void KItemSetTest::testChangingOneItem() // Test insert(int), remove(int), and erase(KItemSet::iterator) // for items between min - 2 and max + 2. for (int i = min - 2; i <= max + 2; ++i) { - // Test insert(int). { KItemSet tmp(itemSet); @@ -512,11 +511,11 @@ void KItemSetTest::testAddSets_data() QTest::addColumn("itemRanges1"); QTest::addColumn("itemRanges2"); - QHash::const_iterator it1 = m_testCases.constBegin(); - const QHash::const_iterator end = m_testCases.constEnd(); + QHash::const_iterator it1 = m_testCases.constBegin(); + const QHash::const_iterator end = m_testCases.constEnd(); while (it1 != end) { - QHash::const_iterator it2 = m_testCases.constBegin(); + QHash::const_iterator it2 = m_testCases.constBegin(); while (it2 != end) { QByteArray name = it1.key() + QByteArray(" + ") + it2.key(); @@ -551,11 +550,11 @@ void KItemSetTest::testSymmetricDifference_data() QTest::addColumn("itemRanges1"); QTest::addColumn("itemRanges2"); - QHash::const_iterator it1 = m_testCases.constBegin(); - const QHash::const_iterator end = m_testCases.constEnd(); + QHash::const_iterator it1 = m_testCases.constBegin(); + const QHash::const_iterator end = m_testCases.constEnd(); while (it1 != end) { - QHash::const_iterator it2 = m_testCases.constBegin(); + QHash::const_iterator it2 = m_testCases.constBegin(); while (it2 != end) { QByteArray name = it1.key() + QByteArray(" ^ ") + it2.key(); @@ -594,7 +593,6 @@ void KItemSetTest::testSymmetricDifference() QCOMPARE(itemSet2 ^ symmetricDifference, itemSet1); } - QTEST_GUILESS_MAIN(KItemSetTest) #include "kitemsettest.moc" diff --git a/src/tests/testdir.cpp b/src/tests/testdir.cpp index 6fbc4c426a..30ca6632ec 100644 --- a/src/tests/testdir.cpp +++ b/src/tests/testdir.cpp @@ -12,8 +12,8 @@ #include #endif -TestDir::TestDir(const QString& directoryPrefix) : - QTemporaryDir(directoryPrefix) +TestDir::TestDir(const QString &directoryPrefix) + : QTemporaryDir(directoryPrefix) { } @@ -27,7 +27,7 @@ QUrl TestDir::url() const } /** The following function is taken from kdelibs/kio/tests/kiotesthelper.h, copyright (C) 2006 by David Faure */ -static void setTimeStamp(const QString& path, const QDateTime& mtime) +static void setTimeStamp(const QString &path, const QDateTime &mtime) { #ifdef Q_OS_UNIX struct utimbuf utbuf; @@ -42,7 +42,7 @@ static void setTimeStamp(const QString& path, const QDateTime& mtime) #endif } -void TestDir::createFile(const QString& path, const QByteArray& data, const QDateTime& time) +void TestDir::createFile(const QString &path, const QByteArray &data, const QDateTime &time) { QString absolutePath = path; makePathAbsoluteAndCreateParents(absolutePath); @@ -59,14 +59,14 @@ void TestDir::createFile(const QString& path, const QByteArray& data, const QDat Q_ASSERT(QFile::exists(absolutePath)); } -void TestDir::createFiles(const QStringList& files) +void TestDir::createFiles(const QStringList &files) { - for (const QString& path : files) { + for (const QString &path : files) { createFile(path); } } -void TestDir::createDir(const QString& path, const QDateTime& time) +void TestDir::createDir(const QString &path, const QDateTime &time) { QString absolutePath = path; makePathAbsoluteAndCreateParents(absolutePath); @@ -79,14 +79,14 @@ void TestDir::createDir(const QString& path, const QDateTime& time) Q_ASSERT(QFile::exists(absolutePath)); } -void TestDir::removeFiles(const QStringList& files) +void TestDir::removeFiles(const QStringList &files) { - for (const QString& path : files) { + for (const QString &path : files) { removeFile(path); } } -void TestDir::removeFile(const QString& path) +void TestDir::removeFile(const QString &path) { QString absolutePath = path; QFileInfo fileInfo(absolutePath); @@ -96,7 +96,7 @@ void TestDir::removeFile(const QString& path) QFile::remove(absolutePath); } -void TestDir::removeDir(const QString& path) +void TestDir::removeDir(const QString &path) { QString absolutePath = path; QFileInfo fileInfo(absolutePath); @@ -107,7 +107,7 @@ void TestDir::removeDir(const QString& path) dirToRemove.removeRecursively(); } -void TestDir::makePathAbsoluteAndCreateParents(QString& path) +void TestDir::makePathAbsoluteAndCreateParents(QString &path) { QFileInfo fileInfo(path); if (!fileInfo.isAbsolute()) { diff --git a/src/tests/testdir.h b/src/tests/testdir.h index 921a891857..10d7614c28 100644 --- a/src/tests/testdir.h +++ b/src/tests/testdir.h @@ -7,9 +7,9 @@ #ifndef TESTDIR_H #define TESTDIR_H -#include -#include #include +#include +#include /** * TestDir provides a temporary directory. In addition to QTemporaryDir, it has @@ -17,9 +17,8 @@ */ class TestDir : public QTemporaryDir { - public: - TestDir(const QString& directoryPrefix = QString()); + TestDir(const QString &directoryPrefix = QString()); virtual ~TestDir(); QUrl url() const; @@ -29,19 +28,16 @@ public: * The paths may be absolute or relative to the test directory. Any missing parent * directories will be created automatically. */ - void createFile(const QString& path, - const QByteArray& data = QByteArray("test"), - const QDateTime& time = QDateTime()); - void createFiles(const QStringList& files); - void createDir(const QString& path, const QDateTime& time = QDateTime()); + void createFile(const QString &path, const QByteArray &data = QByteArray("test"), const QDateTime &time = QDateTime()); + void createFiles(const QStringList &files); + void createDir(const QString &path, const QDateTime &time = QDateTime()); - void removeFile(const QString& path); - void removeFiles(const QStringList& files); - void removeDir(const QString& path); + void removeFile(const QString &path); + void removeFiles(const QStringList &files); + void removeDir(const QString &path); private: - void makePathAbsoluteAndCreateParents(QString& path); - + void makePathAbsoluteAndCreateParents(QString &path); }; #endif diff --git a/src/tests/viewpropertiestest.cpp b/src/tests/viewpropertiestest.cpp index 14d59be0aa..7b30203d27 100644 --- a/src/tests/viewpropertiestest.cpp +++ b/src/tests/viewpropertiestest.cpp @@ -4,8 +4,8 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ -#include "dolphin_generalsettings.h" #include "views/viewproperties.h" +#include "dolphin_generalsettings.h" #include "testdir.h" #include @@ -24,7 +24,7 @@ private Q_SLOTS: private: bool m_globalViewProps; - TestDir* m_testDir; + TestDir *m_testDir; }; void ViewPropertiesTest::initTestCase() diff --git a/src/trash/dolphintrash.cpp b/src/trash/dolphintrash.cpp index 906da2b9da..e1530bfaeb 100644 --- a/src/trash/dolphintrash.cpp +++ b/src/trash/dolphintrash.cpp @@ -7,11 +7,11 @@ #include "dolphintrash.h" -#include -#include #include #include #include +#include +#include #include #if KIO_VERSION >= QT_VERSION_CHECK(5, 100, 0) @@ -72,7 +72,7 @@ void Trash::empty(QWidget *window) uiDelegate.setWindow(window); bool confirmed = uiDelegate.askDeleteConfirmation(QList(), KIO::JobUiDelegate::EmptyTrash, KIO::JobUiDelegate::DefaultConfirmation); if (confirmed) { - KIO::Job* job = KIO::emptyTrash(); + KIO::Job *job = KIO::emptyTrash(); KJobWidgets::setWindow(job, window); job->uiDelegate()->setAutoErrorHandlingEnabled(true); QObject::connect(job, &KIO::Job::result, notifyEmptied); @@ -85,4 +85,3 @@ bool Trash::isEmpty() KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig); return (trashConfig.group("Status").readEntry("Empty", true)); } - diff --git a/src/trash/dolphintrash.h b/src/trash/dolphintrash.h index c65cf92329..388bc82ab4 100644 --- a/src/trash/dolphintrash.h +++ b/src/trash/dolphintrash.h @@ -10,21 +10,21 @@ #include -#include #include +#include -class Trash: public QObject +class Trash : public QObject { Q_OBJECT public: // delete copy and move constructors and assign operators - Trash(Trash const&) = delete; - Trash(Trash&&) = delete; - Trash& operator=(Trash const&) = delete; - Trash& operator=(Trash &&) = delete; + Trash(Trash const &) = delete; + Trash(Trash &&) = delete; + Trash &operator=(Trash const &) = delete; + Trash &operator=(Trash &&) = delete; - static Trash& instance(); + static Trash &instance(); static void empty(QWidget *window); static bool isEmpty(); diff --git a/src/userfeedback/dolphinfeedbackprovider.h b/src/userfeedback/dolphinfeedbackprovider.h index f6575d49fd..8be2f81b6f 100644 --- a/src/userfeedback/dolphinfeedbackprovider.h +++ b/src/userfeedback/dolphinfeedbackprovider.h @@ -16,10 +16,10 @@ class DolphinFeedbackProvider : public KUserFeedback::Provider public: static DolphinFeedbackProvider *instance(); - DolphinFeedbackProvider(const DolphinFeedbackProvider&) = delete; - DolphinFeedbackProvider(DolphinFeedbackProvider&&) = delete; - DolphinFeedbackProvider& operator=(const DolphinFeedbackProvider&) = delete; - DolphinFeedbackProvider& operator=(DolphinFeedbackProvider&&) = delete; + DolphinFeedbackProvider(const DolphinFeedbackProvider &) = delete; + DolphinFeedbackProvider(DolphinFeedbackProvider &&) = delete; + DolphinFeedbackProvider &operator=(const DolphinFeedbackProvider &) = delete; + DolphinFeedbackProvider &operator=(DolphinFeedbackProvider &&) = delete; private: DolphinFeedbackProvider(); diff --git a/src/userfeedback/placesdatasource.cpp b/src/userfeedback/placesdatasource.cpp index 991ce0a18b..cdbd5d7570 100644 --- a/src/userfeedback/placesdatasource.cpp +++ b/src/userfeedback/placesdatasource.cpp @@ -17,7 +17,8 @@ PlacesDataSource::PlacesDataSource() : KUserFeedback::AbstractDataSource(QStringLiteral("places"), KUserFeedback::Provider::DetailedSystemInformation) -{} +{ +} QString PlacesDataSource::name() const { diff --git a/src/userfeedback/placesdatasource.h b/src/userfeedback/placesdatasource.h index f25f1067ca..d4666af25f 100644 --- a/src/userfeedback/placesdatasource.h +++ b/src/userfeedback/placesdatasource.h @@ -19,7 +19,6 @@ public: QString name() const override; QString description() const override; QVariant data() override; - }; #endif // PLACESDATASOURCE_H diff --git a/src/userfeedback/settingsdatasource.cpp b/src/userfeedback/settingsdatasource.cpp index 03a25ff750..c517793adb 100644 --- a/src/userfeedback/settingsdatasource.cpp +++ b/src/userfeedback/settingsdatasource.cpp @@ -5,8 +5,8 @@ */ #include "settingsdatasource.h" -#include "dolphinmainwindow.h" #include "dolphin_generalsettings.h" +#include "dolphinmainwindow.h" #include #include @@ -16,7 +16,8 @@ SettingsDataSource::SettingsDataSource() : KUserFeedback::AbstractDataSource(QStringLiteral("settings"), KUserFeedback::Provider::DetailedSystemInformation) -{} +{ +} QString SettingsDataSource::name() const { diff --git a/src/views/dolphinfileitemlistwidget.cpp b/src/views/dolphinfileitemlistwidget.cpp index c3a15ea6f4..429060221f 100644 --- a/src/views/dolphinfileitemlistwidget.cpp +++ b/src/views/dolphinfileitemlistwidget.cpp @@ -10,9 +10,8 @@ #include -DolphinFileItemListWidget::DolphinFileItemListWidget(KItemListWidgetInformant* informant, - QGraphicsItem* parent) : - KFileItemListWidget(informant, parent) +DolphinFileItemListWidget::DolphinFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent) + : KFileItemListWidget(informant, parent) { } @@ -35,23 +34,39 @@ void DolphinFileItemListWidget::refreshCache() // as tint colors and are mixed with the current set text color. The tint colors // have been optimized for the base colors of the corresponding Oxygen emblems. switch (version) { - case KVersionControlPlugin::UpdateRequiredVersion: tintColor = Qt::yellow; break; - case KVersionControlPlugin::LocallyModifiedUnstagedVersion: tintColor = Qt::green; break; - case KVersionControlPlugin::LocallyModifiedVersion: tintColor = Qt::green; break; - case KVersionControlPlugin::AddedVersion: tintColor = Qt::green; break; - case KVersionControlPlugin::RemovedVersion: tintColor = Qt::darkRed; break; - case KVersionControlPlugin::ConflictingVersion: tintColor = Qt::red; break; - case KVersionControlPlugin::IgnoredVersion: tintColor = Qt::white; break; - case KVersionControlPlugin::MissingVersion: tintColor = Qt::red; break; + case KVersionControlPlugin::UpdateRequiredVersion: + tintColor = Qt::yellow; + break; + case KVersionControlPlugin::LocallyModifiedUnstagedVersion: + tintColor = Qt::green; + break; + case KVersionControlPlugin::LocallyModifiedVersion: + tintColor = Qt::green; + break; + case KVersionControlPlugin::AddedVersion: + tintColor = Qt::green; + break; + case KVersionControlPlugin::RemovedVersion: + tintColor = Qt::darkRed; + break; + case KVersionControlPlugin::ConflictingVersion: + tintColor = Qt::red; + break; + case KVersionControlPlugin::IgnoredVersion: + tintColor = Qt::white; + break; + case KVersionControlPlugin::MissingVersion: + tintColor = Qt::red; + break; case KVersionControlPlugin::NormalVersion: case KVersionControlPlugin::UnversionedVersion: default: break; } - color = QColor((tintColor.red() + textColor.red()) / 2, + color = QColor((tintColor.red() + textColor.red()) / 2, (tintColor.green() + textColor.green()) / 2, - (tintColor.blue() + textColor.blue()) / 2, + (tintColor.blue() + textColor.blue()) / 2, (tintColor.alpha() + textColor.alpha()) / 2); setOverlay(overlayForState(version, styleOption().iconSize)); @@ -109,4 +124,3 @@ QPixmap DolphinFileItemListWidget::overlayForState(KVersionControlPlugin::ItemVe return QIcon::fromTheme(iconName).pixmap(QSize(overlayHeight, overlayHeight)); } - diff --git a/src/views/dolphinfileitemlistwidget.h b/src/views/dolphinfileitemlistwidget.h index dc9e275859..ac98666c8e 100644 --- a/src/views/dolphinfileitemlistwidget.h +++ b/src/views/dolphinfileitemlistwidget.h @@ -22,7 +22,7 @@ class DOLPHIN_EXPORT DolphinFileItemListWidget : public KFileItemListWidget Q_OBJECT public: - DolphinFileItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent); + DolphinFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent); ~DolphinFileItemListWidget() override; protected: @@ -30,9 +30,6 @@ protected: private: static QPixmap overlayForState(KVersionControlPlugin::ItemVersion version, int size); - }; #endif - - diff --git a/src/views/dolphinitemlistview.cpp b/src/views/dolphinitemlistview.cpp index 5dec2b1f88..a24e313477 100644 --- a/src/views/dolphinitemlistview.cpp +++ b/src/views/dolphinitemlistview.cpp @@ -17,10 +17,9 @@ #include #include - -DolphinItemListView::DolphinItemListView(QGraphicsWidget* parent) : - KFileItemListView(parent), - m_zoomLevel(0) +DolphinItemListView::DolphinItemListView(QGraphicsWidget *parent) + : KFileItemListView(parent) + , m_zoomLevel(0) { updateFont(); updateGridSize(); @@ -104,7 +103,7 @@ void DolphinItemListView::writeSettings() DetailsModeSettings::self()->save(); } -KItemListWidgetCreatorBase* DolphinItemListView::defaultWidgetCreator() const +KItemListWidgetCreatorBase *DolphinItemListView::defaultWidgetCreator() const { return new KItemListWidgetCreator(); } @@ -135,8 +134,7 @@ void DolphinItemListView::onPreviewsShownChanged(bool shown) updateGridSize(); } -void DolphinItemListView::onVisibleRolesChanged(const QList& current, - const QList& previous) +void DolphinItemListView::onVisibleRolesChanged(const QList ¤t, const QList &previous) { KFileItemListView::onVisibleRolesChanged(current, previous); updateGridSize(); @@ -180,7 +178,6 @@ void DolphinItemListView::updateGridSize() switch (itemLayout()) { case KFileItemListView::IconsLayout: { - // an exponential factor based on zoom, 0 -> 1, 4 -> 1.36 8 -> ~1.85, 16 -> 3.4 auto zoomFactor = qExp(m_zoomLevel / 13.0); // 9 is the average char width for 10pt Noto Sans, making fontFactor =1 diff --git a/src/views/dolphinitemlistview.h b/src/views/dolphinitemlistview.h index 25476290f6..0483c0644f 100644 --- a/src/views/dolphinitemlistview.h +++ b/src/views/dolphinitemlistview.h @@ -24,17 +24,13 @@ class DOLPHIN_EXPORT DolphinItemListView : public KFileItemListView Q_OBJECT public: - explicit DolphinItemListView(QGraphicsWidget* parent = nullptr); + explicit DolphinItemListView(QGraphicsWidget *parent = nullptr); ~DolphinItemListView() override; void setZoomLevel(int level); int zoomLevel() const; - enum SelectionTogglesEnabled { - True, - False, - FollowSetting - }; + enum SelectionTogglesEnabled { True, False, FollowSetting }; /** * Sets whether the items in this view should show a small selection toggle area on mouse hover. * The default for this view is to follow the "showSelectionToggle" setting but this method can @@ -46,15 +42,14 @@ public: void writeSettings(); protected: - KItemListWidgetCreatorBase* defaultWidgetCreator() const override; + KItemListWidgetCreatorBase *defaultWidgetCreator() const override; /** Overwriting in the Dolphin-specific class because we want this to be user-configurable. * @see KStandardItemListView::itemLayoutHighlightEntireRow */ bool itemLayoutHighlightEntireRow(ItemLayout layout) const override; bool itemLayoutSupportsItemExpanding(ItemLayout layout) const override; void onItemLayoutChanged(ItemLayout current, ItemLayout previous) override; void onPreviewsShownChanged(bool shown) override; - void onVisibleRolesChanged(const QList& current, - const QList& previous) override; + void onVisibleRolesChanged(const QList ¤t, const QList &previous) override; void updateFont() override; diff --git a/src/views/dolphinnewfilemenuobserver.cpp b/src/views/dolphinnewfilemenuobserver.cpp index 1c91282dfb..a1e2fe1d0c 100644 --- a/src/views/dolphinnewfilemenuobserver.cpp +++ b/src/views/dolphinnewfilemenuobserver.cpp @@ -15,37 +15,30 @@ public: }; Q_GLOBAL_STATIC(DolphinNewFileMenuObserverSingleton, s_DolphinNewFileMenuObserver) -DolphinNewFileMenuObserver& DolphinNewFileMenuObserver::instance() +DolphinNewFileMenuObserver &DolphinNewFileMenuObserver::instance() { return s_DolphinNewFileMenuObserver->instance; } -void DolphinNewFileMenuObserver::attach(const DolphinNewFileMenu* menu) +void DolphinNewFileMenuObserver::attach(const DolphinNewFileMenu *menu) { - connect(menu, &DolphinNewFileMenu::fileCreated, - this, &DolphinNewFileMenuObserver::itemCreated); - connect(menu, &DolphinNewFileMenu::directoryCreated, - this, &DolphinNewFileMenuObserver::itemCreated); - connect(menu, &DolphinNewFileMenu::errorMessage, - this, &DolphinNewFileMenuObserver::errorMessage); + connect(menu, &DolphinNewFileMenu::fileCreated, this, &DolphinNewFileMenuObserver::itemCreated); + connect(menu, &DolphinNewFileMenu::directoryCreated, this, &DolphinNewFileMenuObserver::itemCreated); + connect(menu, &DolphinNewFileMenu::errorMessage, this, &DolphinNewFileMenuObserver::errorMessage); } -void DolphinNewFileMenuObserver::detach(const DolphinNewFileMenu* menu) +void DolphinNewFileMenuObserver::detach(const DolphinNewFileMenu *menu) { - disconnect(menu, &DolphinNewFileMenu::fileCreated, - this, &DolphinNewFileMenuObserver::itemCreated); - disconnect(menu, &DolphinNewFileMenu::directoryCreated, - this, &DolphinNewFileMenuObserver::itemCreated); - disconnect(menu, &DolphinNewFileMenu::errorMessage, - this, &DolphinNewFileMenuObserver::errorMessage); + disconnect(menu, &DolphinNewFileMenu::fileCreated, this, &DolphinNewFileMenuObserver::itemCreated); + disconnect(menu, &DolphinNewFileMenu::directoryCreated, this, &DolphinNewFileMenuObserver::itemCreated); + disconnect(menu, &DolphinNewFileMenu::errorMessage, this, &DolphinNewFileMenuObserver::errorMessage); } -DolphinNewFileMenuObserver::DolphinNewFileMenuObserver() : - QObject(nullptr) +DolphinNewFileMenuObserver::DolphinNewFileMenuObserver() + : QObject(nullptr) { } DolphinNewFileMenuObserver::~DolphinNewFileMenuObserver() { } - diff --git a/src/views/dolphinnewfilemenuobserver.h b/src/views/dolphinnewfilemenuobserver.h index 82f09daa26..23bd6a8362 100644 --- a/src/views/dolphinnewfilemenuobserver.h +++ b/src/views/dolphinnewfilemenuobserver.h @@ -25,13 +25,13 @@ class DOLPHIN_EXPORT DolphinNewFileMenuObserver : public QObject Q_OBJECT public: - static DolphinNewFileMenuObserver& instance(); - void attach(const DolphinNewFileMenu* menu); - void detach(const DolphinNewFileMenu* menu); + static DolphinNewFileMenuObserver &instance(); + void attach(const DolphinNewFileMenu *menu); + void detach(const DolphinNewFileMenu *menu); Q_SIGNALS: - void itemCreated(const QUrl& url); - void errorMessage(const QString& error); + void itemCreated(const QUrl &url); + void errorMessage(const QString &error); private: DolphinNewFileMenuObserver(); diff --git a/src/views/dolphinremoteencoding.cpp b/src/views/dolphinremoteencoding.cpp index c7c8b09d1f..04626c1c35 100644 --- a/src/views/dolphinremoteencoding.cpp +++ b/src/views/dolphinremoteencoding.cpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ - /* +/* * This code is largely based on the kremoteencodingplugin * SPDX-FileCopyrightText: 2003 Thiago Macieira * Distributed under the same terms. @@ -12,8 +12,8 @@ #include "dolphinremoteencoding.h" -#include "dolphinviewactionhandler.h" #include "dolphindebug.h" +#include "dolphinviewactionhandler.h" #include #include @@ -27,18 +27,17 @@ #include -#define DATA_KEY QStringLiteral("Charset") +#define DATA_KEY QStringLiteral("Charset") -DolphinRemoteEncoding::DolphinRemoteEncoding(QObject* parent, DolphinViewActionHandler* actionHandler) - :QObject(parent), - m_actionHandler(actionHandler), - m_loaded(false), - m_idDefault(0) +DolphinRemoteEncoding::DolphinRemoteEncoding(QObject *parent, DolphinViewActionHandler *actionHandler) + : QObject(parent) + , m_actionHandler(actionHandler) + , m_loaded(false) + , m_idDefault(0) { m_menu = new KActionMenu(QIcon::fromTheme(QStringLiteral("character-set")), i18n("Select Remote Charset"), this); m_actionHandler->actionCollection()->addAction(QStringLiteral("change_remote_encoding"), m_menu); - connect(m_menu->menu(), &QMenu::aboutToShow, - this, &DolphinRemoteEncoding::slotAboutToShow); + connect(m_menu->menu(), &QMenu::aboutToShow, this, &DolphinRemoteEncoding::slotAboutToShow); m_menu->setEnabled(false); m_menu->setPopupMode(QToolButton::InstantPopup); @@ -69,9 +68,7 @@ void DolphinRemoteEncoding::slotAboutToOpenUrl() if (m_currentURL.scheme() != oldURL.scheme()) { // This plugin works on ftp, fish, etc. // everything whose type is T_FILESYSTEM except for local files - if (!m_currentURL.isLocalFile() && - KProtocolManager::outputType(m_currentURL) == KProtocolInfo::T_FILESYSTEM) { - + if (!m_currentURL.isLocalFile() && KProtocolManager::outputType(m_currentURL) == KProtocolInfo::T_FILESYSTEM) { m_menu->setEnabled(true); loadSettings(); } else { @@ -87,12 +84,12 @@ void DolphinRemoteEncoding::slotAboutToOpenUrl() void DolphinRemoteEncoding::fillMenu() { - QMenu* menu = m_menu->menu(); + QMenu *menu = m_menu->menu(); menu->clear(); menu->addAction(i18n("Default"), this, SLOT(slotDefault()), 0)->setCheckable(true); - for (int i = 0; i < m_encodingDescriptions.size();i++) { - QAction* action = new QAction(m_encodingDescriptions.at(i), this); + for (int i = 0; i < m_encodingDescriptions.size(); i++) { + QAction *action = new QAction(m_encodingDescriptions.at(i), this); action->setCheckable(true); action->setData(i); menu->addAction(action); @@ -112,7 +109,7 @@ void DolphinRemoteEncoding::updateMenu() } // uncheck everything - for (int i = 0; i < m_menu->menu()->actions().count(); i++) { + for (int i = 0; i < m_menu->menu()->actions().count(); i++) { m_menu->menu()->actions().at(i)->setChecked(false); } @@ -131,14 +128,13 @@ void DolphinRemoteEncoding::updateMenu() qCDebug(DolphinDebug) << "URL=" << m_currentURL << " charset=" << charset; if (!isFound) { - qCWarning(DolphinDebug) << "could not find entry for charset=" << charset ; + qCWarning(DolphinDebug) << "could not find entry for charset=" << charset; } else { m_menu->menu()->actions().at(id)->setChecked(true); } } else { m_menu->menu()->actions().at(m_idDefault)->setChecked(true); } - } void DolphinRemoteEncoding::slotAboutToShow() @@ -149,7 +145,7 @@ void DolphinRemoteEncoding::slotAboutToShow() updateMenu(); } -void DolphinRemoteEncoding::slotItemSelected(QAction* action) +void DolphinRemoteEncoding::slotItemSelected(QAction *action) { if (action) { int id = action->data().toInt(); @@ -197,7 +193,7 @@ void DolphinRemoteEncoding::slotDefault() partList.erase(partList.begin()); } - for (QStringList::const_iterator it = domains.constBegin(); it != domains.constEnd();++it) { + for (QStringList::const_iterator it = domains.constBegin(); it != domains.constEnd(); ++it) { qCDebug(DolphinDebug) << "Domain to remove: " << *it; if (config.hasGroup(*it)) { config.deleteGroup(*it); @@ -219,4 +215,3 @@ void DolphinRemoteEncoding::updateView() m_actionHandler->currentView()->setUrl(m_currentURL); m_actionHandler->currentView()->reload(); } - diff --git a/src/views/dolphinremoteencoding.h b/src/views/dolphinremoteencoding.h index ae1d78b6dd..c59de64064 100644 --- a/src/views/dolphinremoteencoding.h +++ b/src/views/dolphinremoteencoding.h @@ -22,35 +22,35 @@ class DolphinViewActionHandler; * When browsing remote url, its possible to change encoding from Tools Menu. */ -class DOLPHIN_EXPORT DolphinRemoteEncoding: public QObject +class DOLPHIN_EXPORT DolphinRemoteEncoding : public QObject { - Q_OBJECT + Q_OBJECT public: - DolphinRemoteEncoding(QObject* parent, DolphinViewActionHandler* actionHandler); - ~DolphinRemoteEncoding() override; + DolphinRemoteEncoding(QObject *parent, DolphinViewActionHandler *actionHandler); + ~DolphinRemoteEncoding() override; public Q_SLOTS: - void slotAboutToOpenUrl(); - void slotItemSelected(QAction* action); - void slotReload(); - void slotDefault(); + void slotAboutToOpenUrl(); + void slotItemSelected(QAction *action); + void slotReload(); + void slotDefault(); private Q_SLOTS: - void slotAboutToShow(); + void slotAboutToShow(); private: - void updateView(); - void loadSettings(); - void fillMenu(); - void updateMenu(); + void updateView(); + void loadSettings(); + void fillMenu(); + void updateMenu(); - KActionMenu* m_menu; - QStringList m_encodingDescriptions; - QUrl m_currentURL; - DolphinViewActionHandler* m_actionHandler; + KActionMenu *m_menu; + QStringList m_encodingDescriptions; + QUrl m_currentURL; + DolphinViewActionHandler *m_actionHandler; - bool m_loaded; - int m_idDefault; + bool m_loaded; + int m_idDefault; }; #endif diff --git a/src/views/dolphinview.cpp b/src/views/dolphinview.cpp index d16aa3b092..35d69e610e 100644 --- a/src/views/dolphinview.cpp +++ b/src/views/dolphinview.cpp @@ -7,8 +7,8 @@ #include "dolphinview.h" -#include "dolphin_generalsettings.h" #include "dolphin_detailsmodesettings.h" +#include "dolphin_generalsettings.h" #include "dolphinitemlistview.h" #include "dolphinnewfilemenuobserver.h" #include "draganddrophelper.h" @@ -19,8 +19,8 @@ #include "kitemviews/kitemlistheader.h" #include "kitemviews/kitemlistselectionmanager.h" #include "kitemviews/private/kitemlistroleeditor.h" -#include "settings/viewmodes/viewmodesettings.h" #include "selectionmode/singleclickselectionproxystyle.h" +#include "settings/viewmodes/viewmodesettings.h" #include "versioncontrol/versioncontrolobserver.h" #include "viewproperties.h" #include "views/tooltips/tooltipmanager.h" @@ -71,33 +71,33 @@ #include #include -DolphinView::DolphinView(const QUrl& url, QWidget* parent) : - QWidget(parent), - m_active(true), - m_tabsForFiles(false), - m_assureVisibleCurrentIndex(false), - m_isFolderWritable(true), - m_dragging(false), - m_url(url), - m_viewPropertiesContext(), - m_mode(DolphinView::IconsView), - m_visibleRoles(), - m_topLayout(nullptr), - m_model(nullptr), - m_view(nullptr), - m_container(nullptr), - m_toolTipManager(nullptr), - m_selectionChangedTimer(nullptr), - m_currentItemUrl(), - m_scrollToCurrentItem(false), - m_restoredContentsPosition(), - m_selectedUrls(), - m_clearSelectionBeforeSelectingNewItems(false), - m_markFirstNewlySelectedItemAsCurrent(false), - m_versionControlObserver(nullptr), - m_twoClicksRenamingTimer(nullptr), - m_placeholderLabel(nullptr), - m_showLoadingPlaceholderTimer(nullptr) +DolphinView::DolphinView(const QUrl &url, QWidget *parent) + : QWidget(parent) + , m_active(true) + , m_tabsForFiles(false) + , m_assureVisibleCurrentIndex(false) + , m_isFolderWritable(true) + , m_dragging(false) + , m_url(url) + , m_viewPropertiesContext() + , m_mode(DolphinView::IconsView) + , m_visibleRoles() + , m_topLayout(nullptr) + , m_model(nullptr) + , m_view(nullptr) + , m_container(nullptr) + , m_toolTipManager(nullptr) + , m_selectionChangedTimer(nullptr) + , m_currentItemUrl() + , m_scrollToCurrentItem(false) + , m_restoredContentsPosition() + , m_selectedUrls() + , m_clearSelectionBeforeSelectingNewItems(false) + , m_markFirstNewlySelectedItemAsCurrent(false) + , m_versionControlObserver(nullptr) + , m_twoClicksRenamingTimer(nullptr) + , m_placeholderLabel(nullptr) + , m_showLoadingPlaceholderTimer(nullptr) { m_topLayout = new QVBoxLayout(this); m_topLayout->setSpacing(0); @@ -106,14 +106,12 @@ DolphinView::DolphinView(const QUrl& url, QWidget* parent) : // When a new item has been created by the "Create New..." menu, the item should // get selected and it must be assured that the item will get visible. As the // creation is done asynchronously, several signals must be checked: - connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated, - this, &DolphinView::observeCreatedItem); + connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated, this, &DolphinView::observeCreatedItem); m_selectionChangedTimer = new QTimer(this); m_selectionChangedTimer->setSingleShot(true); m_selectionChangedTimer->setInterval(300); - connect(m_selectionChangedTimer, &QTimer::timeout, - this, &DolphinView::emitSelectionChangedSignal); + connect(m_selectionChangedTimer, &QTimer::timeout, this, &DolphinView::emitSelectionChangedSignal); m_model = new KFileItemModel(this); m_view = new DolphinItemListView(); @@ -121,7 +119,7 @@ DolphinView::DolphinView(const QUrl& url, QWidget* parent) : m_view->setVisibleRoles({"text"}); applyModeToView(); - KItemListController* controller = new KItemListController(m_model, m_view, this); + KItemListController *controller = new KItemListController(m_model, m_view, this); const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1; controller->setAutoActivationDelay(delay); @@ -132,8 +130,12 @@ DolphinView::DolphinView(const QUrl& url, QWidget* parent) : m_container = new KItemListContainer(controller, this); m_container->installEventFilter(this); setFocusProxy(m_container); - connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, [=] { hideToolTip(); }); - connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] { hideToolTip(); }); + connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, [=] { + hideToolTip(); + }); + connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] { + hideToolTip(); + }); m_showLoadingPlaceholderTimer = new QTimer(this); m_showLoadingPlaceholderTimer->setInterval(500); @@ -162,7 +164,7 @@ DolphinView::DolphinView(const QUrl& url, QWidget* parent) : centeringLayout->addWidget(m_placeholderLabel); centeringLayout->setAlignment(m_placeholderLabel, Qt::AlignCenter); m_placeholderLabel->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_placeholderLabel, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){ + connect(m_placeholderLabel, &QWidget::customContextMenuRequested, this, [this](const QPoint &pos) { slotViewContextMenuRequested(m_placeholderLabel->mapToGlobal(pos)); }); @@ -185,42 +187,33 @@ DolphinView::DolphinView(const QUrl& url, QWidget* parent) : connect(controller, &KItemListController::swipeUp, this, &DolphinView::slotSwipeUp); connect(controller, &KItemListController::selectionModeChangeRequested, this, &DolphinView::selectionModeChangeRequested); - connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted); - connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); - connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::slotDirectoryLoadingCanceled); - connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress); - connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress); - connect(m_model, &KFileItemModel::itemsChanged, - this, &DolphinView::slotItemsChanged); - connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged); - connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged); - connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage); - connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage); + connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted); + connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); + connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::slotDirectoryLoadingCanceled); + connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress); + connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress); + connect(m_model, &KFileItemModel::itemsChanged, this, &DolphinView::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged); + connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged); + connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage); + connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage); connect(m_model, &KFileItemModel::directoryRedirection, this, &DolphinView::slotDirectoryRedirection); - connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError); - connect(m_model, &KFileItemModel::fileItemsChanged, this, &DolphinView::fileItemsChanged); + connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError); + connect(m_model, &KFileItemModel::fileItemsChanged, this, &DolphinView::fileItemsChanged); connect(m_model, &KFileItemModel::currentDirectoryRemoved, this, &DolphinView::currentDirectoryRemoved); - connect(this, &DolphinView::itemCountChanged, - this, &DolphinView::updatePlaceholderLabel); + connect(this, &DolphinView::itemCountChanged, this, &DolphinView::updatePlaceholderLabel); m_view->installEventFilter(this); - connect(m_view, &DolphinItemListView::sortOrderChanged, - this, &DolphinView::slotSortOrderChangedByHeader); - connect(m_view, &DolphinItemListView::sortRoleChanged, - this, &DolphinView::slotSortRoleChangedByHeader); - connect(m_view, &DolphinItemListView::visibleRolesChanged, - this, &DolphinView::slotVisibleRolesChangedByHeader); - connect(m_view, &DolphinItemListView::roleEditingCanceled, - this, &DolphinView::slotRoleEditingCanceled); - connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished, - this, &DolphinView::slotHeaderColumnWidthChangeFinished); - connect(m_view->header(), &KItemListHeader::sidePaddingChanged, - this, &DolphinView::slotSidePaddingWidthChanged); + connect(m_view, &DolphinItemListView::sortOrderChanged, this, &DolphinView::slotSortOrderChangedByHeader); + connect(m_view, &DolphinItemListView::sortRoleChanged, this, &DolphinView::slotSortRoleChangedByHeader); + connect(m_view, &DolphinItemListView::visibleRolesChanged, this, &DolphinView::slotVisibleRolesChangedByHeader); + connect(m_view, &DolphinItemListView::roleEditingCanceled, this, &DolphinView::slotRoleEditingCanceled); + connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished, this, &DolphinView::slotHeaderColumnWidthChangeFinished); + connect(m_view->header(), &KItemListHeader::sidePaddingChanged, this, &DolphinView::slotSidePaddingWidthChanged); - KItemListSelectionManager* selectionManager = controller->selectionManager(); - connect(selectionManager, &KItemListSelectionManager::selectionChanged, - this, &DolphinView::slotSelectionChanged); + KItemListSelectionManager *selectionManager = controller->selectionManager(); + connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &DolphinView::slotSelectionChanged); #if HAVE_BALOO m_toolTipManager = new ToolTipManager(this); @@ -401,7 +394,7 @@ int DolphinView::itemsCount() const KFileItemList DolphinView::selectedItems() const { - const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); KFileItemList selectedItems; const auto items = selectionManager->selectedItems(); @@ -414,11 +407,11 @@ KFileItemList DolphinView::selectedItems() const int DolphinView::selectedItemsCount() const { - const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); return selectionManager->selectedItems().count(); } -void DolphinView::markUrlsAsSelected(const QList& urls) +void DolphinView::markUrlsAsSelected(const QList &urls) { m_selectedUrls = urls; } @@ -431,10 +424,8 @@ void DolphinView::markUrlAsCurrent(const QUrl &url) void DolphinView::selectItems(const QRegularExpression ®exp, bool enabled) { - const KItemListSelectionManager::SelectionMode mode = enabled - ? KItemListSelectionManager::Select - : KItemListSelectionManager::Deselect; - KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const KItemListSelectionManager::SelectionMode mode = enabled ? KItemListSelectionManager::Select : KItemListSelectionManager::Deselect; + KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); for (int index = 0; index < m_model->count(); index++) { const KFileItem item = m_model->fileItem(index); @@ -463,7 +454,7 @@ int DolphinView::zoomLevel() const return m_view->zoomLevel(); } -void DolphinView::setSortRole(const QByteArray& role) +void DolphinView::setSortRole(const QByteArray &role) { if (role != sortRole()) { updateSortRole(role); @@ -472,7 +463,7 @@ void DolphinView::setSortRole(const QByteArray& role) QByteArray DolphinView::sortRole() const { - const KItemModelBase* model = m_container->controller()->model(); + const KItemModelBase *model = m_container->controller()->model(); return model->sortRole(); } @@ -512,7 +503,7 @@ bool DolphinView::sortHiddenLast() const return m_model->sortHiddenLast(); } -void DolphinView::setVisibleRoles(const QList& roles) +void DolphinView::setVisibleRoles(const QList &roles) { const QList previousRoles = roles; @@ -566,7 +557,7 @@ void DolphinView::writeSettings() m_view->writeSettings(); } -void DolphinView::setNameFilter(const QString& nameFilter) +void DolphinView::setNameFilter(const QString &nameFilter) { m_model->setNameFilter(nameFilter); } @@ -576,7 +567,7 @@ QString DolphinView::nameFilter() const return m_model->nameFilter(); } -void DolphinView::setMimeTypeFilters(const QStringList& filters) +void DolphinView::setMimeTypeFilters(const QStringList &filters) { return m_model->setMimeTypeFilters(filters); } @@ -600,7 +591,7 @@ void DolphinView::requestStatusBarText() // Give a summary of the status of the selected files const KFileItemList list = selectedItems(); - for (const KFileItem& item : list) { + for (const KFileItem &item : list) { if (item.isDir()) { ++folderCount; } else { @@ -621,16 +612,13 @@ void DolphinView::requestStatusBarText() return; } - m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(), - KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo); - connect(m_statJobForStatusBarText, &KJob::result, - this, &DolphinView::slotStatJobResult); + m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(), KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo); + connect(m_statJobForStatusBarText, &KJob::result, this, &DolphinView::slotStatJobResult); m_statJobForStatusBarText->start(); } } -void DolphinView::emitStatusBarText(const int folderCount, const int fileCount, - KIO::filesize_t totalFileSize, const Selection selection) +void DolphinView::emitStatusBarText(const int folderCount, const int fileCount, KIO::filesize_t totalFileSize, const Selection selection) { QString foldersText; QString filesText; @@ -647,13 +635,9 @@ void DolphinView::emitStatusBarText(const int folderCount, const int fileCount, } if (fileCount > 0 && folderCount > 0) { - summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)", - foldersText, filesText, - KFormat().formatByteSize(totalFileSize)); + summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)", foldersText, filesText, KFormat().formatByteSize(totalFileSize)); } else if (fileCount > 0) { - summary = i18nc("@info:status files (size)", "%1 (%2)", - filesText, - KFormat().formatByteSize(totalFileSize)); + summary = i18nc("@info:status files (size)", "%1 (%2)", filesText, KFormat().formatByteSize(totalFileSize)); } else if (folderCount > 0) { summary = foldersText; } else { @@ -662,9 +646,9 @@ void DolphinView::emitStatusBarText(const int folderCount, const int fileCount, Q_EMIT statusBarTextChanged(summary); } -QList DolphinView::versionControlActions(const KFileItemList& items) const +QList DolphinView::versionControlActions(const KFileItemList &items) const { - QList actions; + QList actions; if (items.isEmpty()) { const KFileItem item = m_model->rootItem(); @@ -678,7 +662,7 @@ QList DolphinView::versionControlActions(const KFileItemList& items) c return actions; } -void DolphinView::setUrl(const QUrl& url) +void DolphinView::setUrl(const QUrl &url) { if (url == m_url) { return; @@ -690,8 +674,7 @@ void DolphinView::setUrl(const QUrl& url) hideToolTip(); - disconnect(m_view, &DolphinItemListView::roleEditingFinished, - this, &DolphinView::slotRoleEditingFinished); + disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished); // It is important to clear the items from the model before // applying the view properties, otherwise expensive operations @@ -706,13 +689,13 @@ void DolphinView::setUrl(const QUrl& url) void DolphinView::selectAll() { - KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); selectionManager->setSelected(0, m_model->count()); } void DolphinView::invertSelection() { - KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle); } @@ -732,8 +715,8 @@ void DolphinView::renameSelectedItems() if (items.count() == 1 && GeneralSettings::renameInline()) { const int index = m_model->index(items.first()); - QMetaObject::Connection * const connection = new QMetaObject::Connection; - *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=](){ + QMetaObject::Connection *const connection = new QMetaObject::Connection; + *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=]() { QObject::disconnect(*connection); delete connection; @@ -741,15 +724,13 @@ void DolphinView::renameSelectedItems() hideToolTip(); - connect(m_view, &DolphinItemListView::roleEditingFinished, - this, &DolphinView::slotRoleEditingFinished); + connect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished); }); m_view->scrollToItem(index); } else { - KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(items, this); - connect(dialog, &KIO::RenameFileDialog::renamingFinished, - this, &DolphinView::slotRenameDialogRenamingFinished); + KIO::RenameFileDialog *dialog = new KIO::RenameFileDialog(items, this); + connect(dialog, &KIO::RenameFileDialog::renamingFinished, this, &DolphinView::slotRenameDialogRenamingFinished); dialog->open(); } @@ -773,11 +754,10 @@ void DolphinView::trashSelectedItems() KIO::JobUiDelegate uiDelegate; uiDelegate.setWindow(window()); if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) { - KIO::Job* job = KIO::trash(list); + KIO::Job *job = KIO::trash(list); KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job); KJobWidgets::setWindow(job, this); - connect(job, &KIO::Job::result, - this, &DolphinView::slotTrashFileFinished); + connect(job, &KIO::Job::result, this, &DolphinView::slotTrashFileFinished); } #endif } @@ -795,17 +775,16 @@ void DolphinView::deleteSelectedItems() KIO::JobUiDelegate uiDelegate; uiDelegate.setWindow(window()); if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) { - KIO::Job* job = KIO::del(list); + KIO::Job *job = KIO::del(list); KJobWidgets::setWindow(job, this); - connect(job, &KIO::Job::result, - this, &DolphinView::slotDeleteFileFinished); + connect(job, &KIO::Job::result, this, &DolphinView::slotDeleteFileFinished); } #endif } void DolphinView::cutSelectedItemsToClipboard() { - QMimeData* mimeData = selectionMimeData(); + QMimeData *mimeData = selectionMimeData(); KIO::setClipboardDataCut(mimeData, true); KUrlMimeData::exportUrlsToPortal(mimeData); QApplication::clipboard()->setMimeData(mimeData); @@ -820,7 +799,7 @@ void DolphinView::copySelectedItemsToClipboard() void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl) { - KIO::CopyJob* job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags); + KIO::CopyJob *job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags); KJobWidgets::setWindow(job, this); connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult); @@ -830,13 +809,12 @@ void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl & void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl) { - KIO::CopyJob* job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags); + KIO::CopyJob *job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags); KJobWidgets::setWindow(job, this); connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult); connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone); KIO::FileUndoManager::self()->recordCopyJob(job); - } void DolphinView::paste() @@ -865,7 +843,7 @@ void DolphinView::duplicateSelectedItems() // but before the filename extension, if present QList newSelection; for (const auto &item : itemList) { - const QUrl originalURL = item.url(); + const QUrl originalURL = item.url(); const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path(); const QString originalFileName = item.name(); @@ -876,7 +854,7 @@ void DolphinView::duplicateSelectedItems() // No extension; new filename is " copy" if (extension.isEmpty()) { duplicateURL.setPath(originalDirectoryPath + i18nc(" copy", "%1 copy", originalFileName)); - // There's an extension; new filename is " copy." + // There's an extension; new filename is " copy." } else { // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it extension = QLatin1String(".") + extension; @@ -887,7 +865,7 @@ void DolphinView::duplicateSelectedItems() duplicateURL.setPath(originalDirectoryPath + i18nc(" copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension); } - KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL); + KIO::CopyJob *job = KIO::copyAs(originalURL, duplicateURL); KJobWidgets::setWindow(job, this); if (job) { @@ -911,7 +889,7 @@ void DolphinView::updatePalette() color.setAlpha(150); } - QWidget* viewport = m_container->viewport(); + QWidget *viewport = m_container->viewport(); if (viewport) { QPalette palette; palette.setColor(viewport->backgroundRole(), color); @@ -927,7 +905,7 @@ void DolphinView::abortTwoClicksRenaming() m_twoClicksRenamingTimer->stop(); } -bool DolphinView::eventFilter(QObject* watched, QEvent* event) +bool DolphinView::eventFilter(QObject *watched, QEvent *event) { switch (event->type()) { case QEvent::PaletteChange: @@ -943,7 +921,7 @@ bool DolphinView::eventFilter(QObject* watched, QEvent* event) case QEvent::KeyPress: hideToolTip(ToolTipManager::HideBehavior::Instantly); if (GeneralSettings::useTabForSwitchingSplitView()) { - QKeyEvent* keyEvent = static_cast(event); + QKeyEvent *keyEvent = static_cast(event); if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) { Q_EMIT toggleActiveViewRequested(); return true; @@ -976,7 +954,7 @@ bool DolphinView::eventFilter(QObject* watched, QEvent* event) break; case QEvent::ToolTip: - tryShowNameToolTip(static_cast(event)); + tryShowNameToolTip(static_cast(event)); default: break; @@ -985,7 +963,7 @@ bool DolphinView::eventFilter(QObject* watched, QEvent* event) return QWidget::eventFilter(watched, event); } -void DolphinView::wheelEvent(QWheelEvent* event) +void DolphinView::wheelEvent(QWheelEvent *event) { if (event->modifiers().testFlag(Qt::ControlModifier)) { const QPoint numDegrees = event->angleDelta() / 8; @@ -998,13 +976,13 @@ void DolphinView::wheelEvent(QWheelEvent* event) } } -void DolphinView::hideEvent(QHideEvent* event) +void DolphinView::hideEvent(QHideEvent *event) { hideToolTip(); QWidget::hideEvent(event); } -bool DolphinView::event(QEvent* event) +bool DolphinView::event(QEvent *event) { if (event->type() == QEvent::WindowDeactivate) { /* See Bug 297355 @@ -1045,13 +1023,18 @@ void DolphinView::slotItemsActivated(const KItemSet &indexes) if (indexes.count() > 5) { QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count()); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - const int answer = KMessageBox::warningTwoActions(this, question, {}, + const int answer = KMessageBox::warningTwoActions( + this, + question, + {}, #else - const int answer = KMessageBox::warningYesNo(this, question, {}, + const int answer = + KMessageBox::warningYesNo(this, + question, + {}, #endif - KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes.count()), - QStringLiteral("document-open")), - KStandardGuiItem::cancel()); + KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes.count()), QStringLiteral("document-open")), + KStandardGuiItem::cancel()); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) if (answer != KMessageBox::PrimaryAction) { #else @@ -1066,7 +1049,7 @@ void DolphinView::slotItemsActivated(const KItemSet &indexes) for (int index : indexes) { KFileItem item = m_model->fileItem(index); - const QUrl& url = openItemAsFolderUrl(item); + const QUrl &url = openItemAsFolderUrl(item); if (!url.isEmpty()) { // Open folders in new tabs or in new windows depending on the modifier @@ -1091,8 +1074,8 @@ void DolphinView::slotItemsActivated(const KItemSet &indexes) void DolphinView::slotItemMiddleClicked(int index) { - const KFileItem& item = m_model->fileItem(index); - const QUrl& url = openItemAsFolderUrl(item); + const KFileItem &item = m_model->fileItem(index); + const QUrl &url = openItemAsFolderUrl(item); const auto modifiers = QGuiApplication::keyboardModifiers(); if (!url.isEmpty()) { // keep in sync with KUrlNavigator::slotNavigatorButtonClicked @@ -1111,7 +1094,7 @@ void DolphinView::slotItemMiddleClicked(int index) } } -void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos) +void DolphinView::slotItemContextMenuRequested(int index, const QPointF &pos) { // Force emit of a selection changed signal before we request the // context menu, to update the edit-actions first. (See Bug 294013) @@ -1123,18 +1106,18 @@ void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos) Q_EMIT requestContextMenu(pos.toPoint(), item, selectedItems(), url()); } -void DolphinView::slotViewContextMenuRequested(const QPointF& pos) +void DolphinView::slotViewContextMenuRequested(const QPointF &pos) { Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), selectedItems(), url()); } -void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) +void DolphinView::slotHeaderContextMenuRequested(const QPointF &pos) { ViewProperties props(viewPropertiesUrl()); QPointer menu = new QMenu(QApplication::activeWindow()); - KItemListView* view = m_container->controller()->view(); + KItemListView *view = m_container->controller()->view(); const QList visibleRolesSet = view->visibleRoles(); bool indexingEnabled = false; @@ -1144,18 +1127,18 @@ void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) #endif QString groupName; - QMenu* groupMenu = nullptr; + QMenu *groupMenu = nullptr; // Add all roles to the menu that can be shown or hidden by the user const QList rolesInfo = KFileItemModel::rolesInformation(); - for (const KFileItemModel::RoleInfo& info : rolesInfo) { + for (const KFileItemModel::RoleInfo &info : rolesInfo) { if (info.role == "text") { // It should not be possible to hide the "text" role continue; } const QString text = m_model->roleDescription(info.role); - QAction* action = nullptr; + QAction *action = nullptr; if (info.group.isEmpty()) { action = menu->addAction(text); } else { @@ -1171,34 +1154,32 @@ void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) action->setChecked(visibleRolesSet.contains(info.role)); action->setData(info.role); - const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || - (info.requiresBaloo) || - (info.requiresIndexer && indexingEnabled); + const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled); action->setEnabled(enable); } menu->addSeparator(); - QActionGroup* widthsGroup = new QActionGroup(menu); + QActionGroup *widthsGroup = new QActionGroup(menu); const bool autoColumnWidths = props.headerColumnWidths().isEmpty(); - QAction* toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding")); + QAction *toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding")); toggleSidePaddingAction->setCheckable(true); toggleSidePaddingAction->setChecked(view->header()->sidePadding() > 0); - QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths")); + QAction *autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths")); autoAdjustWidthsAction->setCheckable(true); autoAdjustWidthsAction->setChecked(autoColumnWidths); autoAdjustWidthsAction->setActionGroup(widthsGroup); - QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths")); + QAction *customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths")); customWidthsAction->setCheckable(true); customWidthsAction->setChecked(!autoColumnWidths); customWidthsAction->setActionGroup(widthsGroup); - QAction* action = menu->exec(pos.toPoint()); + QAction *action = menu->exec(pos.toPoint()); if (menu && action) { - KItemListHeader* header = view->header(); + KItemListHeader *header = view->header(); if (action == autoAdjustWidthsAction) { // Clear the column-widths from the viewproperties and turn on @@ -1211,7 +1192,7 @@ void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) QList columnWidths; const auto visibleRoles = view->visibleRoles(); columnWidths.reserve(visibleRoles.count()); - for (const QByteArray& role : visibleRoles) { + for (const QByteArray &role : visibleRoles) { columnWidths.append(header->columnWidth(role)); } props.setHeaderColumnWidths(columnWidths); @@ -1236,7 +1217,7 @@ void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) if (!header->automaticColumnResizing()) { const auto visibleRoles = view->visibleRoles(); columnWidths.reserve(visibleRoles.count()); - for (const QByteArray& role : visibleRoles) { + for (const QByteArray &role : visibleRoles) { columnWidths.append(header->columnWidth(role)); } } @@ -1247,7 +1228,7 @@ void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) delete menu; } -void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current) +void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray &role, qreal current) { const QList visibleRoles = m_view->visibleRoles(); @@ -1256,8 +1237,8 @@ void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qr if (columnWidths.count() != visibleRoles.count()) { columnWidths.clear(); columnWidths.reserve(visibleRoles.count()); - const KItemListHeader* header = m_view->header(); - for (const QByteArray& role : visibleRoles) { + const KItemListHeader *header = m_view->header(); + for (const QByteArray &role : visibleRoles) { const int width = header->columnWidth(role); columnWidths.append(width); } @@ -1304,7 +1285,7 @@ void DolphinView::slotItemUnhovered(int index) Q_EMIT requestItemInfo(KFileItem()); } -void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event) +void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event) { QUrl destUrl; KFileItem destItem = m_model->fileItem(index); @@ -1318,11 +1299,7 @@ void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* even destUrl = destItem.mostLocalUrl(); } - QDropEvent dropEvent(event->pos().toPoint(), - event->possibleActions(), - event->mimeData(), - event->buttons(), - event->modifiers()); + QDropEvent dropEvent(event->pos().toPoint(), event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers()); dropUrls(destUrl, &dropEvent, this); setActive(true); @@ -1330,7 +1307,7 @@ void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* even void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget) { - KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget); + KIO::DropJob *job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget); if (job) { connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult); @@ -1344,18 +1321,18 @@ void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget * } } -void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous) +void DolphinView::slotModelChanged(KItemModelBase *current, KItemModelBase *previous) { if (previous != nullptr) { - Q_ASSERT(qobject_cast(previous)); - KFileItemModel* fileItemModel = static_cast(previous); + Q_ASSERT(qobject_cast(previous)); + KFileItemModel *fileItemModel = static_cast(previous); disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); m_versionControlObserver->setModel(nullptr); } if (current) { - Q_ASSERT(qobject_cast(current)); - KFileItemModel* fileItemModel = static_cast(current); + Q_ASSERT(qobject_cast(current)); + KFileItemModel *fileItemModel = static_cast(current); connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); m_versionControlObserver->setModel(fileItemModel); } @@ -1391,7 +1368,7 @@ void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to) slotItemCreated(to); } -void DolphinView::slotItemCreated(const QUrl& url) +void DolphinView::slotItemCreated(const QUrl &url) { if (m_markFirstNewlySelectedItemAsCurrent) { markUrlAsCurrent(url); @@ -1410,12 +1387,11 @@ void DolphinView::slotJobResult(KJob *job) } } -void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous) +void DolphinView::slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous) { const int currentCount = current.count(); const int previousCount = previous.count(); - const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || - (currentCount > 0 && previousCount == 0); + const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || (currentCount > 0 && previousCount == 0); // If nothing has been selected before and something got selected (or if something // was selected before and now nothing is selected) the selectionChangedSignal must @@ -1437,11 +1413,10 @@ void DolphinView::slotStatJobResult(KJob *job) KIO::filesize_t totalFileSize = 0; bool countFileSize = true; - const auto entry = static_cast(job)->statResult(); + const auto entry = static_cast(job)->statResult(); if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) { // We have a precomputed value. - totalFileSize = static_cast( - entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE)); + totalFileSize = static_cast(entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE)); countFileSize = false; } @@ -1460,12 +1435,12 @@ void DolphinView::slotStatJobResult(KJob *job) emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection); } -void DolphinView::updateSortRole(const QByteArray& role) +void DolphinView::updateSortRole(const QByteArray &role) { ViewProperties props(viewPropertiesUrl()); props.setSortRole(role); - KItemModelBase* model = m_container->controller()->model(); + KItemModelBase *model = m_container->controller()->model(); model->setSortRole(role); Q_EMIT sortRoleChanged(role); @@ -1501,7 +1476,6 @@ void DolphinView::updateSortHiddenLast(bool hiddenLast) Q_EMIT sortHiddenLastChanged(hiddenLast); } - QPair DolphinView::pasteInfo() const { const QMimeData *mimeData = QApplication::clipboard()->mimeData(); @@ -1525,7 +1499,7 @@ bool DolphinView::itemsExpandable() const return m_mode == DetailsView; } -bool DolphinView::isExpanded(const KFileItem& item) const +bool DolphinView::isExpanded(const KFileItem &item) const { Q_ASSERT(item.isDir()); Q_ASSERT(items().contains(item)); @@ -1535,7 +1509,7 @@ bool DolphinView::isExpanded(const KFileItem& item) const return m_model->isExpanded(m_model->index(item)); } -void DolphinView::restoreState(QDataStream& stream) +void DolphinView::restoreState(QDataStream &stream) { // Read the version number of the view state and check if the version is supported. quint32 version = 0; @@ -1560,7 +1534,7 @@ void DolphinView::restoreState(QDataStream& stream) m_model->restoreExpandedDirectories(urls); } -void DolphinView::saveState(QDataStream& stream) +void DolphinView::saveState(QDataStream &stream) { stream << quint32(1); // View state version @@ -1592,7 +1566,7 @@ KFileItem DolphinView::rootItem() const return m_model->rootItem(); } -void DolphinView::setViewPropertiesContext(const QString& context) +void DolphinView::setViewPropertiesContext(const QString &context) { m_viewPropertiesContext = context; } @@ -1602,7 +1576,7 @@ QString DolphinView::viewPropertiesContext() const return m_viewPropertiesContext; } -QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives) +QUrl DolphinView::openItemAsFolderUrl(const KFileItem &item, const bool browseThroughArchives) { if (item.isNull()) { return QUrl(); @@ -1615,7 +1589,7 @@ QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseTh } if (item.isMimeTypeKnown()) { - const QString& mimetype = item.mimetype(); + const QString &mimetype = item.mimetype(); if (browseThroughArchives && item.isFile() && url.isLocalFile()) { // Generic mechanism for redirecting to tar:// when clicking on a tar file, @@ -1623,7 +1597,7 @@ QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseTh // The .protocol file specifies the mimetype that the kioslave handles. // Note that we don't use mimetype inheritance since we don't want to // open OpenDocument files as zip folders... - const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype); + const QString &protocol = KProtocolManager::protocolForArchiveMimetype(mimetype); if (!protocol.isEmpty()) { url.setScheme(protocol); return url; @@ -1655,14 +1629,14 @@ void DolphinView::resetZoomLevel() setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize))); } -void DolphinView::observeCreatedItem(const QUrl& url) +void DolphinView::observeCreatedItem(const QUrl &url) { if (m_active) { forceUrlsSelection(url, {url}); } } -void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl) +void DolphinView::slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl) { if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) { Q_EMIT redirection(oldUrl, newUrl); @@ -1673,7 +1647,7 @@ void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUr void DolphinView::updateViewState() { if (m_currentItemUrl != QUrl()) { - KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); // if there is a selection already, leave it that way if (!selectionManager->hasSelection()) { @@ -1705,7 +1679,7 @@ void DolphinView::updateViewState() } if (!m_selectedUrls.isEmpty()) { - KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); // if there is a selection already, leave it that way if (!selectionManager->hasSelection()) { @@ -1744,13 +1718,13 @@ void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior) Q_UNUSED(behavior) #endif } else if (m_mode == DolphinView::IconsView) { - QToolTip::hideText(); + QToolTip::hideText(); } } void DolphinView::slotTwoClicksRenamingTimerTimeout() { - const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); // verify that only one item is selected if (selectionManager->selectedItems().count() == 1) { @@ -1764,7 +1738,7 @@ void DolphinView::slotTwoClicksRenamingTimerTimeout() } } -void DolphinView::slotTrashFileFinished(KJob* job) +void DolphinView::slotTrashFileFinished(KJob *job) { if (job->error() == 0) { Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed.")); @@ -1773,7 +1747,7 @@ void DolphinView::slotTrashFileFinished(KJob* job) } } -void DolphinView::slotDeleteFileFinished(KJob* job) +void DolphinView::slotDeleteFileFinished(KJob *job) { if (job->error() == 0) { Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed.")); @@ -1782,7 +1756,7 @@ void DolphinView::slotDeleteFileFinished(KJob* job) } } -void DolphinView::slotRenamingResult(KJob* job) +void DolphinView::slotRenamingResult(KJob *job) { if (job->error()) { KIO::CopyJob *copyJob = qobject_cast(job); @@ -1855,7 +1829,7 @@ void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOr Q_EMIT sortOrderChanged(current); } -void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous) +void DolphinView::slotSortRoleChangedByHeader(const QByteArray ¤t, const QByteArray &previous) { Q_UNUSED(previous) Q_ASSERT(m_model->sortRole() == current); @@ -1866,8 +1840,7 @@ void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const Q Q_EMIT sortRoleChanged(current); } -void DolphinView::slotVisibleRolesChangedByHeader(const QList& current, - const QList& previous) +void DolphinView::slotVisibleRolesChangedByHeader(const QList ¤t, const QList &previous) { Q_UNUSED(previous) Q_ASSERT(m_container->controller()->view()->visibleRoles() == current); @@ -1884,14 +1857,12 @@ void DolphinView::slotVisibleRolesChangedByHeader(const QList& curre void DolphinView::slotRoleEditingCanceled() { - disconnect(m_view, &DolphinItemListView::roleEditingFinished, - this, &DolphinView::slotRoleEditingFinished); + disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished); } -void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value) +void DolphinView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value) { - disconnect(m_view, &DolphinItemListView::roleEditingFinished, - this, &DolphinView::slotRoleEditingFinished); + disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished); const KFileItemList items = selectedItems(); if (items.count() != 1) { @@ -1914,26 +1885,27 @@ void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, con KGuiItem yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden")); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) - const auto code = KMessageBox::questionTwoActions(this, + const auto code = + KMessageBox::questionTwoActions(this, #else - const auto code = KMessageBox::questionYesNo(this, + const auto code = + KMessageBox::questionYesNo(this, #endif - oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n" - "Do you still want to rename it?") - : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n" - "Do you still want to rename it?"), - oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"), - yesGuiItem, - KStandardGuiItem::cancel(), - QStringLiteral("ConfirmHide") - ); + oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n" + "Do you still want to rename it?") + : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n" + "Do you still want to rename it?"), + oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"), + yesGuiItem, + KStandardGuiItem::cancel(), + QStringLiteral("ConfirmHide")); #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0) if (code == KMessageBox::SecondaryAction) { #else if (code == KMessageBox::No) { #endif - return; + return; } } #endif @@ -1950,7 +1922,7 @@ void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, con m_model->setData(index, data); } - KIO::Job * job = KIO::moveAs(oldUrl, newUrl); + KIO::Job *job = KIO::moveAs(oldUrl, newUrl); KJobWidgets::setWindow(job, this); KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job); job->uiDelegate()->setAutoErrorHandlingEnabled(true); @@ -1966,14 +1938,13 @@ void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, con if (retVal.direction != EditDone) { const short indexShift = retVal.direction == EditNext ? 1 : -1; m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect); - m_container->controller()->selectionManager()->setSelected(index + indexShift, 1, - KItemListSelectionManager::Select); + m_container->controller()->selectionManager()->setSelected(index + indexShift, 1, KItemListSelectionManager::Select); renameSelectedItems(); } } } -void DolphinView::loadDirectory(const QUrl& url, bool reload) +void DolphinView::loadDirectory(const QUrl &url, bool reload) { if (!url.isValid()) { const QString location(url.toDisplayString(QUrl::PreferLocalFile)); @@ -1998,7 +1969,7 @@ void DolphinView::applyViewProperties() applyViewProperties(props); } -void DolphinView::applyViewProperties(const ViewProperties& props) +void DolphinView::applyViewProperties(const ViewProperties &props) { m_view->beginTransaction(); @@ -2077,9 +2048,9 @@ void DolphinView::applyViewProperties(const ViewProperties& props) } } - KItemListView* itemListView = m_container->controller()->view(); + KItemListView *itemListView = m_container->controller()->view(); if (itemListView->isHeaderVisible()) { - KItemListHeader* header = itemListView->header(); + KItemListHeader *header = itemListView->header(); const QList headerColumnWidths = props.headerColumnWidths(); const int rolesCount = m_visibleRoles.count(); if (headerColumnWidths.count() == rolesCount) { @@ -2102,14 +2073,22 @@ void DolphinView::applyViewProperties(const ViewProperties& props) void DolphinView::applyModeToView() { switch (m_mode) { - case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break; - case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break; - case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break; - default: Q_ASSERT(false); break; + case IconsView: + m_view->setItemLayout(KFileItemListView::IconsLayout); + break; + case CompactView: + m_view->setItemLayout(KFileItemListView::CompactLayout); + break; + case DetailsView: + m_view->setItemLayout(KFileItemListView::DetailsLayout); + break; + default: + Q_ASSERT(false); + break; } } -void DolphinView::pasteToUrl(const QUrl& url) +void DolphinView::pasteToUrl(const QUrl &url) { KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url); KJobWidgets::setWindow(job, this); @@ -2125,7 +2104,7 @@ QList DolphinView::simplifiedSelectedUrls() const const KFileItemList items = selectedItems(); urls.reserve(items.count()); - for (const KFileItem& item : items) { + for (const KFileItem &item : items) { urls.append(item.url()); } @@ -2137,9 +2116,9 @@ QList DolphinView::simplifiedSelectedUrls() const return urls; } -QMimeData* DolphinView::selectionMimeData() const +QMimeData *DolphinView::selectionMimeData() const { - const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager(); const KItemSet selectedIndexes = selectionManager->selectedItems(); return m_model->createMimeData(selectedIndexes); @@ -2178,12 +2157,12 @@ QUrl DolphinView::viewPropertiesUrl() const return url; } -void DolphinView::slotRenameDialogRenamingFinished(const QList& urls) +void DolphinView::slotRenameDialogRenamingFinished(const QList &urls) { forceUrlsSelection(urls.first(), urls); } -void DolphinView::forceUrlsSelection(const QUrl& current, const QList& selected) +void DolphinView::forceUrlsSelection(const QUrl ¤t, const QList &selected) { clearSelection(); m_clearSelectionBeforeSelectingNewItems = true; @@ -2197,12 +2176,12 @@ void DolphinView::copyPathToClipboard() if (list.isEmpty()) { return; } - const KFileItem& item = list.at(0); + const KFileItem &item = list.at(0); QString path = item.localPath(); if (path.isEmpty()) { path = item.url().toDisplayString(); } - QClipboard* clipboard = QApplication::clipboard(); + QClipboard *clipboard = QApplication::clipboard(); if (clipboard == nullptr) { return; } @@ -2279,7 +2258,7 @@ void DolphinView::updatePlaceholderLabel() m_placeholderLabel->setVisible(true); } -void DolphinView::tryShowNameToolTip(QHelpEvent* event) +void DolphinView::tryShowNameToolTip(QHelpEvent *event) { if (!GeneralSettings::showToolTips() && m_mode == DolphinView::IconsView) { const std::optional index = m_view->itemAt(event->pos()); @@ -2291,7 +2270,7 @@ void DolphinView::tryShowNameToolTip(QHelpEvent* event) // Check whether the filename has been elided const bool isElided = m_view->isElided(index.value()); - if(isElided) { + if (isElided) { const KFileItem item = m_model->fileItem(index.value()); const QString text = item.text(); const QPoint pos = mapToGlobal(event->pos()); diff --git a/src/views/dolphinview.h b/src/views/dolphinview.h index 50b1b92704..8cf23c2980 100644 --- a/src/views/dolphinview.h +++ b/src/views/dolphinview.h @@ -8,13 +8,13 @@ #ifndef DOLPHINVIEW_H #define DOLPHINVIEW_H -#include "dolphintabwidget.h" #include "dolphin_export.h" +#include "dolphintabwidget.h" #include "tooltips/tooltipmanager.h" +#include "config-dolphin.h" #include #include -#include "config-dolphin.h" #include #include @@ -62,8 +62,7 @@ public: * view mode is automatically updated if the directory itself * defines a view mode (see class ViewProperties for details). */ - enum Mode - { + enum Mode { /** * The items are shown as icons with a name-label below. */ @@ -86,7 +85,7 @@ public: * @param url Specifies the content which should be shown. * @param parent Parent widget of the view. */ - DolphinView(const QUrl& url, QWidget* parent); + DolphinView(const QUrl &url, QWidget *parent); ~DolphinView() override; @@ -179,7 +178,7 @@ public: * Marks the item indicated by \p url to be scrolled to and as the * current item after directory DolphinView::url() has been loaded. */ - void markUrlAsCurrent(const QUrl& url); + void markUrlAsCurrent(const QUrl &url); /** * All items that match the regular expression \a regexp will get selected @@ -206,7 +205,7 @@ public: */ void resetZoomLevel(); - void setSortRole(const QByteArray& role); + void setSortRole(const QByteArray &role); QByteArray sortRole() const; void setSortOrder(Qt::SortOrder order); @@ -221,7 +220,7 @@ public: bool sortHiddenLast() const; /** Sets the additional information which should be shown for the items. */ - void setVisibleRoles(const QList& roles); + void setVisibleRoles(const QList &roles); /** Returns the additional information which should be shown for the items. */ QList visibleRoles() const; @@ -243,7 +242,7 @@ public: * Filters the currently shown items by \a nameFilter. All items * which contain the given filter string will be shown. */ - void setNameFilter(const QString& nameFilter); + void setNameFilter(const QString &nameFilter); QString nameFilter() const; /** @@ -251,7 +250,7 @@ public: * whose content-type matches those given by the list of filters * will be shown. */ - void setMimeTypeFilters(const QStringList& filters); + void setMimeTypeFilters(const QStringList &filters); QStringList mimeTypeFilters() const; /** @@ -267,7 +266,7 @@ public: * Returns the version control actions that are provided for the items \p items. * Usually the actions are presented in the context menu. */ - QList versionControlActions(const KFileItemList& items) const; + QList versionControlActions(const KFileItemList &items) const; /** * Returns the state of the paste action: @@ -301,12 +300,12 @@ public: /** * Restores the view state (current item, contents position, details view expansion state) */ - void restoreState(QDataStream& stream); + void restoreState(QDataStream &stream); /** * Saves the view state (current item, contents position, details view expansion state) */ - void saveState(QDataStream& stream); + void saveState(QDataStream &stream); /** * Returns the root item which represents the current URL. @@ -320,7 +319,7 @@ public: * makes sense if specific types of URLs (e.g. search-URLs) should * share common view-properties. */ - void setViewPropertiesContext(const QString& context); + void setViewPropertiesContext(const QString &context); QString viewPropertiesContext() const; /** @@ -329,7 +328,7 @@ public: * @return a valid and adjusted url if the item can be opened as folder, * otherwise return an empty url. */ - static QUrl openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives = true); + static QUrl openItemAsFolderUrl(const KFileItem &item, const bool browseThroughArchives = true); /** * Hides tooltip displayed over element. @@ -341,7 +340,7 @@ public Q_SLOTS: * Changes the directory to \a url. If the current directory is equal to * \a url, nothing will be done (use DolphinView::reload() instead). */ - void setUrl(const QUrl& url); + void setUrl(const QUrl &url); /** * Selects all items. @@ -428,7 +427,7 @@ public Q_SLOTS: void updateViewState(); /** Activates the view if the item list container gets focus. */ - bool eventFilter(QObject* watched, QEvent* event) override; + bool eventFilter(QObject *watched, QEvent *event) override; Q_SIGNALS: /** @@ -437,7 +436,7 @@ Q_SIGNALS: void activated(); /** Is emitted if the URL of the view has been changed to \a url. */ - void urlChanged(const QUrl& url); + void urlChanged(const QUrl &url); /** * Is emitted when clicking on an item with the left mouse button. @@ -458,7 +457,7 @@ Q_SIGNALS: /** * Is emitted if a new tab should be opened for the URL \a url. */ - void tabRequested(const QUrl& url); + void tabRequested(const QUrl &url); /** * Is emitted if a new tab should be opened for the URL \a url and set as active. @@ -490,7 +489,7 @@ Q_SIGNALS: void statusBarTextChanged(QString statusBarText); /** Is emitted if the sorting by name, size or date has been changed. */ - void sortRoleChanged(const QByteArray& role); + void sortRoleChanged(const QByteArray &role); /** Is emitted if the sort order (ascending or descending) has been changed. */ void sortOrderChanged(Qt::SortOrder order); @@ -507,8 +506,7 @@ Q_SIGNALS: void sortHiddenLastChanged(bool hiddenLast); /** Is emitted if the additional information shown for this view has been changed. */ - void visibleRolesChanged(const QList& current, - const QList& previous); + void visibleRolesChanged(const QList ¤t, const QList &previous); /** Is emitted if the zoom level has been changed by zooming in or out. */ void zoomLevelChanged(int current, int previous); @@ -517,40 +515,37 @@ Q_SIGNALS: * Is emitted if information of an item is requested to be shown e. g. in the panel. * If item is null, no item information request is pending. */ - void requestItemInfo(const KFileItem& item); + void requestItemInfo(const KFileItem &item); /** * Is emitted whenever the selection has been changed. */ - void selectionChanged(const KFileItemList& selection); + void selectionChanged(const KFileItemList &selection); /** * Is emitted if a context menu is requested for the item \a item, * which is part of \a url. If the item is null, the context menu * for the URL should be shown. */ - void requestContextMenu(const QPoint& pos, - const KFileItem& item, - const KFileItemList &selectedItems, - const QUrl& url); + void requestContextMenu(const QPoint &pos, const KFileItem &item, const KFileItemList &selectedItems, const QUrl &url); /** * Is emitted if an information message with the content \a msg * should be shown. */ - void infoMessage(const QString& msg); + void infoMessage(const QString &msg); /** * Is emitted if an error message with the content \a msg * should be shown. */ - void errorMessage(const QString& msg); + void errorMessage(const QString &msg); /** * Is emitted if an "operation completed" message with the content \a msg * should be shown. */ - void operationCompletedMessage(const QString& msg); + void operationCompletedMessage(const QString &msg); /** * Is emitted after DolphinView::setUrl() has been invoked and @@ -588,13 +583,13 @@ Q_SIGNALS: * Emitted when the file-item-model emits redirection. * Testcase: fish://localhost */ - void redirection(const QUrl& oldUrl, const QUrl& newUrl); + void redirection(const QUrl &oldUrl, const QUrl &newUrl); /** * Is emitted when the URL set by DolphinView::setUrl() represents a file. * In this case no signal errorMessage() will be emitted. */ - void urlIsFileError(const QUrl& url); + void urlIsFileError(const QUrl &url); /** * Is emitted when the write state of the folder has been changed. The application @@ -631,7 +626,7 @@ Q_SIGNALS: * Is emitted when the user clicks a tag or a link * in the metadata widget of a tooltip. */ - void urlActivated(const QUrl& url); + void urlActivated(const QUrl &url); void goUpRequested(); @@ -644,10 +639,10 @@ Q_SIGNALS: protected: /** Changes the zoom level if Control is pressed during a wheel event. */ - void wheelEvent(QWheelEvent* event) override; + void wheelEvent(QWheelEvent *event) override; - void hideEvent(QHideEvent* event) override; - bool event(QEvent* event) override; + void hideEvent(QHideEvent *event) override; + bool event(QEvent *event) override; private Q_SLOTS: /** @@ -659,17 +654,17 @@ private Q_SLOTS: void slotItemActivated(int index); void slotItemsActivated(const KItemSet &indexes); void slotItemMiddleClicked(int index); - void slotItemContextMenuRequested(int index, const QPointF& pos); - void slotViewContextMenuRequested(const QPointF& pos); - void slotHeaderContextMenuRequested(const QPointF& pos); - void slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current); + void slotItemContextMenuRequested(int index, const QPointF &pos); + void slotViewContextMenuRequested(const QPointF &pos); + void slotHeaderContextMenuRequested(const QPointF &pos); + void slotHeaderColumnWidthChangeFinished(const QByteArray &role, qreal current); void slotSidePaddingWidthChanged(qreal width); void slotItemHovered(int index); void slotItemUnhovered(int index); - void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event); - void slotModelChanged(KItemModelBase* current, KItemModelBase* previous); + void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event); + void slotModelChanged(KItemModelBase *current, KItemModelBase *previous); void slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons); - void slotRenameDialogRenamingFinished(const QList& urls); + void slotRenameDialogRenamingFinished(const QList &urls); void slotSelectedItemTextPressed(int index); void slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to); void slotIncreaseZoom(); @@ -692,7 +687,7 @@ private Q_SLOTS: * the signal is emitted only after no selection change has been done * within a small delay. */ - void slotSelectionChanged(const KItemSet& current, const KItemSet& previous); + void slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous); /** * Is called by emitDelayedSelectionChangedSignal() and emits the @@ -713,7 +708,7 @@ private Q_SLOTS: * Updates the view properties of the current URL to the * sorting given by \a role. */ - void updateSortRole(const QByteArray& role); + void updateSortRole(const QByteArray &role); /** * Updates the view properties of the current URL to the @@ -737,18 +732,18 @@ private Q_SLOTS: * Indicates in the status bar that the delete operation * of the job \a job has been finished. */ - void slotDeleteFileFinished(KJob* job); + void slotDeleteFileFinished(KJob *job); /** * Indicates in the status bar that the trash operation * of the job \a job has been finished. */ - void slotTrashFileFinished(KJob* job); + void slotTrashFileFinished(KJob *job); /** * Invoked when the rename job is done, for error handling. */ - void slotRenamingResult(KJob* job); + void slotRenamingResult(KJob *job); /** * Invoked when the file item model has started the loading @@ -783,17 +778,16 @@ private Q_SLOTS: * Is invoked when the sort role has been changed by the user by clicking * on a header item. The view properties of the directory will get updated. */ - void slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous); + void slotSortRoleChangedByHeader(const QByteArray ¤t, const QByteArray &previous); /** * Is invoked when the visible roles have been changed by the user by dragging * a header item. The view properties of the directory will get updated. */ - void slotVisibleRolesChangedByHeader(const QList& current, - const QList& previous); + void slotVisibleRolesChangedByHeader(const QList ¤t, const QList &previous); void slotRoleEditingCanceled(); - void slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value); + void slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value); /** * Observes the item with the URL \a url. As soon as the directory @@ -806,12 +800,12 @@ private Q_SLOTS: * Called when a redirection happens. * Testcase: fish://localhost */ - void slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl); + void slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl); void slotTwoClicksRenamingTimerTimeout(); private: - void loadDirectory(const QUrl& url, bool reload = false); + void loadDirectory(const QUrl &url, bool reload = false); /** * Applies the view properties which are defined by the current URL @@ -824,7 +818,7 @@ private: /** * Applies the given view properties to the DolphinView. */ - void applyViewProperties(const ViewProperties& props); + void applyViewProperties(const ViewProperties &props); /** * Applies the m_mode property to the corresponding @@ -832,10 +826,7 @@ private: */ void applyModeToView(); - enum Selection { - HasSelection, - NoSelection - }; + enum Selection { HasSelection, NoSelection }; /** * Helper method for DolphinView::requestStatusBarText(). * Generates the status bar text from the parameters and @@ -844,14 +835,13 @@ private: * @param selection if HasSelection is passed, the emitted status bar text will say * that the folders and files which are counted here are selected. */ - void emitStatusBarText(const int folderCount, const int fileCount, - KIO::filesize_t totalFileSize, const Selection selection); + void emitStatusBarText(const int folderCount, const int fileCount, KIO::filesize_t totalFileSize, const Selection selection); /** * Helper method for DolphinView::paste() and DolphinView::pasteIntoFolder(). * Pastes the clipboard data into the URL \a url. */ - void pasteToUrl(const QUrl& url); + void pasteToUrl(const QUrl &url); /** * Returns a list of URLs for all selected items. The list is @@ -863,7 +853,7 @@ private: /** * Returns the MIME data for all selected items. */ - QMimeData* selectionMimeData() const; + QMimeData *selectionMimeData() const; /** * Updates m_isFolderWritable dependent on whether the folder represented by @@ -885,13 +875,13 @@ private: * @param current URL to be set as current * @param selected list of selected items */ - void forceUrlsSelection(const QUrl& current, const QList& selected); + void forceUrlsSelection(const QUrl ¤t, const QList &selected); void abortTwoClicksRenaming(); void updatePlaceholderLabel(); - void tryShowNameToolTip(QHelpEvent* event); + void tryShowNameToolTip(QHelpEvent *event); private: void updatePalette(); @@ -904,12 +894,7 @@ private: bool m_dragging; // True if a dragging is done. Required to be able to decide whether a // tooltip may be shown when hovering an item. - enum class LoadingState { - Idle, - Loading, - Canceled, - Completed - }; + enum class LoadingState { Idle, Loading, Canceled, Completed }; LoadingState m_loadingState = LoadingState::Idle; QUrl m_url; @@ -919,15 +904,15 @@ private: QPointer m_statJobForStatusBarText; - QVBoxLayout* m_topLayout; + QVBoxLayout *m_topLayout; - KFileItemModel* m_model; - DolphinItemListView* m_view; - KItemListContainer* m_container; + KFileItemModel *m_model; + DolphinItemListView *m_view; + KItemListContainer *m_container; - ToolTipManager* m_toolTipManager; + ToolTipManager *m_toolTipManager; - QTimer* m_selectionChangedTimer; + QTimer *m_selectionChangedTimer; QUrl m_currentItemUrl; // Used for making the view to remember the current URL after F5 bool m_scrollToCurrentItem; // Used for marking we need to scroll to current item or not @@ -937,12 +922,12 @@ private: bool m_clearSelectionBeforeSelectingNewItems; bool m_markFirstNewlySelectedItemAsCurrent; - VersionControlObserver* m_versionControlObserver; + VersionControlObserver *m_versionControlObserver; - QTimer* m_twoClicksRenamingTimer; + QTimer *m_twoClicksRenamingTimer; QUrl m_twoClicksRenamingItemUrl; - QLabel* m_placeholderLabel; - QTimer* m_showLoadingPlaceholderTimer; + QLabel *m_placeholderLabel; + QTimer *m_showLoadingPlaceholderTimer; /// Used for selection mode. @see setSelectionMode() std::unique_ptr m_proxyStyle; @@ -951,7 +936,7 @@ private: friend class TestBase; friend class DolphinDetailsViewTest; friend class DolphinMainWindowTest; - friend class DolphinPart; // Accesses m_model + friend class DolphinPart; // Accesses m_model }; /// Allow using DolphinView::Mode in QVariant diff --git a/src/views/dolphinviewactionhandler.cpp b/src/views/dolphinviewactionhandler.cpp index fc88f5c179..cbe8b89e5d 100644 --- a/src/views/dolphinviewactionhandler.cpp +++ b/src/views/dolphinviewactionhandler.cpp @@ -28,18 +28,18 @@ #include #include -DolphinViewActionHandler::DolphinViewActionHandler(KActionCollection* collection, SelectionMode::ActionTextHelper* actionTextHelper, QObject* parent) : - QObject(parent), - m_actionCollection(collection), - m_currentView(nullptr), - m_sortByActions(), - m_visibleRoles() +DolphinViewActionHandler::DolphinViewActionHandler(KActionCollection *collection, SelectionMode::ActionTextHelper *actionTextHelper, QObject *parent) + : QObject(parent) + , m_actionCollection(collection) + , m_currentView(nullptr) + , m_sortByActions() + , m_visibleRoles() { Q_ASSERT(m_actionCollection); createActions(actionTextHelper); } -void DolphinViewActionHandler::setCurrentView(DolphinView* view) +void DolphinViewActionHandler::setCurrentView(DolphinView *view) { Q_ASSERT(view); @@ -49,36 +49,25 @@ void DolphinViewActionHandler::setCurrentView(DolphinView* view) m_currentView = view; - connect(view, &DolphinView::modeChanged, - this, &DolphinViewActionHandler::updateViewActions); - connect(view, &DolphinView::previewsShownChanged, - this, &DolphinViewActionHandler::slotPreviewsShownChanged); - connect(view, &DolphinView::sortOrderChanged, - this, &DolphinViewActionHandler::slotSortOrderChanged); - connect(view, &DolphinView::sortFoldersFirstChanged, - this, &DolphinViewActionHandler::slotSortFoldersFirstChanged); - connect(view, &DolphinView::sortHiddenLastChanged, - this, &DolphinViewActionHandler::slotSortHiddenLastChanged); - connect(view, &DolphinView::visibleRolesChanged, - this, &DolphinViewActionHandler::slotVisibleRolesChanged); - connect(view, &DolphinView::groupedSortingChanged, - this, &DolphinViewActionHandler::slotGroupedSortingChanged); - connect(view, &DolphinView::hiddenFilesShownChanged, - this, &DolphinViewActionHandler::slotHiddenFilesShownChanged); - connect(view, &DolphinView::sortRoleChanged, - this, &DolphinViewActionHandler::slotSortRoleChanged); - connect(view, &DolphinView::zoomLevelChanged, - this, &DolphinViewActionHandler::slotZoomLevelChanged); - connect(view, &DolphinView::writeStateChanged, - this, &DolphinViewActionHandler::slotWriteStateChanged); - connect(view, &DolphinView::selectionModeChangeRequested, - this, [this](bool enabled) { Q_EMIT selectionModeChangeTriggered(enabled); }); - connect(view, &DolphinView::selectionChanged, - this, &DolphinViewActionHandler::slotSelectionChanged); + connect(view, &DolphinView::modeChanged, this, &DolphinViewActionHandler::updateViewActions); + connect(view, &DolphinView::previewsShownChanged, this, &DolphinViewActionHandler::slotPreviewsShownChanged); + connect(view, &DolphinView::sortOrderChanged, this, &DolphinViewActionHandler::slotSortOrderChanged); + connect(view, &DolphinView::sortFoldersFirstChanged, this, &DolphinViewActionHandler::slotSortFoldersFirstChanged); + connect(view, &DolphinView::sortHiddenLastChanged, this, &DolphinViewActionHandler::slotSortHiddenLastChanged); + connect(view, &DolphinView::visibleRolesChanged, this, &DolphinViewActionHandler::slotVisibleRolesChanged); + connect(view, &DolphinView::groupedSortingChanged, this, &DolphinViewActionHandler::slotGroupedSortingChanged); + connect(view, &DolphinView::hiddenFilesShownChanged, this, &DolphinViewActionHandler::slotHiddenFilesShownChanged); + connect(view, &DolphinView::sortRoleChanged, this, &DolphinViewActionHandler::slotSortRoleChanged); + connect(view, &DolphinView::zoomLevelChanged, this, &DolphinViewActionHandler::slotZoomLevelChanged); + connect(view, &DolphinView::writeStateChanged, this, &DolphinViewActionHandler::slotWriteStateChanged); + connect(view, &DolphinView::selectionModeChangeRequested, this, [this](bool enabled) { + Q_EMIT selectionModeChangeTriggered(enabled); + }); + connect(view, &DolphinView::selectionChanged, this, &DolphinViewActionHandler::slotSelectionChanged); slotSelectionChanged(m_currentView->selectedItems()); } -DolphinView* DolphinViewActionHandler::currentView() +DolphinView *DolphinViewActionHandler::currentView() { return m_currentView; } @@ -87,19 +76,20 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac { // This action doesn't appear in the GUI, it's for the shortcut only. // KNewFileMenu takes care of the GUI stuff. - QAction* newDirAction = m_actionCollection->addAction(QStringLiteral("create_dir")); + QAction *newDirAction = m_actionCollection->addAction(QStringLiteral("create_dir")); newDirAction->setText(i18nc("@action", "Create Folder...")); m_actionCollection->setDefaultShortcuts(newDirAction, KStandardShortcut::createFolder()); newDirAction->setIcon(QIcon::fromTheme(QStringLiteral("folder-new"))); - newDirAction->setEnabled(false); // Will be enabled in slotWriteStateChanged(bool) if the current URL is writable + newDirAction->setEnabled(false); // Will be enabled in slotWriteStateChanged(bool) if the current URL is writable connect(newDirAction, &QAction::triggered, this, &DolphinViewActionHandler::createDirectoryTriggered); // File menu auto renameAction = KStandardAction::renameFile(this, &DolphinViewActionHandler::slotRename, m_actionCollection); - renameAction->setWhatsThis(xi18nc("@info:whatsthis", "This renames the " - "items in your current selection.Renaming multiple items " - "at once amounts to their new names differing only in a number.")); + renameAction->setWhatsThis(xi18nc("@info:whatsthis", + "This renames the " + "items in your current selection.Renaming multiple items " + "at once amounts to their new names differing only in a number.")); auto trashAction = KStandardAction::moveToTrash(this, &DolphinViewActionHandler::slotTrashActivated, m_actionCollection); auto trashShortcuts = trashAction->shortcuts(); @@ -107,10 +97,11 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac trashShortcuts.append(QKeySequence::Delete); m_actionCollection->setDefaultShortcuts(trashAction, trashShortcuts); } - trashAction->setWhatsThis(xi18nc("@info:whatsthis", "This moves the " - "items in your current selection to the Trash" - ".The trash is a temporary storage where " - "items can be deleted from if disk space is needed.")); + trashAction->setWhatsThis(xi18nc("@info:whatsthis", + "This moves the " + "items in your current selection to the Trash" + ".The trash is a temporary storage where " + "items can be deleted from if disk space is needed.")); auto deleteAction = KStandardAction::deleteFile(this, &DolphinViewActionHandler::slotDeleteItems, m_actionCollection); auto deleteShortcuts = deleteAction->shortcuts(); @@ -118,46 +109,45 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac deleteShortcuts.append(Qt::SHIFT | Qt::Key_Delete); m_actionCollection->setDefaultShortcuts(deleteAction, deleteShortcuts); } - deleteAction->setWhatsThis(xi18nc("@info:whatsthis", "This deletes " - "the items in your current selection completely. They can " - "not be recovered by normal means.")); + deleteAction->setWhatsThis(xi18nc("@info:whatsthis", + "This deletes " + "the items in your current selection completely. They can " + "not be recovered by normal means.")); // This action is useful for being enabled when KStandardAction::MoveToTrash should be // disabled and KStandardAction::DeleteFile is enabled (e.g. non-local files), so that Key_Del // can be used for deleting the file (#76016). It needs to be a separate action // so that the Edit menu isn't affected. - QAction* deleteWithTrashShortcut = m_actionCollection->addAction(QStringLiteral("delete_shortcut")); + QAction *deleteWithTrashShortcut = m_actionCollection->addAction(QStringLiteral("delete_shortcut")); // The descriptive text is just for the shortcuts editor. deleteWithTrashShortcut->setText(i18nc("@action \"Move to Trash\" for non-local files, etc.", "Delete (using shortcut for Trash)")); m_actionCollection->setDefaultShortcuts(deleteWithTrashShortcut, KStandardShortcut::moveToTrash()); deleteWithTrashShortcut->setEnabled(false); connect(deleteWithTrashShortcut, &QAction::triggered, this, &DolphinViewActionHandler::slotDeleteItems); - QAction* duplicateAction = m_actionCollection->addAction(QStringLiteral("duplicate")); + QAction *duplicateAction = m_actionCollection->addAction(QStringLiteral("duplicate")); duplicateAction->setText(i18nc("@action:inmenu File", "Duplicate Here")); duplicateAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-duplicate"))); m_actionCollection->setDefaultShortcut(duplicateAction, Qt::CTRL | Qt::Key_D); duplicateAction->setEnabled(false); connect(duplicateAction, &QAction::triggered, this, &DolphinViewActionHandler::slotDuplicate); - QAction *propertiesAction = m_actionCollection->addAction( QStringLiteral("properties") ); + QAction *propertiesAction = m_actionCollection->addAction(QStringLiteral("properties")); // Well, it's the File menu in dolphinmainwindow and the Edit menu in dolphinpart... :) - propertiesAction->setText( i18nc("@action:inmenu File", "Properties") ); + propertiesAction->setText(i18nc("@action:inmenu File", "Properties")); propertiesAction->setWhatsThis(xi18nc("@info:whatsthis properties", - "This shows a complete list of properties of the currently " - "selected items in a new window.If nothing is selected the " - "window will be about the currently viewed folder instead." - "You can configure advanced options there like managing " - "read- and write-permissions.")); + "This shows a complete list of properties of the currently " + "selected items in a new window.If nothing is selected the " + "window will be about the currently viewed folder instead." + "You can configure advanced options there like managing " + "read- and write-permissions.")); propertiesAction->setIcon(QIcon::fromTheme(QStringLiteral("document-properties"))); m_actionCollection->setDefaultShortcuts(propertiesAction, {Qt::ALT | Qt::Key_Return, Qt::ALT | Qt::Key_Enter}); connect(propertiesAction, &QAction::triggered, this, &DolphinViewActionHandler::slotProperties); - QAction *copyPathAction = m_actionCollection->addAction( QStringLiteral("copy_location") ); + QAction *copyPathAction = m_actionCollection->addAction(QStringLiteral("copy_location")); copyPathAction->setText(i18nc("@action:incontextmenu", "Copy Location")); - copyPathAction->setWhatsThis(i18nc("@info:whatsthis copy_location", - "This will copy the path of the first selected item into the clipboard." - )); + copyPathAction->setWhatsThis(i18nc("@info:whatsthis copy_location", "This will copy the path of the first selected item into the clipboard.")); copyPathAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy-path"))); m_actionCollection->setDefaultShortcuts(copyPathAction, {Qt::CTRL | Qt::ALT | Qt::Key_C}); @@ -192,32 +182,32 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac // actions in slotSelectionChanged() after the static ones above. // View menu - KToggleAction* iconsAction = iconsModeAction(); - KToggleAction* compactAction = compactModeAction(); - KToggleAction* detailsAction = detailsModeAction(); + KToggleAction *iconsAction = iconsModeAction(); + KToggleAction *compactAction = compactModeAction(); + KToggleAction *detailsAction = detailsModeAction(); iconsAction->setWhatsThis(xi18nc("@info:whatsthis Icons view mode", - "This switches to a view mode that focuses on the folder " - "and file icons. This mode makes it easy to distinguish folders " - "from files and to detect items with distinctive " - "file types. This mode is handy to " - "browse through pictures when the Preview" - " option is enabled.")); + "This switches to a view mode that focuses on the folder " + "and file icons. This mode makes it easy to distinguish folders " + "from files and to detect items with distinctive " + "file types. This mode is handy to " + "browse through pictures when the Preview" + " option is enabled.")); compactAction->setWhatsThis(xi18nc("@info:whatsthis Compact view mode", - "This switches to a compact view mode that lists the folders " - "and files in columns with the names beside the icons." - "This helps to keep the overview in folders with many items.")); + "This switches to a compact view mode that lists the folders " + "and files in columns with the names beside the icons." + "This helps to keep the overview in folders with many items.")); detailsAction->setWhatsThis(xi18nc("@info:whatsthis Details view mode", - "This switches to a list view mode that focuses on folder " - "and file details.Click on a detail in the column " - "header to sort the items by it. Click again to sort the other " - "way around. To select which details should be displayed click " - "the header with the right mouse button.You can " - "view the contents of a folder without leaving the current " - "location by clicking to the left of it. This way you can view " - "the contents of multiple folders in the same list.")); + "This switches to a list view mode that focuses on folder " + "and file details.Click on a detail in the column " + "header to sort the items by it. Click again to sort the other " + "way around. To select which details should be displayed click " + "the header with the right mouse button.You can " + "view the contents of a folder without leaving the current " + "location by clicking to the left of it. This way you can view " + "the contents of multiple folders in the same list.")); - KSelectAction* viewModeActions = m_actionCollection->add(QStringLiteral("view_mode")); + KSelectAction *viewModeActions = m_actionCollection->add(QStringLiteral("view_mode")); viewModeActions->setText(i18nc("@action:intoolbar", "View Mode")); viewModeActions->addAction(iconsAction); viewModeActions->addAction(compactAction); @@ -225,12 +215,10 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac viewModeActions->setToolBarMode(KSelectAction::MenuMode); connect(viewModeActions, &KSelectAction::triggered, this, &DolphinViewActionHandler::slotViewModeActionTriggered); - QAction* zoomInAction = KStandardAction::zoomIn(this, - &DolphinViewActionHandler::zoomIn, - m_actionCollection); + QAction *zoomInAction = KStandardAction::zoomIn(this, &DolphinViewActionHandler::zoomIn, m_actionCollection); zoomInAction->setWhatsThis(i18nc("@info:whatsthis zoom in", "This increases the icon size.")); - QAction* zoomResetAction = m_actionCollection->addAction(QStringLiteral("view_zoom_reset")); + QAction *zoomResetAction = m_actionCollection->addAction(QStringLiteral("view_zoom_reset")); zoomResetAction->setText(i18nc("@action:inmenu View", "Reset Zoom Level")); zoomResetAction->setToolTip(i18n("Zoom To Default")); zoomResetAction->setWhatsThis(i18nc("@info:whatsthis zoom reset", "This resets the icon size to default.")); @@ -238,12 +226,10 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac m_actionCollection->setDefaultShortcuts(zoomResetAction, {Qt::CTRL | Qt::Key_0}); connect(zoomResetAction, &QAction::triggered, this, &DolphinViewActionHandler::zoomReset); - QAction* zoomOutAction = KStandardAction::zoomOut(this, - &DolphinViewActionHandler::zoomOut, - m_actionCollection); + QAction *zoomOutAction = KStandardAction::zoomOut(this, &DolphinViewActionHandler::zoomOut, m_actionCollection); zoomOutAction->setWhatsThis(i18nc("@info:whatsthis zoom out", "This reduces the icon size.")); - KActionMenu* zoomMenu = m_actionCollection->add(QStringLiteral("zoom")); + KActionMenu *zoomMenu = m_actionCollection->add(QStringLiteral("zoom")); zoomMenu->setText(i18nc("@action:inmenu menu of zoom actions", "Zoom")); zoomMenu->setIcon(QIcon::fromTheme(QStringLiteral("zoom"))); zoomMenu->setPopupMode(QToolButton::InstantPopup); @@ -251,49 +237,50 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac zoomMenu->addAction(zoomResetAction); zoomMenu->addAction(zoomOutAction); - KToggleAction* showPreview = m_actionCollection->add(QStringLiteral("show_preview")); + KToggleAction *showPreview = m_actionCollection->add(QStringLiteral("show_preview")); showPreview->setText(i18nc("@action:intoolbar", "Show Previews")); showPreview->setToolTip(i18nc("@info", "Show preview of files and folders")); - showPreview->setWhatsThis(xi18nc("@info:whatsthis", "When this is " - "enabled, the icons are based on the actual file or folder " - "contents.For example the icons of images become scaled " - "down versions of the images.")); + showPreview->setWhatsThis(xi18nc("@info:whatsthis", + "When this is " + "enabled, the icons are based on the actual file or folder " + "contents.For example the icons of images become scaled " + "down versions of the images.")); showPreview->setIcon(QIcon::fromTheme(QStringLiteral("view-preview"))); connect(showPreview, &KToggleAction::triggered, this, &DolphinViewActionHandler::togglePreview); - KToggleAction* sortFoldersFirst = m_actionCollection->add(QStringLiteral("folders_first")); + KToggleAction *sortFoldersFirst = m_actionCollection->add(QStringLiteral("folders_first")); sortFoldersFirst->setText(i18nc("@action:inmenu Sort", "Folders First")); connect(sortFoldersFirst, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleSortFoldersFirst); - KToggleAction* sortHiddenLast = m_actionCollection->add(QStringLiteral("hidden_last")); + KToggleAction *sortHiddenLast = m_actionCollection->add(QStringLiteral("hidden_last")); sortHiddenLast->setText(i18nc("@action:inmenu Sort", "Hidden Files Last")); connect(sortHiddenLast, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleSortHiddenLast); // View -> Sort By - QActionGroup* sortByActionGroup = createFileItemRolesActionGroup(QStringLiteral("sort_by_")); + QActionGroup *sortByActionGroup = createFileItemRolesActionGroup(QStringLiteral("sort_by_")); - KActionMenu* sortByActionMenu = m_actionCollection->add(QStringLiteral("sort")); + KActionMenu *sortByActionMenu = m_actionCollection->add(QStringLiteral("sort")); sortByActionMenu->setIcon(QIcon::fromTheme(QStringLiteral("view-sort"))); sortByActionMenu->setText(i18nc("@action:inmenu View", "Sort By")); sortByActionMenu->setPopupMode(QToolButton::InstantPopup); const auto sortByActionGroupActions = sortByActionGroup->actions(); - for (QAction* action : sortByActionGroupActions) { + for (QAction *action : sortByActionGroupActions) { sortByActionMenu->addAction(action); } sortByActionMenu->addSeparator(); - QActionGroup* group = new QActionGroup(sortByActionMenu); + QActionGroup *group = new QActionGroup(sortByActionMenu); group->setExclusive(true); - KToggleAction* ascendingAction = m_actionCollection->add(QStringLiteral("ascending")); + KToggleAction *ascendingAction = m_actionCollection->add(QStringLiteral("ascending")); ascendingAction->setActionGroup(group); connect(ascendingAction, &QAction::triggered, this, [this] { m_currentView->setSortOrder(Qt::AscendingOrder); }); - KToggleAction* descendingAction = m_actionCollection->add(QStringLiteral("descending")); + KToggleAction *descendingAction = m_actionCollection->add(QStringLiteral("descending")); descendingAction->setActionGroup(group); connect(descendingAction, &QAction::triggered, this, [this] { m_currentView->setSortOrder(Qt::DescendingOrder); @@ -306,62 +293,62 @@ void DolphinViewActionHandler::createActions(SelectionMode::ActionTextHelper *ac sortByActionMenu->addAction(sortHiddenLast); // View -> Additional Information - QActionGroup* visibleRolesGroup = createFileItemRolesActionGroup(QStringLiteral("show_")); + QActionGroup *visibleRolesGroup = createFileItemRolesActionGroup(QStringLiteral("show_")); - KActionMenu* visibleRolesMenu = m_actionCollection->add(QStringLiteral("additional_info")); + KActionMenu *visibleRolesMenu = m_actionCollection->add(QStringLiteral("additional_info")); visibleRolesMenu->setText(i18nc("@action:inmenu View", "Show Additional Information")); visibleRolesMenu->setIcon(QIcon::fromTheme(QStringLiteral("documentinfo"))); visibleRolesMenu->setPopupMode(QToolButton::InstantPopup); const auto visibleRolesGroupActions = visibleRolesGroup->actions(); - for (QAction* action : visibleRolesGroupActions) { + for (QAction *action : visibleRolesGroupActions) { visibleRolesMenu->addAction(action); } - KToggleAction* showInGroups = m_actionCollection->add(QStringLiteral("show_in_groups")); + KToggleAction *showInGroups = m_actionCollection->add(QStringLiteral("show_in_groups")); showInGroups->setIcon(QIcon::fromTheme(QStringLiteral("view-group"))); showInGroups->setText(i18nc("@action:inmenu View", "Show in Groups")); showInGroups->setWhatsThis(i18nc("@info:whatsthis", "This groups files and folders by their first letter.")); connect(showInGroups, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleGroupedSorting); - KToggleAction* showHiddenFiles = m_actionCollection->add(QStringLiteral("show_hidden_files")); + KToggleAction *showHiddenFiles = m_actionCollection->add(QStringLiteral("show_hidden_files")); showHiddenFiles->setIcon(QIcon::fromTheme(QStringLiteral("view-visible"))); showHiddenFiles->setText(i18nc("@action:inmenu View", "Show Hidden Files")); - showHiddenFiles->setWhatsThis(xi18nc("@info:whatsthis", "When " - "this is enabled hidden files and folders " - "are visible. They will be displayed semi-transparent." - "Hidden items only differ from other ones in that their " - "name starts with a \".\". In general there is no need for " - "users to access them which is why they are hidden.")); + showHiddenFiles->setWhatsThis(xi18nc("@info:whatsthis", + "When " + "this is enabled hidden files and folders " + "are visible. They will be displayed semi-transparent." + "Hidden items only differ from other ones in that their " + "name starts with a \".\". In general there is no need for " + "users to access them which is why they are hidden.")); m_actionCollection->setDefaultShortcuts(showHiddenFiles, KStandardShortcut::showHideHiddenFiles()); connect(showHiddenFiles, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleShowHiddenFiles); - QAction* adjustViewProps = m_actionCollection->addAction(QStringLiteral("view_properties")); + QAction *adjustViewProps = m_actionCollection->addAction(QStringLiteral("view_properties")); adjustViewProps->setText(i18nc("@action:inmenu View", "Adjust View Display Style...")); adjustViewProps->setIcon(QIcon::fromTheme(QStringLiteral("view-choose"))); - adjustViewProps->setWhatsThis(i18nc("@info:whatsthis", "This opens a window " - "in which all folder view properties can be adjusted.")); + adjustViewProps->setWhatsThis(i18nc("@info:whatsthis", + "This opens a window " + "in which all folder view properties can be adjusted.")); connect(adjustViewProps, &QAction::triggered, this, &DolphinViewActionHandler::slotAdjustViewProperties); } -QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QString& groupPrefix) +QActionGroup *DolphinViewActionHandler::createFileItemRolesActionGroup(const QString &groupPrefix) { const bool isSortGroup = (groupPrefix == QLatin1String("sort_by_")); Q_ASSERT(isSortGroup || groupPrefix == QLatin1String("show_")); - QActionGroup* rolesActionGroup = new QActionGroup(m_actionCollection); + QActionGroup *rolesActionGroup = new QActionGroup(m_actionCollection); rolesActionGroup->setExclusive(isSortGroup); if (isSortGroup) { - connect(rolesActionGroup, &QActionGroup::triggered, - this, &DolphinViewActionHandler::slotSortTriggered); + connect(rolesActionGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::slotSortTriggered); } else { - connect(rolesActionGroup, &QActionGroup::triggered, - this, &DolphinViewActionHandler::toggleVisibleRole); + connect(rolesActionGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::toggleVisibleRole); } QString groupName; - KActionMenu* groupMenu = nullptr; - QActionGroup* groupMenuGroup = nullptr; + KActionMenu *groupMenu = nullptr; + QActionGroup *groupMenuGroup = nullptr; bool indexingEnabled = false; #if HAVE_BALOO @@ -370,13 +357,13 @@ QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QSt #endif const QList rolesInfo = KFileItemModel::rolesInformation(); - for (const KFileItemModel::RoleInfo& info : rolesInfo) { + for (const KFileItemModel::RoleInfo &info : rolesInfo) { if (!isSortGroup && info.role == "text") { // It should not be possible to hide the "text" role continue; } - KToggleAction* action = nullptr; + KToggleAction *action = nullptr; const QString name = groupPrefix + info.role; if (info.group.isEmpty()) { action = m_actionCollection->add(name); @@ -391,11 +378,9 @@ QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QSt groupMenuGroup = new QActionGroup(groupMenu); groupMenuGroup->setExclusive(isSortGroup); if (isSortGroup) { - connect(groupMenuGroup, &QActionGroup::triggered, - this, &DolphinViewActionHandler::slotSortTriggered); + connect(groupMenuGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::slotSortTriggered); } else { - connect(groupMenuGroup, &QActionGroup::triggered, - this, &DolphinViewActionHandler::toggleVisibleRole); + connect(groupMenuGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::toggleVisibleRole); } } @@ -406,9 +391,7 @@ QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QSt action->setText(info.translation); action->setData(info.role); - const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || - (info.requiresBaloo) || - (info.requiresIndexer && indexingEnabled); + const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled); action->setEnabled(enable); if (isSortGroup) { @@ -421,12 +404,12 @@ QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QSt return rolesActionGroup; } -void DolphinViewActionHandler::slotViewModeActionTriggered(QAction* action) +void DolphinViewActionHandler::slotViewModeActionTriggered(QAction *action) { const DolphinView::Mode mode = action->data().value(); m_currentView->setViewMode(mode); - QAction* viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode")); + QAction *viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode")); viewModeMenu->setIcon(action->icon()); } @@ -493,22 +476,22 @@ QString DolphinViewActionHandler::currentViewModeActionName() const return QString(); // can't happen } -KActionCollection* DolphinViewActionHandler::actionCollection() +KActionCollection *DolphinViewActionHandler::actionCollection() { return m_actionCollection; } void DolphinViewActionHandler::updateViewActions() { - QAction* viewModeAction = m_actionCollection->action(currentViewModeActionName()); + QAction *viewModeAction = m_actionCollection->action(currentViewModeActionName()); if (viewModeAction) { viewModeAction->setChecked(true); - QAction* viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode")); + QAction *viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode")); viewModeMenu->setIcon(viewModeAction->icon()); } - QAction* showPreviewAction = m_actionCollection->action(QStringLiteral("show_preview")); + QAction *showPreviewAction = m_actionCollection->action(QStringLiteral("show_preview")); showPreviewAction->setChecked(m_currentView->previewsShown()); slotSortOrderChanged(m_currentView->sortOrder()); @@ -557,8 +540,8 @@ void DolphinViewActionHandler::toggleSortHiddenLast() void DolphinViewActionHandler::slotSortOrderChanged(Qt::SortOrder order) { - QAction* descending = m_actionCollection->action(QStringLiteral("descending")); - QAction* ascending = m_actionCollection->action(QStringLiteral("ascending")); + QAction *descending = m_actionCollection->action(QStringLiteral("descending")); + QAction *ascending = m_actionCollection->action(QStringLiteral("ascending")); const bool sortDescending = (order == Qt::DescendingOrder); descending->setChecked(sortDescending); ascending->setChecked(!sortDescending); @@ -574,7 +557,7 @@ void DolphinViewActionHandler::slotSortHiddenLastChanged(bool hiddenLast) m_actionCollection->action(QStringLiteral("hidden_last"))->setChecked(hiddenLast); } -void DolphinViewActionHandler::toggleVisibleRole(QAction* action) +void DolphinViewActionHandler::toggleVisibleRole(QAction *action) { Q_EMIT actionBeingHandled(); @@ -596,17 +579,16 @@ void DolphinViewActionHandler::toggleVisibleRole(QAction* action) } } -void DolphinViewActionHandler::slotVisibleRolesChanged(const QList& current, - const QList& previous) +void DolphinViewActionHandler::slotVisibleRolesChanged(const QList ¤t, const QList &previous) { Q_UNUSED(previous) const auto checkedRoles = QSet(current.constBegin(), current.constEnd()); - QHashIterator it(m_visibleRoles); + QHashIterator it(m_visibleRoles); while (it.hasNext()) { it.next(); - const QByteArray& role = it.key(); - KToggleAction* action = it.value(); + const QByteArray &role = it.key(); + KToggleAction *action = it.value(); action->setChecked(checkedRoles.contains(role)); } } @@ -618,7 +600,7 @@ void DolphinViewActionHandler::toggleGroupedSorting(bool grouped) void DolphinViewActionHandler::slotGroupedSortingChanged(bool groupedSorting) { - QAction* showInGroupsAction = m_actionCollection->action(QStringLiteral("show_in_groups")); + QAction *showInGroupsAction = m_actionCollection->action(QStringLiteral("show_in_groups")); showInGroupsAction->setChecked(groupedSorting); } @@ -630,19 +612,18 @@ void DolphinViewActionHandler::toggleShowHiddenFiles(bool show) void DolphinViewActionHandler::slotHiddenFilesShownChanged(bool shown) { - QAction* showHiddenFilesAction = m_actionCollection->action(QStringLiteral("show_hidden_files")); + QAction *showHiddenFilesAction = m_actionCollection->action(QStringLiteral("show_hidden_files")); showHiddenFilesAction->setChecked(shown); } void DolphinViewActionHandler::slotWriteStateChanged(bool isFolderWritable) { - m_actionCollection->action(QStringLiteral("create_dir"))->setEnabled(isFolderWritable && - KProtocolManager::supportsMakeDir(currentView()->url())); + m_actionCollection->action(QStringLiteral("create_dir"))->setEnabled(isFolderWritable && KProtocolManager::supportsMakeDir(currentView()->url())); } -KToggleAction* DolphinViewActionHandler::iconsModeAction() +KToggleAction *DolphinViewActionHandler::iconsModeAction() { - KToggleAction* iconsView = m_actionCollection->add(QStringLiteral("icons")); + KToggleAction *iconsView = m_actionCollection->add(QStringLiteral("icons")); iconsView->setText(i18nc("@action:inmenu View Mode", "Icons")); iconsView->setToolTip(i18nc("@info", "Icons view mode")); m_actionCollection->setDefaultShortcut(iconsView, Qt::CTRL | Qt::Key_1); @@ -651,9 +632,9 @@ KToggleAction* DolphinViewActionHandler::iconsModeAction() return iconsView; } -KToggleAction* DolphinViewActionHandler::compactModeAction() +KToggleAction *DolphinViewActionHandler::compactModeAction() { - KToggleAction* iconsView = m_actionCollection->add(QStringLiteral("compact")); + KToggleAction *iconsView = m_actionCollection->add(QStringLiteral("compact")); iconsView->setText(i18nc("@action:inmenu View Mode", "Compact")); iconsView->setToolTip(i18nc("@info", "Compact view mode")); m_actionCollection->setDefaultShortcut(iconsView, Qt::CTRL | Qt::Key_2); @@ -662,9 +643,9 @@ KToggleAction* DolphinViewActionHandler::compactModeAction() return iconsView; } -KToggleAction* DolphinViewActionHandler::detailsModeAction() +KToggleAction *DolphinViewActionHandler::detailsModeAction() { - KToggleAction* detailsView = m_actionCollection->add(QStringLiteral("details")); + KToggleAction *detailsView = m_actionCollection->add(QStringLiteral("details")); detailsView->setText(i18nc("@action:inmenu View Mode", "Details")); detailsView->setToolTip(i18nc("@info", "Details view mode")); m_actionCollection->setDefaultShortcut(detailsView, Qt::CTRL | Qt::Key_3); @@ -673,20 +654,20 @@ KToggleAction* DolphinViewActionHandler::detailsModeAction() return detailsView; } -void DolphinViewActionHandler::slotSortRoleChanged(const QByteArray& role) +void DolphinViewActionHandler::slotSortRoleChanged(const QByteArray &role) { - KToggleAction* action = m_sortByActions.value(role); + KToggleAction *action = m_sortByActions.value(role); if (action) { action->setChecked(true); if (!action->icon().isNull()) { - QAction* sortByMenu = m_actionCollection->action(QStringLiteral("sort")); + QAction *sortByMenu = m_actionCollection->action(QStringLiteral("sort")); sortByMenu->setIcon(action->icon()); } } - QAction* descending = m_actionCollection->action(QStringLiteral("descending")); - QAction* ascending = m_actionCollection->action(QStringLiteral("ascending")); + QAction *descending = m_actionCollection->action(QStringLiteral("descending")); + QAction *ascending = m_actionCollection->action(QStringLiteral("ascending")); if (role == "text" || role == "type" || role == "extension" || role == "tags" || role == "comment") { descending->setText(i18nc("Sort descending", "Z-A")); @@ -712,18 +693,18 @@ void DolphinViewActionHandler::slotZoomLevelChanged(int current, int previous) { Q_UNUSED(previous) - QAction* zoomInAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomIn)); + QAction *zoomInAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomIn)); if (zoomInAction) { zoomInAction->setEnabled(current < ZoomLevelInfo::maximumLevel()); } - QAction* zoomOutAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomOut)); + QAction *zoomOutAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomOut)); if (zoomOutAction) { zoomOutAction->setEnabled(current > ZoomLevelInfo::minimumLevel()); } } -void DolphinViewActionHandler::slotSortTriggered(QAction* action) +void DolphinViewActionHandler::slotSortTriggered(QAction *action) { // The radiobuttons of the "Sort By"-menu are split between the main-menu // and several sub-menus. Because of this they don't have a common @@ -732,10 +713,10 @@ void DolphinViewActionHandler::slotSortTriggered(QAction* action) // be assured that all other actions get unchecked, except the ascending/ // descending actions for (QAction *groupAction : qAsConst(m_sortByActions)) { - KActionMenu* actionMenu = qobject_cast(groupAction); + KActionMenu *actionMenu = qobject_cast(groupAction); if (actionMenu) { const auto actions = actionMenu->menu()->actions(); - for (QAction* subAction : actions) { + for (QAction *subAction : actions) { subAction->setChecked(false); } } else if (groupAction->actionGroup()) { @@ -770,7 +751,7 @@ void DolphinViewActionHandler::slotDuplicate() void DolphinViewActionHandler::slotProperties() { - KPropertiesDialog* dialog = nullptr; + KPropertiesDialog *dialog = nullptr; const KFileItemList list = m_currentView->selectedItems(); if (list.isEmpty()) { const QUrl url = m_currentView->url(); @@ -795,14 +776,14 @@ void DolphinViewActionHandler::slotCopyPath() } } -void DolphinViewActionHandler::slotSelectionChanged(const KFileItemList& selection) +void DolphinViewActionHandler::slotSelectionChanged(const KFileItemList &selection) { QString basicActionsMenuText; if (selection.isEmpty()) { - basicActionsMenuText = - i18nc("@action:inmenu menu with actions like copy, paste, rename. The user's selection is empty when this text is shown.", - "Actions for Current View"); + basicActionsMenuText = i18nc("@action:inmenu menu with actions like copy, paste, rename. The user's selection is empty when this text is shown.", + "Actions for Current View"); } else { + // clang-format off QFontMetrics fontMetrics = QMenu().fontMetrics(); // i18n: @action:inmenu menu with actions like copy, paste, rename. // %1 is a textual representation of the currently selected files or folders. This can be the name of @@ -810,13 +791,15 @@ void DolphinViewActionHandler::slotSelectionChanged(const KFileItemList& selecti // If this sort of word puzzle can not be correctly translated in your language, translate it as "NULL" (without the quotes) // and a fallback will be used. basicActionsMenuText = i18n("Actions for %1", fileItemListToString(selection, fontMetrics.averageCharWidth() * 40, fontMetrics, ItemsState::Selected)); + // clang-format on } if (basicActionsMenuText == QStringLiteral("NULL")) { const KFileItemListProperties properties(selection); - basicActionsMenuText = - i18ncp("@action:inmenu menu with actions like copy, paste, rename. %1 is the amount of selected files/folders.", - "Actions for One Selected Item", "Actions for %1 Selected Items", selection.count()); + basicActionsMenuText = i18ncp("@action:inmenu menu with actions like copy, paste, rename. %1 is the amount of selected files/folders.", + "Actions for One Selected Item", + "Actions for %1 Selected Items", + selection.count()); } QAction *basicActionsMenu = m_actionCollection->action(QStringLiteral("basic_actions")); diff --git a/src/views/dolphinviewactionhandler.h b/src/views/dolphinviewactionhandler.h index 8631936d9c..f36b3d1d04 100644 --- a/src/views/dolphinviewactionhandler.h +++ b/src/views/dolphinviewactionhandler.h @@ -5,7 +5,6 @@ * SPDX-License-Identifier: GPL-2.0-or-later */ - #ifndef DOLPHINVIEWACTIONHANDLER_H #define DOLPHINVIEWACTIONHANDLER_H @@ -21,8 +20,9 @@ class QActionGroup; class DolphinView; class KActionCollection; class KFileItemList; -namespace SelectionMode { - class ActionTextHelper; +namespace SelectionMode +{ +class ActionTextHelper; } /** @@ -44,17 +44,17 @@ class DOLPHIN_EXPORT DolphinViewActionHandler : public QObject Q_OBJECT public: - explicit DolphinViewActionHandler(KActionCollection* collection, SelectionMode::ActionTextHelper* actionTextHelper, QObject* parent); + explicit DolphinViewActionHandler(KActionCollection *collection, SelectionMode::ActionTextHelper *actionTextHelper, QObject *parent); /** * Sets the view that this action handler should work on. */ - void setCurrentView(DolphinView* view); + void setCurrentView(DolphinView *view); /** * Returns the view that this action handler should work on. */ - DolphinView* currentView(); + DolphinView *currentView(); /** * Returns the name of the action for the current viewmode @@ -64,7 +64,7 @@ public: /** * Returns m_actionCollection */ - KActionCollection* actionCollection(); + KActionCollection *actionCollection(); public Q_SLOTS: /** @@ -94,7 +94,7 @@ private Q_SLOTS: /** * Emitted when the user requested a change of view mode */ - void slotViewModeActionTriggered(QAction*); + void slotViewModeActionTriggered(QAction *); /** * Let the user input a name for the selected item(s) and trigger @@ -126,7 +126,7 @@ private Q_SLOTS: /** Decreases the size of the current set view mode. */ void zoomOut(); - + /** Resets the size of the current set view mode to default. */ void zoomReset(); @@ -156,7 +156,7 @@ private Q_SLOTS: /** * Updates the state of the 'Sort by' actions. */ - void slotSortRoleChanged(const QByteArray& role); + void slotSortRoleChanged(const QByteArray &role); /** * Updates the state of the 'Zoom In' and 'Zoom Out' actions. @@ -167,18 +167,17 @@ private Q_SLOTS: * Switches on or off the displaying of additional information * as specified by \a action. */ - void toggleVisibleRole(QAction* action); + void toggleVisibleRole(QAction *action); /** * Changes the sorting of the current view. */ - void slotSortTriggered(QAction*); + void slotSortTriggered(QAction *); /** * Updates the state of the 'Additional Information' actions. */ - void slotVisibleRolesChanged(const QList& current, - const QList& previous); + void slotVisibleRolesChanged(const QList ¤t, const QList &previous); /** * Switches between sorting by groups or not. @@ -234,7 +233,7 @@ private Q_SLOTS: * The name is changed to something like "Actions for 3 Selected Items" to be extra * explicit of how these basic actions are used. */ - void slotSelectionChanged(const KFileItemList& selection); + void slotSelectionChanged(const KFileItemList &selection); private: /** @@ -251,31 +250,31 @@ private: * The changes of actions are reported to slotSortTriggered() or * toggleAdditionalInfo(). */ - QActionGroup* createFileItemRolesActionGroup(const QString& groupPrefix); + QActionGroup *createFileItemRolesActionGroup(const QString &groupPrefix); /** * Returns the "switch to icons mode" action. * Helper method for createActions(); */ - KToggleAction* iconsModeAction(); + KToggleAction *iconsModeAction(); /** * Returns the "switch to compact mode" action. * Helper method for createActions(); */ - KToggleAction* compactModeAction(); + KToggleAction *compactModeAction(); /** * Returns the "switch to details mode" action. * Helper method for createActions(); */ - KToggleAction* detailsModeAction(); + KToggleAction *detailsModeAction(); - KActionCollection* m_actionCollection; - DolphinView* m_currentView; + KActionCollection *m_actionCollection; + DolphinView *m_currentView; - QHash m_sortByActions; - QHash m_visibleRoles; + QHash m_sortByActions; + QHash m_visibleRoles; }; #endif /* DOLPHINVIEWACTIONHANDLER_H */ diff --git a/src/views/draganddrophelper.cpp b/src/views/draganddrophelper.cpp index b3f2a4c3e0..aaf2baa383 100644 --- a/src/views/draganddrophelper.cpp +++ b/src/views/draganddrophelper.cpp @@ -17,30 +17,34 @@ QHash DragAndDropHelper::m_urlListMatchesUrlCache; -bool DragAndDropHelper::urlListMatchesUrl(const QList& urls, const QUrl& destUrl) +bool DragAndDropHelper::urlListMatchesUrl(const QList &urls, const QUrl &destUrl) { auto iteratorResult = m_urlListMatchesUrlCache.constFind(destUrl); if (iteratorResult != m_urlListMatchesUrlCache.constEnd()) { return *iteratorResult; } - const bool destUrlMatches = - std::find_if(urls.constBegin(), urls.constEnd(), [destUrl](const QUrl& url) { - return url.matches(destUrl, QUrl::StripTrailingSlash); - }) != urls.constEnd(); + const bool destUrlMatches = std::find_if(urls.constBegin(), + urls.constEnd(), + [destUrl](const QUrl &url) { + return url.matches(destUrl, QUrl::StripTrailingSlash); + }) + != urls.constEnd(); return *m_urlListMatchesUrlCache.insert(destUrl, destUrlMatches); } -KIO::DropJob* DragAndDropHelper::dropUrls(const QUrl& destUrl, QDropEvent* event, QWidget* window) +KIO::DropJob *DragAndDropHelper::dropUrls(const QUrl &destUrl, QDropEvent *event, QWidget *window) { - const QMimeData* mimeData = event->mimeData(); + const QMimeData *mimeData = event->mimeData(); if (isArkDndMimeType(mimeData)) { const QString remoteDBusClient = mimeData->data(arkDndServiceMimeType()); const QString remoteDBusPath = mimeData->data(arkDndPathMimeType()); - QDBusMessage message = QDBusMessage::createMethodCall(remoteDBusClient, remoteDBusPath, - QStringLiteral("org.kde.ark.DndExtract"), QStringLiteral("extractSelectedFilesTo")); + QDBusMessage message = QDBusMessage::createMethodCall(remoteDBusClient, + remoteDBusPath, + QStringLiteral("org.kde.ark.DndExtract"), + QStringLiteral("extractSelectedFilesTo")); message.setArguments({destUrl.toDisplayString(QUrl::PreferLocalFile)}); QDBusConnection::sessionBus().call(message); } else { @@ -64,6 +68,5 @@ void DragAndDropHelper::clearUrlListMatchesUrlCache() bool DragAndDropHelper::isArkDndMimeType(const QMimeData *mimeData) { - return mimeData->hasFormat(arkDndServiceMimeType()) - && mimeData->hasFormat(arkDndPathMimeType()); + return mimeData->hasFormat(arkDndServiceMimeType()) && mimeData->hasFormat(arkDndPathMimeType()); } diff --git a/src/views/draganddrophelper.h b/src/views/draganddrophelper.h index 19a30404e7..656cefe1be 100644 --- a/src/views/draganddrophelper.h +++ b/src/views/draganddrophelper.h @@ -17,7 +17,10 @@ class QDropEvent; class QMimeData; class QWidget; -namespace KIO { class DropJob; } +namespace KIO +{ +class DropJob; +} class DOLPHIN_EXPORT DragAndDropHelper { @@ -35,26 +38,31 @@ public: * @return KIO::DropJob pointer or null in case the destUrl is contained * in the mimeData url list. */ - static KIO::DropJob* dropUrls(const QUrl& destUrl, - QDropEvent* event, - QWidget *window); + static KIO::DropJob *dropUrls(const QUrl &destUrl, QDropEvent *event, QWidget *window); /** * @return True if destUrl is contained in the urls parameter. */ - static bool urlListMatchesUrl(const QList& urls, const QUrl& destUrl); + static bool urlListMatchesUrl(const QList &urls, const QUrl &destUrl); /** * @return True if mimeData contains Ark's drag and drop mime types. */ static bool isArkDndMimeType(const QMimeData *mimeData); - static QString arkDndServiceMimeType() { return QStringLiteral("application/x-kde-ark-dndextract-service"); } - static QString arkDndPathMimeType() { return QStringLiteral("application/x-kde-ark-dndextract-path"); } + static QString arkDndServiceMimeType() + { + return QStringLiteral("application/x-kde-ark-dndextract-service"); + } + static QString arkDndPathMimeType() + { + return QStringLiteral("application/x-kde-ark-dndextract-path"); + } /** * clear the internal cache. */ static void clearUrlListMatchesUrlCache(); + private: /** * Stores the results of the expensive checks made in urlListMatchesUrl. diff --git a/src/views/tooltips/dolphinfilemetadatawidget.cpp b/src/views/tooltips/dolphinfilemetadatawidget.cpp index 80d22d837f..3686b0f185 100644 --- a/src/views/tooltips/dolphinfilemetadatawidget.cpp +++ b/src/views/tooltips/dolphinfilemetadatawidget.cpp @@ -8,10 +8,10 @@ #include "dolphinfilemetadatawidget.h" +#include #include #include #include -#include #include #include @@ -20,11 +20,11 @@ #include #include -DolphinFileMetaDataWidget::DolphinFileMetaDataWidget(QWidget* parent) : - QWidget(parent), - m_preview(nullptr), - m_name(nullptr), - m_fileMetaDataWidget(nullptr) +DolphinFileMetaDataWidget::DolphinFileMetaDataWidget(QWidget *parent) + : QWidget(parent) + , m_preview(nullptr) + , m_name(nullptr) + , m_fileMetaDataWidget(nullptr) { // Create widget for file preview m_preview = new QLabel(this); @@ -45,14 +45,12 @@ DolphinFileMetaDataWidget::DolphinFileMetaDataWidget(QWidget* parent) : // Create widget for the meta data m_fileMetaDataWidget = new Baloo::FileMetaDataWidget(this); - connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::metaDataRequestFinished, - this, &DolphinFileMetaDataWidget::metaDataRequestFinished); - connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::urlActivated, - this, &DolphinFileMetaDataWidget::urlActivated); + connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::metaDataRequestFinished, this, &DolphinFileMetaDataWidget::metaDataRequestFinished); + connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::urlActivated, this, &DolphinFileMetaDataWidget::urlActivated); m_fileMetaDataWidget->setForegroundRole(QPalette::ToolTipText); m_fileMetaDataWidget->setReadOnly(true); - QVBoxLayout* textLayout = new QVBoxLayout(); + QVBoxLayout *textLayout = new QVBoxLayout(); textLayout->addWidget(m_name); textLayout->addWidget(new KSeparator()); textLayout->addWidget(m_fileMetaDataWidget); @@ -64,7 +62,7 @@ DolphinFileMetaDataWidget::DolphinFileMetaDataWidget(QWidget* parent) : // (see bug #241608) textLayout->addStretch(); - QHBoxLayout* layout = new QHBoxLayout(this); + QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(m_preview); layout->addSpacing(layout->contentsMargins().left()); layout->addLayout(textLayout); @@ -74,7 +72,7 @@ DolphinFileMetaDataWidget::~DolphinFileMetaDataWidget() { } -void DolphinFileMetaDataWidget::setPreview(const QPixmap& pixmap) +void DolphinFileMetaDataWidget::setPreview(const QPixmap &pixmap) { m_preview->setPixmap(pixmap); } @@ -88,7 +86,7 @@ QPixmap DolphinFileMetaDataWidget::preview() const return QPixmap(); } -void DolphinFileMetaDataWidget::setName(const QString& name) +void DolphinFileMetaDataWidget::setName(const QString &name) { QTextOption textOption; textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); @@ -124,7 +122,7 @@ QString DolphinFileMetaDataWidget::name() const return m_name->text(); } -void DolphinFileMetaDataWidget::setItems(const KFileItemList& items) +void DolphinFileMetaDataWidget::setItems(const KFileItemList &items) { m_fileMetaDataWidget->setItems(items); } @@ -133,4 +131,3 @@ KFileItemList DolphinFileMetaDataWidget::items() const { return m_fileMetaDataWidget->items(); } - diff --git a/src/views/tooltips/dolphinfilemetadatawidget.h b/src/views/tooltips/dolphinfilemetadatawidget.h index 63bd8b0938..89f9474986 100644 --- a/src/views/tooltips/dolphinfilemetadatawidget.h +++ b/src/views/tooltips/dolphinfilemetadatawidget.h @@ -16,8 +16,9 @@ class KFileItemList; class QLabel; -namespace Baloo { - class FileMetaDataWidget; +namespace Baloo +{ +class FileMetaDataWidget; } /** @@ -29,13 +30,13 @@ class DolphinFileMetaDataWidget : public QWidget Q_OBJECT public: - explicit DolphinFileMetaDataWidget(QWidget* parent = nullptr); + explicit DolphinFileMetaDataWidget(QWidget *parent = nullptr); ~DolphinFileMetaDataWidget() override; - void setPreview(const QPixmap& pixmap); + void setPreview(const QPixmap &pixmap); QPixmap preview() const; - void setName(const QString& name); + void setName(const QString &name); QString name() const; /** @@ -43,7 +44,7 @@ public: * The signal metaDataRequestFinished() will be emitted, * as soon as the meta data for the items has been received. */ - void setItems(const KFileItemList& items); + void setItems(const KFileItemList &items); KFileItemList items() const; Q_SIGNALS: @@ -51,18 +52,18 @@ Q_SIGNALS: * Is emitted after the meta data has been received for the items * set by DolphinFileMetaDataWidget::setItems(). */ - void metaDataRequestFinished(const KFileItemList& items); + void metaDataRequestFinished(const KFileItemList &items); /** * Is emitted when the user clicks a tag or a link * in the metadata widget. */ - void urlActivated(const QUrl& url); + void urlActivated(const QUrl &url); private: - QLabel* m_preview; - QLabel* m_name; - Baloo::FileMetaDataWidget* m_fileMetaDataWidget; + QLabel *m_preview; + QLabel *m_name; + Baloo::FileMetaDataWidget *m_fileMetaDataWidget; }; #endif diff --git a/src/views/tooltips/tooltipmanager.cpp b/src/views/tooltips/tooltipmanager.cpp index 5a40d1023c..c9d22eedf2 100644 --- a/src/views/tooltips/tooltipmanager.cpp +++ b/src/views/tooltips/tooltipmanager.cpp @@ -8,19 +8,20 @@ #include "dolphinfilemetadatawidget.h" -#include #include +#include +#include #include #include #include -#include #include #include #include #include -class IconLoaderSingleton { +class IconLoaderSingleton +{ public: IconLoaderSingleton() = default; @@ -29,17 +30,17 @@ public: Q_GLOBAL_STATIC(IconLoaderSingleton, iconLoader) -ToolTipManager::ToolTipManager(QWidget* parent) : - QObject(parent), - m_showToolTipTimer(nullptr), - m_contentRetrievalTimer(nullptr), - m_transientParent(nullptr), - m_toolTipRequested(false), - m_metaDataRequested(false), - m_appliedWaitCursor(false), - m_margin(4), - m_item(), - m_itemRect() +ToolTipManager::ToolTipManager(QWidget *parent) + : QObject(parent) + , m_showToolTipTimer(nullptr) + , m_contentRetrievalTimer(nullptr) + , m_transientParent(nullptr) + , m_toolTipRequested(false) + , m_metaDataRequested(false) + , m_appliedWaitCursor(false) + , m_margin(4) + , m_item() + , m_itemRect() { if (parent) { m_margin = qMax(m_margin, parent->style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth)); @@ -65,7 +66,7 @@ ToolTipManager::~ToolTipManager() } } -void ToolTipManager::showToolTip(const KFileItem& item, const QRectF& itemRect, QWindow *transientParent) +void ToolTipManager::showToolTip(const KFileItem &item, const QRectF &itemRect, QWindow *transientParent) { hideToolTip(HideBehavior::Instantly); @@ -134,23 +135,17 @@ void ToolTipManager::startContentRetrieval() const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings"); const QStringList plugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins()); - KIO::PreviewJob* job = new KIO::PreviewJob(KFileItemList() << m_item, - QSize(256, 256), - &plugins); + KIO::PreviewJob *job = new KIO::PreviewJob(KFileItemList() << m_item, QSize(256, 256), &plugins); job->setIgnoreMaximumSize(m_item.isLocalFile() && !m_item.isSlow()); if (job->uiDelegate()) { KJobWidgets::setWindow(job, qApp->activeWindow()); } - connect(job, &KIO::PreviewJob::gotPreview, - this, &ToolTipManager::setPreviewPix); - connect(job, &KIO::PreviewJob::failed, - this, &ToolTipManager::previewFailed); + connect(job, &KIO::PreviewJob::gotPreview, this, &ToolTipManager::setPreviewPix); + connect(job, &KIO::PreviewJob::failed, this, &ToolTipManager::previewFailed); } - -void ToolTipManager::setPreviewPix(const KFileItem& item, - const QPixmap& pixmap) +void ToolTipManager::setPreviewPix(const KFileItem &item, const QPixmap &pixmap) { if (!m_toolTipRequested || (m_item.url() != item.url())) { // No tooltip is requested anymore or an old preview has been received @@ -173,7 +168,7 @@ void ToolTipManager::previewFailed() return; } QPalette pal; - for (auto state : { QPalette::Active, QPalette::Inactive, QPalette::Disabled }) { + for (auto state : {QPalette::Active, QPalette::Inactive, QPalette::Disabled}) { pal.setBrush(state, QPalette::WindowText, pal.toolTipText()); pal.setBrush(state, QPalette::Window, pal.toolTipBase()); } @@ -224,4 +219,3 @@ void ToolTipManager::showToolTip() m_toolTipRequested = false; } - diff --git a/src/views/tooltips/tooltipmanager.h b/src/views/tooltips/tooltipmanager.h index c86c97f6bc..9aee295ffc 100644 --- a/src/views/tooltips/tooltipmanager.h +++ b/src/views/tooltips/tooltipmanager.h @@ -29,12 +29,9 @@ class ToolTipManager : public QObject Q_OBJECT public: - enum class HideBehavior { - Instantly, - Later - }; + enum class HideBehavior { Instantly, Later }; - explicit ToolTipManager(QWidget* parent); + explicit ToolTipManager(QWidget *parent); ~ToolTipManager() override; /** @@ -43,7 +40,7 @@ public: * The tooltip manager takes care that the tooltip is shown * slightly delayed and with a proper \p transientParent. */ - void showToolTip(const KFileItem& item, const QRectF& itemRect, QWindow *transientParent); + void showToolTip(const KFileItem &item, const QRectF &itemRect, QWindow *transientParent); /** * Hides the currently shown tooltip. @@ -55,11 +52,11 @@ Q_SIGNALS: * Is emitted when the user clicks a tag or a link * in the metadata widget. */ - void urlActivated(const QUrl& url); + void urlActivated(const QUrl &url); private Q_SLOTS: void startContentRetrieval(); - void setPreviewPix(const KFileItem& item, const QPixmap& pix); + void setPreviewPix(const KFileItem &item, const QPixmap &pix); void previewFailed(); void slotMetaDataRequestFinished(); void showToolTip(); @@ -67,14 +64,14 @@ private Q_SLOTS: private: /// Timeout from requesting a tooltip until the tooltip /// should be shown - QTimer* m_showToolTipTimer; + QTimer *m_showToolTipTimer; /// Timeout from requesting a tooltip until the retrieving of /// the tooltip content like preview and meta data gets started. - QTimer* m_contentRetrievalTimer; + QTimer *m_contentRetrievalTimer; /// Transient parent of the tooltip, mandatory on Wayland. - QWindow* m_transientParent; + QWindow *m_transientParent; QScopedPointer m_tooltipWidget; DolphinFileMetaDataWidget *m_fileMetaDataWidget = nullptr; diff --git a/src/views/versioncontrol/kversioncontrolplugin.cpp b/src/views/versioncontrol/kversioncontrolplugin.cpp index 9cbf0eb5b6..0190bb365e 100644 --- a/src/views/versioncontrol/kversioncontrolplugin.cpp +++ b/src/views/versioncontrol/kversioncontrolplugin.cpp @@ -7,8 +7,8 @@ #include "kversioncontrolplugin.h" -KVersionControlPlugin::KVersionControlPlugin(QObject* parent) : - QObject(parent) +KVersionControlPlugin::KVersionControlPlugin(QObject *parent) + : QObject(parent) { } @@ -16,7 +16,7 @@ KVersionControlPlugin::~KVersionControlPlugin() { } -QString KVersionControlPlugin::localRepositoryRoot(const QString &/*directory*/) const +QString KVersionControlPlugin::localRepositoryRoot(const QString & /*directory*/) const { return QString(); } diff --git a/src/views/versioncontrol/kversioncontrolplugin.h b/src/views/versioncontrol/kversioncontrolplugin.h index d3a39fbd6b..1a41114528 100644 --- a/src/views/versioncontrol/kversioncontrolplugin.h +++ b/src/views/versioncontrol/kversioncontrolplugin.h @@ -73,8 +73,7 @@ class DOLPHINVCS_EXPORT KVersionControlPlugin : public QObject Q_OBJECT public: - enum ItemVersion - { + enum ItemVersion { /** The file is not under version control. */ UnversionedVersion, /** @@ -131,7 +130,7 @@ public: MissingVersion }; - KVersionControlPlugin(QObject* parent = nullptr); + KVersionControlPlugin(QObject *parent = nullptr); ~KVersionControlPlugin() override; /** @@ -145,7 +144,7 @@ public: * Returns the path of the local repository root for the versioned directory * Returns an empty QString when directory is not part of a working copy */ - virtual QString localRepositoryRoot(const QString& directory) const; + virtual QString localRepositoryRoot(const QString &directory) const; /** * Is invoked whenever the version control @@ -153,7 +152,7 @@ public: * \p directory. It is assured that the directory * contains a trailing slash. */ - virtual bool beginRetrieval(const QString& directory) = 0; + virtual bool beginRetrieval(const QString &directory) = 0; /** * Is invoked after the version control information has been @@ -169,13 +168,13 @@ public: * invoked before and that the file is part of the directory specified * in beginRetrieval(). */ - virtual ItemVersion itemVersion(const KFileItem& item) const = 0; + virtual ItemVersion itemVersion(const KFileItem &item) const = 0; /** * @return List of actions that are available for the \p items in a version controlled * path. */ - virtual QList versionControlActions(const KFileItemList& items) const = 0; + virtual QList versionControlActions(const KFileItemList &items) const = 0; /** * @return List of actions that are available for the out of version control @@ -183,7 +182,7 @@ public: * is for clone/checkout actions. * @since 21.04 */ - virtual QList outOfVersionControlActions(const KFileItemList& items) const = 0; + virtual QList outOfVersionControlActions(const KFileItemList &items) const = 0; Q_SIGNALS: /** @@ -201,20 +200,19 @@ Q_SIGNALS: * Is emitted if an information message with the content \a msg * should be shown. */ - void infoMessage(const QString& msg); + void infoMessage(const QString &msg); /** * Is emitted if an error message with the content \a msg * should be shown. */ - void errorMessage(const QString& msg); + void errorMessage(const QString &msg); /** * Is emitted if an "operation completed" message with the content \a msg * should be shown. */ - void operationCompletedMessage(const QString& msg); + void operationCompletedMessage(const QString &msg); }; #endif // KVERSIONCONTROLPLUGIN_H - diff --git a/src/views/versioncontrol/updateitemstatesthread.cpp b/src/views/versioncontrol/updateitemstatesthread.cpp index cf45bbff16..37c36f40c9 100644 --- a/src/views/versioncontrol/updateitemstatesthread.cpp +++ b/src/views/versioncontrol/updateitemstatesthread.cpp @@ -6,13 +6,11 @@ #include "updateitemstatesthread.h" - -UpdateItemStatesThread::UpdateItemStatesThread(KVersionControlPlugin* plugin, - const QMap >& itemStates) : - QThread(), - m_globalPluginMutex(nullptr), - m_plugin(plugin), - m_itemStates(itemStates) +UpdateItemStatesThread::UpdateItemStatesThread(KVersionControlPlugin *plugin, const QMap> &itemStates) + : QThread() + , m_globalPluginMutex(nullptr) + , m_plugin(plugin) + , m_itemStates(itemStates) { // Several threads may share one instance of a plugin. A global // mutex is required to serialize the retrieval of version control @@ -31,13 +29,13 @@ void UpdateItemStatesThread::run() Q_ASSERT(m_plugin); QMutexLocker pluginLocker(m_globalPluginMutex); - QMap >::iterator it = m_itemStates.begin(); + QMap>::iterator it = m_itemStates.begin(); for (; it != m_itemStates.end(); ++it) { if (m_plugin->beginRetrieval(it.key())) { - QVector& items = it.value(); + QVector &items = it.value(); const int count = items.count(); for (int i = 0; i < count; ++i) { - const KFileItem& item = items.at(i).first; + const KFileItem &item = items.at(i).first; const KVersionControlPlugin::ItemVersion version = m_plugin->itemVersion(item); items[i].second = version; } @@ -47,8 +45,7 @@ void UpdateItemStatesThread::run() } } -QMap > UpdateItemStatesThread::itemStates() const +QMap> UpdateItemStatesThread::itemStates() const { return m_itemStates; } - diff --git a/src/views/versioncontrol/updateitemstatesthread.h b/src/views/versioncontrol/updateitemstatesthread.h index eac28bb78c..24f060d266 100644 --- a/src/views/versioncontrol/updateitemstatesthread.h +++ b/src/views/versioncontrol/updateitemstatesthread.h @@ -31,20 +31,19 @@ public: * UpdateItemStatesThread::unlockPlugin() must be used. * @param itemStates List of items, where the states get updated. */ - UpdateItemStatesThread(KVersionControlPlugin* plugin, - const QMap >& itemStates); + UpdateItemStatesThread(KVersionControlPlugin *plugin, const QMap> &itemStates); ~UpdateItemStatesThread() override; - QMap > itemStates() const; + QMap> itemStates() const; protected: void run() override; private: - QMutex* m_globalPluginMutex; // Protects the m_plugin globally - KVersionControlPlugin* m_plugin; + QMutex *m_globalPluginMutex; // Protects the m_plugin globally + KVersionControlPlugin *m_plugin; - QMap > m_itemStates; + QMap> m_itemStates; }; #endif // UPDATEITEMSTATESTHREAD_H diff --git a/src/views/versioncontrol/versioncontrolobserver.cpp b/src/views/versioncontrol/versioncontrolobserver.cpp index e0505675ac..28fbbef1a4 100644 --- a/src/views/versioncontrol/versioncontrolobserver.cpp +++ b/src/views/versioncontrol/versioncontrolobserver.cpp @@ -8,9 +8,9 @@ #include "dolphin_versioncontrolsettings.h" #include "dolphindebug.h" -#include "views/dolphinview.h" #include "kitemviews/kfileitemmodel.h" #include "updateitemstatesthread.h" +#include "views/dolphinview.h" #include #include @@ -18,16 +18,16 @@ #include -VersionControlObserver::VersionControlObserver(QObject* parent) : - QObject(parent), - m_pendingItemStatesUpdate(false), - m_silentUpdate(false), - m_view(nullptr), - m_model(nullptr), - m_dirVerificationTimer(nullptr), - m_pluginsInitialized(false), - m_plugin(nullptr), - m_updateItemStatesThread(nullptr) +VersionControlObserver::VersionControlObserver(QObject *parent) + : QObject(parent) + , m_pendingItemStatesUpdate(false) + , m_silentUpdate(false) + , m_view(nullptr) + , m_model(nullptr) + , m_dirVerificationTimer(nullptr) + , m_pluginsInitialized(false) + , m_plugin(nullptr) + , m_updateItemStatesThread(nullptr) { // The verification timer specifies the timeout until the shown directory // is checked whether it is versioned. Per default it is assumed that users @@ -37,8 +37,7 @@ VersionControlObserver::VersionControlObserver(QObject* parent) : m_dirVerificationTimer = new QTimer(this); m_dirVerificationTimer->setSingleShot(true); m_dirVerificationTimer->setInterval(500); - connect(m_dirVerificationTimer, &QTimer::timeout, - this, &VersionControlObserver::verifyDirectory); + connect(m_dirVerificationTimer, &QTimer::timeout, this, &VersionControlObserver::verifyDirectory); } VersionControlObserver::~VersionControlObserver() @@ -49,54 +48,48 @@ VersionControlObserver::~VersionControlObserver() } } -void VersionControlObserver::setModel(KFileItemModel* model) +void VersionControlObserver::setModel(KFileItemModel *model) { if (m_model) { - disconnect(m_model, &KFileItemModel::itemsInserted, - this, &VersionControlObserver::delayedDirectoryVerification); - disconnect(m_model, &KFileItemModel::itemsChanged, - this, &VersionControlObserver::slotItemsChanged); + disconnect(m_model, &KFileItemModel::itemsInserted, this, &VersionControlObserver::delayedDirectoryVerification); + disconnect(m_model, &KFileItemModel::itemsChanged, this, &VersionControlObserver::slotItemsChanged); } m_model = model; if (model) { - connect(m_model, &KFileItemModel::itemsInserted, - this, &VersionControlObserver::delayedDirectoryVerification); - connect(m_model, &KFileItemModel::itemsChanged, - this, &VersionControlObserver::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsInserted, this, &VersionControlObserver::delayedDirectoryVerification); + connect(m_model, &KFileItemModel::itemsChanged, this, &VersionControlObserver::slotItemsChanged); } } -KFileItemModel* VersionControlObserver::model() const +KFileItemModel *VersionControlObserver::model() const { return m_model; } -void VersionControlObserver::setView(DolphinView* view) +void VersionControlObserver::setView(DolphinView *view) { if (m_view) { - disconnect(m_view, &DolphinView::activated, - this, &VersionControlObserver::delayedDirectoryVerification); + disconnect(m_view, &DolphinView::activated, this, &VersionControlObserver::delayedDirectoryVerification); } m_view = view; if (m_view) { - connect(m_view, &DolphinView::activated, - this, &VersionControlObserver::delayedDirectoryVerification); + connect(m_view, &DolphinView::activated, this, &VersionControlObserver::delayedDirectoryVerification); } } -DolphinView* VersionControlObserver::view() const +DolphinView *VersionControlObserver::view() const { return m_view; } -QList VersionControlObserver::actions(const KFileItemList& items) const +QList VersionControlObserver::actions(const KFileItemList &items) const { bool hasNullItems = false; - for (const KFileItem& item : items) { + for (const KFileItem &item : items) { if (item.isNull()) { qCWarning(DolphinDebug) << "Requesting version-control-actions for empty items"; hasNullItems = true; @@ -111,7 +104,7 @@ QList VersionControlObserver::actions(const KFileItemList& items) cons if (isVersionControlled()) { return m_plugin->versionControlActions(items); } else { - QList actions; + QList actions; for (const QPointer &plugin : qAsConst(m_plugins)) { actions << plugin->outOfVersionControlActions(items); } @@ -131,14 +124,14 @@ void VersionControlObserver::silentDirectoryVerification() m_dirVerificationTimer->start(); } -void VersionControlObserver::slotItemsChanged(const KItemRangeList& itemRanges, const QSet& roles) +void VersionControlObserver::slotItemsChanged(const KItemRangeList &itemRanges, const QSet &roles) { Q_UNUSED(itemRanges) // Because "version" role is emitted by VCS plugin (ourselves) we don't need to // analyze it and update directory item states information. So lets check if // there is only "version". - if ( !(roles.count() == 1 && roles.contains("version")) ) { + if (!(roles.count() == 1 && roles.contains("version"))) { delayedDirectoryVerification(); } } @@ -176,20 +169,20 @@ void VersionControlObserver::verifyDirectory() void VersionControlObserver::slotThreadFinished() { - UpdateItemStatesThread* thread = m_updateItemStatesThread; + UpdateItemStatesThread *thread = m_updateItemStatesThread; m_updateItemStatesThread = nullptr; // The thread deletes itself automatically (see updateItemStates()) if (!m_plugin || !thread) { return; } - const QMap >& itemStates = thread->itemStates(); - QMap >::const_iterator it = itemStates.constBegin(); + const QMap> &itemStates = thread->itemStates(); + QMap>::const_iterator it = itemStates.constBegin(); for (; it != itemStates.constEnd(); ++it) { - const QVector& items = it.value(); + const QVector &items = it.value(); - for (const ItemState& item : items) { - const KFileItem& fileItem = item.first; + for (const ItemState &item : items) { + const KFileItem &fileItem = item.first; const KVersionControlPlugin::ItemVersion version = item.second; QHash values; values.insert("version", QVariant(version)); @@ -220,7 +213,7 @@ void VersionControlObserver::updateItemStates() return; } - QMap > itemStates; + QMap> itemStates; createItemStatesList(itemStates); if (!itemStates.isEmpty()) { @@ -228,17 +221,14 @@ void VersionControlObserver::updateItemStates() Q_EMIT infoMessage(i18nc("@info:status", "Updating version information...")); } m_updateItemStatesThread = new UpdateItemStatesThread(m_plugin, itemStates); - connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished, - this, &VersionControlObserver::slotThreadFinished); - connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished, - m_updateItemStatesThread, &UpdateItemStatesThread::deleteLater); + connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished, this, &VersionControlObserver::slotThreadFinished); + connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished, m_updateItemStatesThread, &UpdateItemStatesThread::deleteLater); m_updateItemStatesThread->start(); // slotThreadFinished() is called when finished } } -int VersionControlObserver::createItemStatesList(QMap >& itemStates, - const int firstIndex) +int VersionControlObserver::createItemStatesList(QMap> &itemStates, const int firstIndex) { const int itemCount = m_model->count(); const int currentExpansionLevel = m_model->expandedParentsCount(firstIndex); @@ -265,7 +255,7 @@ int VersionControlObserver::createItemStatesList(QMap actions(const KFileItemList& items) const; + QList actions(const KFileItemList &items) const; Q_SIGNALS: /** * Is emitted if an information message with the content \a msg * should be shown. */ - void infoMessage(const QString& msg); + void infoMessage(const QString &msg); /** * Is emitted if an error message with the content \a msg * should be shown. */ - void errorMessage(const QString& msg); + void errorMessage(const QString &msg); /** * Is emitted if an "operation completed" message with the content \a msg * should be shown. */ - void operationCompletedMessage(const QString& msg); + void operationCompletedMessage(const QString &msg); private Q_SLOTS: /** @@ -89,7 +89,7 @@ private Q_SLOTS: * Invokes delayedDirectoryVerification() only if the itemsChanged() signal has not * been triggered by the VCS plugin itself. */ - void slotItemsChanged(const KItemRangeList& itemRanges, const QSet& roles); + void slotItemsChanged(const KItemRangeList &itemRanges, const QSet &roles); void verifyDirectory(); @@ -117,14 +117,13 @@ private: * * @return The number of (recursive) processed items. */ - int createItemStatesList(QMap >& itemStates, - const int firstIndex = 0); + int createItemStatesList(QMap> &itemStates, const int firstIndex = 0); /** * Returns a matching plugin for the given directory. * 0 is returned, if no matching plugin has been found. */ - KVersionControlPlugin* searchPlugin(const QUrl& directory); + KVersionControlPlugin *searchPlugin(const QUrl &directory); /** * Returns true, if the directory contains a version control information. @@ -139,18 +138,17 @@ private: // of version states QString m_localRepoRoot; - DolphinView* m_view; - KFileItemModel* m_model; + DolphinView *m_view; + KFileItemModel *m_model; - QTimer* m_dirVerificationTimer; + QTimer *m_dirVerificationTimer; bool m_pluginsInitialized; - KVersionControlPlugin* m_plugin; + KVersionControlPlugin *m_plugin; QList> m_plugins; - UpdateItemStatesThread* m_updateItemStatesThread; + UpdateItemStatesThread *m_updateItemStatesThread; friend class UpdateItemStatesThread; }; #endif // REVISIONCONTROLOBSERVER_H - diff --git a/src/views/viewmodecontroller.cpp b/src/views/viewmodecontroller.cpp index 4bdd8321a2..55be625d7e 100644 --- a/src/views/viewmodecontroller.cpp +++ b/src/views/viewmodecontroller.cpp @@ -8,11 +8,11 @@ #include "zoomlevelinfo.h" -ViewModeController::ViewModeController(QObject* parent) : - QObject(parent), - m_zoomLevel(0), - m_nameFilter(), - m_url() +ViewModeController::ViewModeController(QObject *parent) + : QObject(parent) + , m_zoomLevel(0) + , m_nameFilter() + , m_url() { } @@ -25,7 +25,7 @@ QUrl ViewModeController::url() const return m_url; } -void ViewModeController::redirectToUrl(const QUrl& url) +void ViewModeController::redirectToUrl(const QUrl &url) { m_url = url; } @@ -35,7 +35,7 @@ void ViewModeController::indicateActivationChange(bool active) Q_EMIT activationChanged(active); } -void ViewModeController::setNameFilter(const QString& nameFilter) +void ViewModeController::setNameFilter(const QString &nameFilter) { if (nameFilter != m_nameFilter) { m_nameFilter = nameFilter; @@ -63,7 +63,7 @@ int ViewModeController::zoomLevel() const return m_zoomLevel; } -void ViewModeController::setUrl(const QUrl& url) +void ViewModeController::setUrl(const QUrl &url) { if (m_url != url) { m_url = url; @@ -71,4 +71,3 @@ void ViewModeController::setUrl(const QUrl& url) Q_EMIT urlChanged(url); } } - diff --git a/src/views/viewmodecontroller.h b/src/views/viewmodecontroller.h index bd92a60a24..3aebf16380 100644 --- a/src/views/viewmodecontroller.h +++ b/src/views/viewmodecontroller.h @@ -26,7 +26,7 @@ class DOLPHIN_EXPORT ViewModeController : public QObject Q_OBJECT public: - explicit ViewModeController(QObject* parent = nullptr); + explicit ViewModeController(QObject *parent = nullptr); ~ViewModeController() override; /** @@ -38,7 +38,7 @@ public: * Sets the URL to \a url and does nothing else. Called when * a redirection happens. See ViewModeController::setUrl() */ - void redirectToUrl(const QUrl& url); + void redirectToUrl(const QUrl &url); /** * Informs the view mode implementation about a change of the activation @@ -58,7 +58,7 @@ public: /** * Sets the name filter to \a and emits the signal nameFilterChanged(). */ - void setNameFilter(const QString& nameFilter); + void setNameFilter(const QString &nameFilter); QString nameFilter() const; public Q_SLOTS: @@ -66,13 +66,13 @@ public Q_SLOTS: * Sets the URL to \a url and emits the signals cancelPreviews() and * urlChanged() if \a url is different for the current URL. */ - void setUrl(const QUrl& url); + void setUrl(const QUrl &url); Q_SIGNALS: /** * Is emitted if the URL has been changed by ViewModeController::setUrl(). */ - void urlChanged(const QUrl& url); + void urlChanged(const QUrl &url); /** * Is emitted, if ViewModeController::indicateActivationChange() has been @@ -85,7 +85,7 @@ Q_SIGNALS: * Is emitted if the name filter has been changed by * ViewModeController::setNameFilter(). */ - void nameFilterChanged(const QString& nameFilter); + void nameFilterChanged(const QString &nameFilter); /** * Is emitted if the zoom level has been changed by diff --git a/src/views/viewproperties.cpp b/src/views/viewproperties.cpp index e6dbcd8117..f42adbce7a 100644 --- a/src/views/viewproperties.cpp +++ b/src/views/viewproperties.cpp @@ -15,27 +15,28 @@ #include -namespace { - const int AdditionalInfoViewPropertiesVersion = 1; - const int NameRolePropertiesVersion = 2; - const int DateRolePropertiesVersion = 4; - const int CurrentViewPropertiesVersion = 4; +namespace +{ +const int AdditionalInfoViewPropertiesVersion = 1; +const int NameRolePropertiesVersion = 2; +const int DateRolePropertiesVersion = 4; +const int CurrentViewPropertiesVersion = 4; - // String representation to mark the additional properties of - // the details view as customized by the user. See - // ViewProperties::visibleRoles() for more information. - const char CustomizedDetailsString[] = "CustomizedDetails"; +// String representation to mark the additional properties of +// the details view as customized by the user. See +// ViewProperties::visibleRoles() for more information. +const char CustomizedDetailsString[] = "CustomizedDetails"; - // Filename that is used for storing the properties - const char ViewPropertiesFileName[] = ".directory"; +// Filename that is used for storing the properties +const char ViewPropertiesFileName[] = ".directory"; } -ViewProperties::ViewProperties(const QUrl& url) : - m_changedProps(false), - m_autoSave(true), - m_node(nullptr) +ViewProperties::ViewProperties(const QUrl &url) + : m_changedProps(false) + , m_autoSave(true) + , m_node(nullptr) { - GeneralSettings* settings = GeneralSettings::self(); + GeneralSettings *settings = GeneralSettings::self(); const bool useGlobalViewProps = settings->globalViewProps() || url.isEmpty(); bool useSearchView = false; bool useTrashView = false; @@ -78,10 +79,10 @@ ViewProperties::ViewProperties(const QUrl& url) : } if (useDestinationDir) { - #ifdef Q_OS_WIN +#ifdef Q_OS_WIN // m_filePath probably begins with C:/ - the colon is not a valid character for paths though - m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':')); - #endif + m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':')); +#endif m_filePath = destinationDir(QStringLiteral("local")) + m_filePath; } @@ -97,9 +98,8 @@ ViewProperties::ViewProperties(const QUrl& url) : // If the .directory file does not exist or the timestamp is too old, // use default values instead. - const bool useDefaultProps = (!useGlobalViewProps || useSearchView || useTrashView || useRecentDocumentsView || useDownloadsView) && - (!QFile::exists(file) || - (m_node->timestamp() < settings->viewPropsTimestamp())); + const bool useDefaultProps = (!useGlobalViewProps || useSearchView || useTrashView || useRecentDocumentsView || useDownloadsView) + && (!QFile::exists(file) || (m_node->timestamp() < settings->viewPropsTimestamp())); if (useDefaultProps) { if (useSearchView) { const QString path = url.path(); @@ -134,7 +134,7 @@ ViewProperties::ViewProperties(const QUrl& url) : } } else { // The global view-properties act as default for directories without - // any view-property configuration. Constructing a ViewProperties + // any view-property configuration. Constructing a ViewProperties // instance for an empty QUrl ensures that the global view-properties // are loaded. QUrl emptyUrl; @@ -230,7 +230,7 @@ bool ViewProperties::hiddenFilesShown() const return m_node->hiddenFilesShown(); } -void ViewProperties::setSortRole(const QByteArray& role) +void ViewProperties::setSortRole(const QByteArray &role) { if (m_node->sortRole() != role) { m_node->setSortRole(role); @@ -282,7 +282,7 @@ bool ViewProperties::sortHiddenLast() const return m_node->sortHiddenLast(); } -void ViewProperties::setVisibleRoles(const QList& roles) +void ViewProperties::setVisibleRoles(const QList &roles) { if (roles == visibleRoles()) { return; @@ -303,13 +303,12 @@ void ViewProperties::setVisibleRoles(const QList& roles) // Add the updated values for the current view-mode newVisibleRoles.reserve(roles.count()); - for (const QByteArray& role : roles) { + for (const QByteArray &role : roles) { newVisibleRoles.append(prefix + role); } if (oldVisibleRoles != newVisibleRoles) { - const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView) - && !newVisibleRoles.contains(CustomizedDetailsString); + const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView) && !newVisibleRoles.contains(CustomizedDetailsString); if (markCustomizedDetails) { // The additional information of the details-view has been modified. Set a marker, // so that it is allowed to also show no additional information without doing the @@ -346,7 +345,7 @@ QList ViewProperties::visibleRoles() const const int prefixLength = prefix.length(); const QStringList visibleRoles = m_node->visibleRoles(); - for (const QString& visibleRole : visibleRoles) { + for (const QString &visibleRole : visibleRoles) { if (visibleRole.startsWith(prefix)) { const QByteArray role = visibleRole.right(visibleRole.length() - prefixLength).toLatin1(); if (role != "text") { @@ -358,8 +357,7 @@ QList ViewProperties::visibleRoles() const // For the details view the size and date should be shown per default // until the additional information has been explicitly changed by the user const bool useDefaultValues = roles.count() == 1 // "text" - && (m_node->viewMode() == DolphinView::DetailsView) - && !visibleRoles.contains(CustomizedDetailsString); + && (m_node->viewMode() == DolphinView::DetailsView) && !visibleRoles.contains(CustomizedDetailsString); if (useDefaultValues) { roles.append("size"); roles.append("modificationtime"); @@ -368,7 +366,7 @@ QList ViewProperties::visibleRoles() const return roles; } -void ViewProperties::setHeaderColumnWidths(const QList& widths) +void ViewProperties::setHeaderColumnWidths(const QList &widths) { if (m_node->headerColumnWidths() != widths) { m_node->setHeaderColumnWidths(widths); @@ -381,7 +379,7 @@ QList ViewProperties::headerColumnWidths() const return m_node->headerColumnWidths(); } -void ViewProperties::setDirProperties(const ViewProperties& props) +void ViewProperties::setDirProperties(const ViewProperties &props) { setViewMode(props.viewMode()); setPreviewsShown(props.previewsShown()); @@ -428,7 +426,7 @@ bool ViewProperties::exist() const return QFile::exists(file); } -QString ViewProperties::destinationDir(const QString& subDir) const +QString ViewProperties::destinationDir(const QString &subDir) const { QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); path.append("/view_properties/").append(subDir); @@ -440,10 +438,17 @@ QString ViewProperties::viewModePrefix() const QString prefix; switch (m_node->viewMode()) { - case DolphinView::IconsView: prefix = QStringLiteral("Icons_"); break; - case DolphinView::CompactView: prefix = QStringLiteral("Compact_"); break; - case DolphinView::DetailsView: prefix = QStringLiteral("Details_"); break; - default: qCWarning(DolphinDebug) << "Unknown view-mode of the view properties"; + case DolphinView::IconsView: + prefix = QStringLiteral("Icons_"); + break; + case DolphinView::CompactView: + prefix = QStringLiteral("Compact_"); + break; + case DolphinView::DetailsView: + prefix = QStringLiteral("Details_"); + break; + default: + qCWarning(DolphinDebug) << "Unknown view-mode of the view properties"; } return prefix; @@ -460,7 +465,7 @@ void ViewProperties::convertAdditionalInfo() // the internal role. One special-case must be handled: "LinkDestination" // has been used for "destination". visibleRoles.reserve(visibleRoles.count() + additionalInfo.count()); - for (const QString& info : additionalInfo) { + for (const QString &info : additionalInfo) { QString visibleRole = info; int index = visibleRole.indexOf('_'); if (index >= 0 && index + 1 < visibleRole.length()) { @@ -525,7 +530,7 @@ void ViewProperties::convertDateRoleToModificationTimeRole() update(); } -bool ViewProperties::isPartOfHome(const QString& filePath) +bool ViewProperties::isPartOfHome(const QString &filePath) { // For performance reasons cache the path in a static QString // (see QDir::homePath() for more details) @@ -538,7 +543,7 @@ bool ViewProperties::isPartOfHome(const QString& filePath) return filePath.startsWith(homePath); } -QString ViewProperties::directoryHashForUrl(const QUrl& url) +QString ViewProperties::directoryHashForUrl(const QUrl &url) { const QByteArray hashValue = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Sha1); QString hashString = hashValue.toBase64(); diff --git a/src/views/viewproperties.h b/src/views/viewproperties.h index def8aa7381..29827c38b6 100644 --- a/src/views/viewproperties.h +++ b/src/views/viewproperties.h @@ -38,7 +38,7 @@ class ViewPropertySettings; class DOLPHIN_EXPORT ViewProperties { public: - explicit ViewProperties(const QUrl& url); + explicit ViewProperties(const QUrl &url); virtual ~ViewProperties(); void setViewMode(DolphinView::Mode mode); @@ -53,7 +53,7 @@ public: void setGroupedSorting(bool grouped); bool groupedSorting() const; - void setSortRole(const QByteArray& role); + void setSortRole(const QByteArray &role); QByteArray sortRole() const; void setSortOrder(Qt::SortOrder sortOrder); @@ -70,7 +70,7 @@ public: * Note that the additional-info property is the only property where * the value is dependent from another property (in this case the view-mode). */ - void setVisibleRoles(const QList& info); + void setVisibleRoles(const QList &info); /** * Returns the additional information for the current set view-mode. @@ -79,7 +79,7 @@ public: */ QList visibleRoles() const; - void setHeaderColumnWidths(const QList& widths); + void setHeaderColumnWidths(const QList &widths); QList headerColumnWidths() const; /** @@ -87,7 +87,7 @@ public: * show hidden files, sorting and sort order like * set in \a props. */ - void setDirProperties(const ViewProperties& props); + void setDirProperties(const ViewProperties &props); /** * If \a autoSave is true, the properties are automatically @@ -122,7 +122,7 @@ private: * properties are stored. \a subDir specifies the used sub * directory. */ - QString destinationDir(const QString& subDir) const; + QString destinationDir(const QString &subDir) const; /** * Returns the view-mode prefix when storing additional properties for @@ -153,7 +153,7 @@ private: /** * Returns true, if \a filePath is part of the home-path (see QDir::homePath()). */ - static bool isPartOfHome(const QString& filePath); + static bool isPartOfHome(const QString &filePath); /** * @return A hash-value for an URL that can be used as directory name. @@ -167,7 +167,7 @@ private: bool m_changedProps; bool m_autoSave; QString m_filePath; - ViewPropertySettings* m_node; + ViewPropertySettings *m_node; }; #endif diff --git a/src/views/zoomlevelinfo.cpp b/src/views/zoomlevelinfo.cpp index 6e499967a5..2ad8711df1 100644 --- a/src/views/zoomlevelinfo.cpp +++ b/src/views/zoomlevelinfo.cpp @@ -24,26 +24,48 @@ int ZoomLevelInfo::iconSizeForZoomLevel(int level) { int size = KIconLoader::SizeMedium; switch (level) { - case 0: size = KIconLoader::SizeSmall; break; - case 1: size = KIconLoader::SizeSmallMedium; break; - case 2: size = KIconLoader::SizeMedium; break; - case 3: size = KIconLoader::SizeLarge; break; - case 4: size = KIconLoader::SizeHuge; break; - default: size = KIconLoader::SizeHuge + ((level - 4) << 4); + case 0: + size = KIconLoader::SizeSmall; + break; + case 1: + size = KIconLoader::SizeSmallMedium; + break; + case 2: + size = KIconLoader::SizeMedium; + break; + case 3: + size = KIconLoader::SizeLarge; + break; + case 4: + size = KIconLoader::SizeHuge; + break; + default: + size = KIconLoader::SizeHuge + ((level - 4) << 4); } return size; } -int ZoomLevelInfo::zoomLevelForIconSize(const QSize& size) +int ZoomLevelInfo::zoomLevelForIconSize(const QSize &size) { int level = 0; switch (size.height()) { - case KIconLoader::SizeSmall: level = 0; break; - case KIconLoader::SizeSmallMedium: level = 1; break; - case KIconLoader::SizeMedium: level = 2; break; - case KIconLoader::SizeLarge: level = 3; break; - case KIconLoader::SizeHuge: level = 4; break; - default: level = 4 + ((size.height() - KIconLoader::SizeHuge) >> 4); + case KIconLoader::SizeSmall: + level = 0; + break; + case KIconLoader::SizeSmallMedium: + level = 1; + break; + case KIconLoader::SizeMedium: + level = 2; + break; + case KIconLoader::SizeLarge: + level = 3; + break; + case KIconLoader::SizeHuge: + level = 4; + break; + default: + level = 4 + ((size.height() - KIconLoader::SizeHuge) >> 4); } return level; } diff --git a/src/views/zoomlevelinfo.h b/src/views/zoomlevelinfo.h index 9565848261..2d444eaf0a 100644 --- a/src/views/zoomlevelinfo.h +++ b/src/views/zoomlevelinfo.h @@ -13,7 +13,8 @@ class QSize; * @short Helper class for getting information about the zooming * capabilities. */ -class ZoomLevelInfo { +class ZoomLevelInfo +{ public: static int minimumLevel(); static int maximumLevel(); @@ -32,7 +33,7 @@ public: * is between the range ZoomLevelInfo::minimumLevel() and * ZoomLevelInfo::maximumLevel(). */ - static int zoomLevelForIconSize(const QSize& size); + static int zoomLevelForIconSize(const QSize &size); }; #endif