1
0
mirror of https://invent.kde.org/system/dolphin synced 2024-07-02 16:31:23 +00:00

Add clang-format and format code as in Frameworks

This commit is contained in:
Serg Podtynnyi 2023-02-04 00:14:53 +07:00
parent ffff8af851
commit 38c34eeca3
260 changed files with 7209 additions and 7699 deletions

View File

@ -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)

View File

@ -5,8 +5,8 @@
*/
#include "dbusinterface.h"
#include "global.h"
#include "dolphin_generalsettings.h"
#include "global.h"
#include <KPropertiesDialog>
#include <KWindowSystem>
@ -14,42 +14,43 @@
#include <QDBusConnection>
#include <QDBusConnectionInterface>
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<QUrl> 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<QUrl> 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<QUrl> urls = Dolphin::validateUris(uriList);
if (!urls.isEmpty()) {

View File

@ -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);

View File

@ -14,15 +14,11 @@
#include <QDir>
#include <QStandardPaths>
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<KBookmarkOwner::FutureBookmark> 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());
}

View File

@ -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<KBookmarkMenu> m_bookmarkMenu;
};

View File

@ -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 <QClipboard>
#include <QKeyEvent>
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<KHamburgerMenu *>(m_mainWindow->actionCollection()->
action(QStringLiteral("hamburger_menu")))->addToMenu(this);
static_cast<KHamburgerMenu *>(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<QKeyEvent*>(event);
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(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<QUrl> 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<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
const DolphinView *view = m_mainWindow->activeViewContainer()->view();
const QList<QAction *> versionControlActions = view->versionControlActions(m_selectedItems);
if (!versionControlActions.isEmpty()) {
addActions(versionControlActions);
addSeparator();
}
}

View File

@ -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

View File

@ -8,22 +8,28 @@
#include <QStyle>
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);
}

View File

@ -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

File diff suppressed because it is too large Load Diff

View File

@ -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 <KFileItemActions>
#include <kio/fileundomanager.h>
#include <kxmlguiwindow.h>
#if HAVE_BALOO
#include "panels/information/informationpanel.h"
#include "panels/information/informationpanel.h"
#endif
#include <QIcon>
@ -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<DolphinViewContainer*> viewContainers() const;
QVector<DolphinViewContainer *> 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<QUrl>& files, bool splitView);
void openFiles(const QList<QUrl> &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<DolphinSettingsDialog> 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

View File

@ -22,11 +22,11 @@
#include <limits>
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<int> splitterSizes = {widthOfSplitterPrimary,
m_splitter->width() - widthOfSplitterPrimary};
const QList<int> 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<QToolBar *>(m_splitter->parentWidget());
}
DolphinUrlNavigator* DolphinNavigatorsWidgetAction::primaryUrlNavigator() const
DolphinUrlNavigator *DolphinNavigatorsWidgetAction::primaryUrlNavigator() const
{
Q_ASSERT(m_splitter);
return m_splitter->widget(0)->findChild<DolphinUrlNavigator *>();
}
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;
}

View File

@ -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;

View File

@ -11,8 +11,8 @@
#include <KActionCollection>
#include <KIO/Job>
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);
}
}

View File

@ -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

View File

@ -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("<qt>%1</qt>").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<bool, QString> 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<QAction*> actions = searchTools.actions();
KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames(&searchTools, {"files-find"}, QUrl::fromLocalFile(localFilePathOrHome()));
QList<QAction *> 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<QUrl>& files)
void DolphinPart::setFilesToSelect(const QList<QUrl> &files)
{
if (files.isEmpty()) {
return;
@ -627,15 +585,15 @@ void DolphinPart::setFilesToSelect(const QList<QUrl>& 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<QMenu*>(obj);
QMenu *menu = qobject_cast<QMenu *>(obj);
if (menu && menu->parent() == m_view) {
QKeyEvent* ev = static_cast<QKeyEvent*>(event);
QKeyEvent *ev = static_cast<QKeyEvent *>(event);
if (ev->key() == Qt::Key_Shift) {
m_removeAction->update(type == QEvent::KeyPress ? ShiftState::Pressed : ShiftState::Released);
}

View File

@ -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<QUrl> filesToSelect READ filesToSelect WRITE setFilesToSelect )
Q_PROPERTY(QList<QUrl> 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<QUrl> &files);
QList<QUrl> filesToSelect() const { return QList<QUrl>(); } // silence moc
QList<QUrl> filesToSelect() const
{
return QList<QUrl>();
} // 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)
};

View File

@ -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);
}

View File

@ -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

View File

@ -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()

View File

@ -7,8 +7,8 @@
#ifndef DOLPHINPLACESMODELSINGLETON_H
#define DOLPHINPLACESMODELSINGLETON_H
#include <QString>
#include <QScopedPointer>
#include <QString>
#include <KFilePlacesModel>
@ -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();

View File

@ -12,8 +12,8 @@
#include <QMenu>
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<QAction*> actions = menu()->actions();
QList<QAction *> actions = menu()->actions();
const int count = actions.size();
for (int i = count - 1; i >= 2; i--) {
removeAction(actions.at(i));

View File

@ -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

View File

@ -9,9 +9,9 @@
#include <QApplication>
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);

View File

@ -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.

View File

@ -13,10 +13,10 @@
#include <QMimeData>
#include <QTimer>
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) {

View File

@ -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;
};

View File

@ -14,12 +14,12 @@
#include <QStyle>
#include <QVariantAnimation>
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<int> 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<QGridLayout *>(layout());
if (navigatorsWidget->isInToolbar()) {
@ -226,7 +217,7 @@ void DolphinTabPage::insertNavigatorsWidget(DolphinNavigatorsWidgetAction* navig
}
}
void DolphinTabPage::markUrlsAsSelected(const QList<QUrl>& urls)
void DolphinTabPage::markUrlsAsSelected(const QList<QUrl> &urls)
{
m_primaryViewContainer->view()->markUrlsAsSelected(urls);
if (m_splitViewEnabled) {
@ -234,7 +225,7 @@ void DolphinTabPage::markUrlsAsSelected(const QList<QUrl>& 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);
}

View File

@ -11,9 +11,9 @@
#include "global.h"
#include <QPointer>
#include <QSplitter>
#include <QUrl>
#include <QWidget>
#include <QSplitter>
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

View File

@ -10,35 +10,30 @@
#include "dolphintabbar.h"
#include "dolphinviewcontainer.h"
#include <KAcceleratorManager>
#include <KConfigGroup>
#include <KIO/CommandLauncherJob>
#include <KLocalizedString>
#include <KShell>
#include <kio/global.h>
#include <KIO/CommandLauncherJob>
#include <KAcceleratorManager>
#include <KLocalizedString>
#include <QApplication>
#include <QDropEvent>
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<int>::of(&DolphinTabWidget::closeTab));
connect(this, &DolphinTabWidget::currentChanged,
this, &DolphinTabWidget::currentTabChanged);
connect(this, &DolphinTabWidget::tabCloseRequested, this, QOverload<int>::of(&DolphinTabWidget::closeTab));
connect(this, &DolphinTabWidget::currentChanged, this, &DolphinTabWidget::currentTabChanged);
DolphinTabBar* tabBar = new DolphinTabBar(this);
connect(tabBar, &DolphinTabBar::openNewActivatedTab,
this, QOverload<int>::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<int>::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<DolphinTabPage*>(widget(index));
return static_cast<DolphinTabPage *>(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<QUrl>& dirs, bool splitView)
void DolphinTabWidget::openDirectories(const QList<QUrl> &dirs, bool splitView)
{
Q_ASSERT(dirs.size() > 0);
@ -204,7 +197,7 @@ void DolphinTabWidget::openDirectories(const QList<QUrl>& dirs, bool splitView)
QList<QUrl>::const_iterator it = dirs.constBegin();
while (it != dirs.constEnd()) {
const QUrl& primaryUrl = *(it++);
const QUrl &primaryUrl = *(it++);
const std::optional<ViewIndex> viewIndexAtDirectory = viewOpenAtDirectory(primaryUrl);
// When the user asks for a URL that's already open,
@ -213,7 +206,7 @@ void DolphinTabWidget::openDirectories(const QList<QUrl>& 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<QUrl>& dirs, bool splitView)
}
}
void DolphinTabWidget::openFiles(const QList<QUrl>& files, bool splitView)
void DolphinTabWidget::openFiles(const QList<QUrl> &files, bool splitView)
{
Q_ASSERT(files.size() > 0);
// Get all distinct directories from 'files'.
QList<QUrl> dirsThatNeedToBeOpened;
QList<QUrl> 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<QUrl>& 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<QWidget*>(sender()));
const int index = indexOf(qobject_cast<QWidget *>(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<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl& directory) const
const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpenAtDirectory(const QUrl &directory) const
{
int i = currentIndex();
if (i < 0) {
@ -556,13 +550,12 @@ const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewOpe
}
i = (i + 1) % count();
}
while (i != currentIndex());
} while (i != currentIndex());
return std::nullopt;
}
const std::optional<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewShowingItem(const QUrl& item) const
const std::optional<const DolphinTabWidget::ViewIndex> 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<const DolphinTabWidget::ViewIndex> DolphinTabWidget::viewSho
}
i = (i + 1) % count();
}
while (i != currentIndex());
} while (i != currentIndex());
return std::nullopt;
}

View File

@ -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<QUrl>& dirs, bool splitView);
void openDirectories(const QList<QUrl> &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<const ViewIndex> viewOpenAtDirectory(const QUrl& directory) const;
const std::optional<const ViewIndex> 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<const ViewIndex> viewShowingItem(const QUrl& item) const;
const std::optional<const ViewIndex> viewShowingItem(const QUrl &item) const;
private:
QPointer<DolphinTabPage> m_lastViewedTab;

View File

@ -12,43 +12,43 @@
#include "dolphinurlnavigatorscontroller.h"
#include "global.h"
#include <KUrlComboBox>
#include <KLocalizedString>
#include <KUrlComboBox>
#include <QAbstractButton>
#include <QLayout>
#include <QLineEdit>
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",
"<para>This describes the location of the files and folders "
"displayed below.</para><para>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 <emphasis>path</emphasis> to the current location because "
"following these folders from left to right leads here.</para>"
"<para>This interactive path "
"is more powerful than one would expect. To learn more "
"about the basic and advanced features of the location bar "
"<link url='help:/dolphin/location-bar.html'>click here</link>. "
"This will open the dedicated page in the Handbook.</para>"));
"<para>This describes the location of the files and folders "
"displayed below.</para><para>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 <emphasis>path</emphasis> to the current location because "
"following these folders from left to right leads here.</para>"
"<para>This interactive path "
"is more powerful than one would expect. To learn more "
"about the basic and advanced features of the location bar "
"<link url='help:/dolphin/location-bar.html'>click here</link>. "
"This will open the dedicated page in the Handbook.</para>"));
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::VisualState> DolphinUrlNavigator::visualSta
return visualState;
}
void DolphinUrlNavigator::setVisualState(const VisualState& visualState)
void DolphinUrlNavigator::setVisualState(const VisualState &visualState)
{
setUrlEditable(visualState.isUrlEditable);
if (!visualState.isUrlEditable) {

View File

@ -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)

View File

@ -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 <KActionCollection>
#if HAVE_KACTIVITIES
@ -38,38 +38,38 @@
#include <QDropEvent>
#include <QGridLayout>
#include <QGuiApplication>
#include <QRegularExpression>
#include <QTimer>
#include <QUrl>
#include <QRegularExpression>
// 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",
"<para>This helps you find files and folders. Enter a <emphasis>"
"search term</emphasis> and specify search settings with the "
"buttons at the bottom:<list><item>Filename/Content: "
"Does the item you are looking for contain the search terms "
"within its filename or its contents?<nl/>The contents of images, "
"audio files and videos will not be searched.</item><item>"
"From Here/Everywhere: Do you want to search in this "
"folder and its sub-folders or everywhere?</item><item>"
"More Options: Click this to search by media type, access "
"time or rating.</item><item>More Search Tools: Install other "
"means to find an item.</item></list></para>"));
"<para>This helps you find files and folders. Enter a <emphasis>"
"search term</emphasis> and specify search settings with the "
"buttons at the bottom:<list><item>Filename/Content: "
"Does the item you are looking for contain the search terms "
"within its filename or its contents?<nl/>The contents of images, "
"audio files and videos will not be searched.</item><item>"
"From Here/Everywhere: Do you want to search in this "
"folder and its sub-folders or everywhere?</item><item>"
"More Options: Click this to search by media type, access "
"time or rating.</item><item>More Search Tools: Install other "
"means to find an item.</item></list></para>"));
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{};
}

View File

@ -21,8 +21,9 @@
#include <QWidget>
#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<DolphinUrlNavigator> 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
};

View File

@ -15,8 +15,8 @@
#include <QLineEdit>
#include <QToolButton>
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;
}
}

View File

@ -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

View File

@ -19,11 +19,11 @@
#include <QApplication>
QList<QUrl> Dolphin::validateUris(const QStringList& uriList)
QList<QUrl> Dolphin::validateUris(const QStringList &uriList)
{
const QString currentDir = QDir::currentPath();
QList<QUrl> 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<QUrl> &urls, QWidget *window, const Open
job->start();
}
bool Dolphin::attachToExistingInstance(const QList<QUrl>& inputUrls, bool openFiles, bool splitView, const QString& preferredService, const QString &activationToken)
bool Dolphin::attachToExistingInstance(const QList<QUrl> &inputUrls,
bool openFiles,
bool splitView,
const QString &preferredService,
const QString &activationToken)
{
bool attached = false;
@ -71,7 +75,7 @@ bool Dolphin::attachToExistingInstance(const QList<QUrl>& 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<QUrl>& inputUrls, bool openFi
// check to see if any instances already have any of the given URLs or their parents open
QList<QUrl> 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<QUrl>& 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<QUrl>& 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<QUrl>& inputUrls, bool openFi
return attached;
}
QVector<QPair<QSharedPointer<OrgKdeDolphinMainWindowInterface>, QStringList>> Dolphin::dolphinGuiInstances(const QString& preferredService)
QVector<QPair<QSharedPointer<OrgKdeDolphinMainWindowInterface>, QStringList>> Dolphin::dolphinGuiInstances(const QString &preferredService)
{
QVector<QPair<QSharedPointer<OrgKdeDolphinMainWindowInterface>, QStringList>> dolphinInterfaces;
if (!preferredService.isEmpty()) {
QSharedPointer<OrgKdeDolphinMainWindowInterface> 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<QPair<QSharedPointer<OrgKdeDolphinMainWindowInterface>, 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<OrgKdeDolphinMainWindowInterface> 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));
}
}

View File

@ -14,51 +14,46 @@
class KConfigGroup;
class OrgKdeDolphinMainWindowInterface;
namespace Dolphin {
QList<QUrl> validateUris(const QStringList& uriList);
namespace Dolphin
{
QList<QUrl> 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<QUrl> &urls = {}, QWidget *window = nullptr, const OpenNewWindowFlags &flags = OpenNewWindowFlag::None);
/**
* Opens a new Dolphin window
*/
void openNewWindow(const QList<QUrl> &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<QUrl>& 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<QUrl> &inputUrls, bool openFiles, bool splitView, const QString &preferredService, const QString &activationToken);
/**
* Returns a QVector with all GUI-capable Dolphin instances
*/
QVector<QPair<QSharedPointer<OrgKdeDolphinMainWindowInterface>, QStringList>> dolphinGuiInstances(const QString& preferredService);
/**
* Returns a QVector with all GUI-capable Dolphin instances
*/
QVector<QPair<QSharedPointer<OrgKdeDolphinMainWindowInterface>, QStringList>> dolphinGuiInstances(const QString &preferredService);
QPair<QString, Qt::SortOrder> sortOrderForUrl(QUrl &url);
QPair<QString, Qt::SortOrder> 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
{

View File

@ -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());
}
}

View File

@ -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.

View File

@ -15,32 +15,33 @@
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainter>
#include <QTimer>
#include <QIcon>
#include <QMimeDatabase>
#include <QPainter>
#include <QTimer>
// #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<KFileItemListWidget>();
}
void KFileItemListView::initializeItemListWidget(KItemListWidget* item)
void KFileItemListView::initializeItemListWidget(KItemListWidget *item)
{
KStandardItemListView::initializeItemListWidget(item);
// Make sure that the item has an icon.
QHash<QByteArray, QVariant> data = item->data();
if (!data.contains("iconName") && data["iconPixmap"].value<QPixmap>().isNull()) {
Q_ASSERT(qobject_cast<KFileItemModel*>(model()));
KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(model());
Q_ASSERT(qobject_cast<KFileItemModel *>(model()));
KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(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<KFileItemModel*>(current));
Q_ASSERT(qobject_cast<KFileItemModel *>(current));
KStandardItemListView::onModelChanged(current, previous);
delete m_modelRolesUpdater;
m_modelRolesUpdater = nullptr;
if (current) {
m_modelRolesUpdater = new KFileItemModelRolesUpdater(static_cast<KFileItemModel*>(current), this);
m_modelRolesUpdater = new KFileItemModelRolesUpdater(static_cast<KFileItemModel *>(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 &current, 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<QByteArray>& current, const QList<QByteArray>& previous)
void KFileItemListView::onVisibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &previous)
{
KStandardItemListView::onVisibleRolesChanged(current, previous);
applyRolesToModel();
}
void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption &current, 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 &current, const QByteArray &previous)
{
const QByteArray sortRole = model()->sortRole();
if (!visibleRoles().contains(sortRole)) {
@ -420,8 +420,8 @@ void KFileItemListView::applyRolesToModel()
return;
}
Q_ASSERT(qobject_cast<KFileItemModel*>(model()));
KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(model());
Q_ASSERT(qobject_cast<KFileItemModel *>(model()));
KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(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);
}

View File

@ -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 &current, const QSizeF &previous) override;
void onScrollOffsetChanged(qreal current, qreal previous) override;
void onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous) override;
void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) override;
void onVisibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &previous) override;
void onStyleOptionChanged(const KItemListStyleOption &current, 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 &current, 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

View File

@ -18,8 +18,8 @@
#include <QGraphicsView>
#include <QMimeDatabase>
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<KFileItemModel*>(view->model()));
KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(view->model());
Q_ASSERT(qobject_cast<KFileItemModel *>(view->model()));
KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(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<KFileItemModel*>(view->model()));
KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(view->model());
Q_ASSERT(qobject_cast<KFileItemModel *>(view->model()));
KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(view->model());
const KFileItem item = fileItemModel->fileItem(index);
return item.isLink();
}
QString KFileItemListWidgetInformant::roleText(const QByteArray& role,
const QHash<QByteArray, QVariant>& values) const
QString KFileItemListWidgetInformant::roleText(const QByteArray &role, const QHash<QByteArray, QVariant> &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<KFileItemListView*>(parentItem());
return dynamic_cast<KFileItemListView *>(parentItem());
}

View File

@ -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<QByteArray, QVariant>& 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<QByteArray, QVariant> &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

File diff suppressed because it is too large Load Diff

View File

@ -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<QByteArray, QVariant> data(int index) const override;
bool setData(int index, const QHash<QByteArray, QVariant>& values) override;
bool setData(int index, const QHash<QByteArray, QVariant> &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<QPair<int, QVariant> > groups() const override;
QList<QPair<int, QVariant>> 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<QByteArray>& roles);
void setRoles(const QSet<QByteArray> &roles);
QSet<QByteArray> 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<QUrl>& urls);
void restoreExpandedDirectories(const QSet<QUrl> &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 &current, 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<QPair<KFileItem, KFileItem> >& items);
void slotItemsAdded(const QUrl &directoryUrl, const KFileItemList &items);
void slotItemsDeleted(const KFileItemList &items);
void slotRefreshItems(const QList<QPair<KFileItem, KFileItem>> &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<QByteArray, QVariant> values;
ItemData* parent;
ItemData *parent;
};
enum RemoveItemsBehavior {
KeepItemData,
DeleteItemData,
DeleteItemDataIfUnfiltered
};
enum RemoveItemsBehavior { KeepItemData, DeleteItemData, DeleteItemDataIfUnfiltered };
void insertItems(QList<ItemData*>& items);
void removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior);
void insertItems(QList<ItemData *> &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<ItemData*> createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const;
QList<ItemData *> 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<ItemData*>& itemDataList);
void prepareItemsForSorting(QList<ItemData *> &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<QByteArray>& changedRoles);
void emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet<QByteArray> &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<QByteArray, QVariant> retrieveData(const KFileItem& item, const ItemData* parent) const;
QHash<QByteArray, QVariant> 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<ItemData*>::iterator &begin, const QList<ItemData*>::iterator &end) const;
void sort(const QList<ItemData *>::iterator &begin, const QList<ItemData *>::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<QPair<int, QVariant> > nameRoleGroups() const;
QList<QPair<int, QVariant> > sizeRoleGroups() const;
QList<QPair<int, QVariant> > timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const;
QList<QPair<int, QVariant> > permissionRoleGroups() const;
QList<QPair<int, QVariant> > ratingRoleGroups() const;
QList<QPair<int, QVariant> > genericStringRoleGroups(const QByteArray& typeForRole) const;
QList<QPair<int, QVariant>> nameRoleGroups() const;
QList<QPair<int, QVariant>> sizeRoleGroups() const;
QList<QPair<int, QVariant>> timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const;
QList<QPair<int, QVariant>> permissionRoleGroups() const;
QList<QPair<int, QVariant>> ratingRoleGroups() const;
QList<QPair<int, QVariant>> 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<QByteArray> m_roles;
QList<ItemData*> m_itemData;
QList<ItemData *> 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<QUrl, int> m_items;
KFileItemModelFilter m_filter;
QHash<KFileItem, ItemData*> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
QHash<KFileItem, ItemData *> m_filteredItems; // Items that got hidden by KFileItemModel::setNameFilter()
bool m_requestRole[RolesCount];
QTimer* m_maximumUpdateIntervalTimer;
QTimer* m_resortAllItemsTimer;
QList<ItemData*> m_pendingItemsToInsert;
QTimer *m_maximumUpdateIntervalTimer;
QTimer *m_resortAllItemsTimer;
QList<ItemData *> m_pendingItemsToInsert;
// Cache for KFileItemModel::groups()
mutable QList<QPair<int, QVariant> > m_groups;
mutable QList<QPair<int, QVariant>> m_groups;
// Stores the URLs (key: target url, value: url) of the expanded directories.
QHash<QUrl, QUrl> m_expandedDirs;
@ -522,31 +555,21 @@ private:
// and done step after step in slotCompleted().
QSet<QUrl> 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

View File

@ -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<qulonglong>(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<QByteArray>& roles)
void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray> &roles)
{
if (m_roles != roles) {
m_roles = roles;
@ -273,11 +267,11 @@ void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& 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<QByteArray> 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<QByteArray>& 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<QByteArray>& roles)
void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &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<KFileItem>& targetSet = itemsChangedRecently ? m_recentlyChangedItems : m_changedItems;
QSet<KFileItem> &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 &current, 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<QByteArray, QVariant> 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<QByteArray, QVariant> data = m_model->data(index);
QVector<QPixmap> pixmaps = data["hoverSequencePixmaps"].value<QVector<QPixmap>>();
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<QPixmap>()));
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<QByteArray, QVariant> 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<QByteArray, QVariant> 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<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);
return true;
}
return false;
}
QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem& item)
QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem &item)
{
QHash<QByteArray, QVariant> data;
@ -1364,14 +1318,14 @@ QHash<QByteArray, QVariant> 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<QByteArray, QVariant> data = m_model->data(index);
QHash<QByteArray, QVariant> 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<int> KFileItemModelRolesUpdater::indexesToResolve() const
const int count = m_model->count();
QList<int> 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()
}
}
}

View File

@ -12,8 +12,8 @@
#include <list>
#include <KFileItem>
#include "config-dolphin.h"
#include <KFileItem>
#include <QObject>
#include <QSet>
@ -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 <Baloo/IndexerConfig>
namespace Baloo
{
class FileMonitor;
}
#include <Baloo/IndexerConfig>
#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<QByteArray>& roles);
void setRoles(const QSet<QByteArray> &roles);
QSet<QByteArray> 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<int> &movedToIndexes);
void slotItemsChanged(const KItemRangeList& itemRanges,
const QSet<QByteArray>& roles);
void slotSortRoleChanged(const QByteArray& current,
const QByteArray& previous);
void slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles);
void slotSortRoleChanged(const QByteArray &current, 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<QByteArray, QVariant> rolesData(const KFileItem& item);
QHash<QByteArray, QVariant> 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<KFileItem> 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<KFileItem> 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<KFileItem> m_recentlyChangedItems;
// Items which have not been changed repeatedly recently.
QSet<KFileItem> m_changedItems;
KDirectoryContentsCounter* m_directoryContentsCounter;
KDirectoryContentsCounter *m_directoryContentsCounter;
QList<KOverlayIconPlugin*> m_overlayIconsPlugin;
QList<KOverlayIconPlugin *> m_overlayIconsPlugin;
#if HAVE_BALOO
Baloo::FileMonitor* m_balooFileMonitor;
Baloo::FileMonitor *m_balooFileMonitor;
Baloo::IndexerConfig m_balooConfig;
#endif
};

View File

@ -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<QGraphicsView*>(viewport());
QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(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<QGraphicsView*>(viewport());
const QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(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<QGraphicsView*>(viewport())->scene();
QGraphicsScene *scene = static_cast<QGraphicsView *>(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<KItemListContainerViewport*>(viewport())->scene()->setSceneRect(m_controller->view()->geometry());
static_cast<KItemListContainerViewport*>(viewport())->viewport()->setGeometry(m_controller->view()->geometry().toRect());
static_cast<KItemListContainerViewport *>(viewport())->scene()->setSceneRect(m_controller->view()->geometry());
static_cast<KItemListContainerViewport *>(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 {

View File

@ -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

View File

@ -30,40 +30,37 @@
#include <QTimer>
#include <QTouchEvent>
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<KItemListWidget*, KItemListGroupHeader*> it(m_view->m_visibleGroups);
QHashIterator<KItemListWidget *, KItemListGroupHeader *> 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<int> 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<QTapGesture*>(tap);
if (QGesture *tap = event->gesture(Qt::TapGesture)) {
QTapGesture *tapGesture = static_cast<QTapGesture *>(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<QTapGesture*>(tap), transform);
if (QGesture *tap = event->gesture(Qt::TapGesture)) {
tapTriggered(static_cast<QTapGesture *>(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<QTapAndHoldGesture*>(event->gesture(Qt::TapAndHoldGesture));
const QTapAndHoldGesture *tap = static_cast<QTapAndHoldGesture *>(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<QPinchGesture*>(event->gesture(Qt::PinchGesture));
const QPinchGesture *pinch = static_cast<QPinchGesture *>(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<KTwoFingerSwipe*>(event->gesture(m_swipeGesture));
const KTwoFingerSwipe *swipe = static_cast<KTwoFingerSwipe *>(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<KTwoFingerTap*>(event->gesture(m_twoFingerTapGesture));
const KTwoFingerTap *twoTap = static_cast<KTwoFingerTap *>(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<QKeyEvent*>(event));
return keyPressEvent(static_cast<QKeyEvent *>(event));
case QEvent::InputMethod:
return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
return inputMethodEvent(static_cast<QInputMethodEvent *>(event));
case QEvent::GraphicsSceneMousePress:
return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
return mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event), QTransform());
case QEvent::GraphicsSceneMouseMove:
return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent *>(event), QTransform());
case QEvent::GraphicsSceneMouseRelease:
return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event), QTransform());
case QEvent::GraphicsSceneMouseDoubleClick:
return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event), QTransform());
case QEvent::GraphicsSceneWheel:
return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
return wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event), QTransform());
case QEvent::GraphicsSceneDragEnter:
return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event), QTransform());
case QEvent::GraphicsSceneDragLeave:
return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event), QTransform());
case QEvent::GraphicsSceneDragMove:
return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event), QTransform());
case QEvent::GraphicsSceneDrop:
return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
return dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event), QTransform());
case QEvent::GraphicsSceneHoverEnter:
return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent *>(event), QTransform());
case QEvent::GraphicsSceneHoverMove:
return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent *>(event), QTransform());
case QEvent::GraphicsSceneHoverLeave:
return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent *>(event), QTransform());
case QEvent::GraphicsSceneResize:
return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
return resizeEvent(static_cast<QGraphicsSceneResizeEvent *>(event), transform);
case QEvent::Gesture:
return gestureEvent(static_cast<QGestureEvent*>(event), transform);
return gestureEvent(static_cast<QGestureEvent *>(event), transform);
case QEvent::TouchBegin:
return touchBeginEvent(static_cast<QTouchEvent*>(event), transform);
return touchBeginEvent(static_cast<QTouchEvent *>(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<int> 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);

View File

@ -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<int> 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

View File

@ -14,17 +14,17 @@
#include <QPainter>
#include <QStyleOptionGraphicsItem>
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 &current, const QByteArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
void KItemListGroupHeader::dataChanged(const QVariant& current, const QVariant& previous)
void KItemListGroupHeader::dataChanged(const QVariant &current, const QVariant &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
void KItemListGroupHeader::styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
void KItemListGroupHeader::styleOptionChanged(const KItemListStyleOption &current, 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());
}

View File

@ -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 &current, 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 &current, 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 &current, 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

View File

@ -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<QByteArray, qreal>& columnWidths)
void KItemListHeader::setColumnWidths(const QHash<QByteArray, qreal> &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<QByteArray, qreal>& 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);
}

View File

@ -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<QByteArray, qreal>& columnWidths);
void setColumnWidths(const QHash<QByteArray, qreal> &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

View File

@ -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<int>& movedToIndexes)
void KItemListSelectionManager::itemsMoved(const KItemRange &itemRange, const QList<int> &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);
}

View File

@ -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 &current, 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<int>& movedToIndexes);
void setModel(KItemModelBase *model);
void itemsInserted(const KItemRangeList &itemRanges);
void itemsRemoved(const KItemRangeList &itemRanges);
void itemsMoved(const KItemRange &itemRange, const QList<int> &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;
};

View File

@ -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);
}

View File

@ -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

File diff suppressed because it is too large Load Diff

View File

@ -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<QByteArray>& roles);
void setVisibleRoles(const QList<QByteArray> &roles);
QList<QByteArray> 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<int> 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<int> 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<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint) const;
void calculateItemSizeHints(QVector<std::pair<qreal, bool>> &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 &current, 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<QByteArray>& current, const QList<QByteArray>& previous);
void visibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &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<QByteArray>& changedRoles) const;
virtual bool itemSizeHintUpdateRequired(const QSet<QByteArray> &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 &current, const QSizeF &previous);
virtual void onScrollOffsetChanged(qreal current, qreal previous);
virtual void onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous);
virtual void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous);
virtual void onVisibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &previous);
virtual void onStyleOptionChanged(const KItemListStyleOption &current, 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<KItemListWidget*> visibleItemListWidgets() const;
QList<KItemListWidget *> 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<int>& movedToIndexes);
virtual void slotItemsChanged(const KItemRangeList& itemRanges,
const QSet<QByteArray>& roles);
virtual void slotItemsInserted(const KItemRangeList &itemRanges);
virtual void slotItemsRemoved(const KItemRangeList &itemRanges);
virtual void slotItemsMoved(const KItemRange &itemRange, const QList<int> &movedToIndexes);
virtual void slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &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 &current, const QByteArray &previous);
virtual void slotCurrentChanged(int current, int previous);
virtual void slotSelectionChanged(const KItemSet& current, const KItemSet& previous);
virtual void slotSelectionChanged(const KItemSet &current, 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<int> recycleInvisibleItems(int firstVisibleIndex,
int lastVisibleIndex,
LayoutAnimationHint hint);
QList<int> 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<QByteArray, qreal> preferredColumnWidths(const KItemRangeList& itemRanges) const;
QHash<QByteArray, qreal> 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<QByteArray> m_visibleRoles;
mutable KItemListWidgetCreatorBase* m_widgetCreator;
mutable KItemListGroupHeaderCreatorBase* m_groupHeaderCreator;
mutable KItemListWidgetCreatorBase *m_widgetCreator;
mutable KItemListGroupHeaderCreatorBase *m_groupHeaderCreator;
KItemListStyleOption m_styleOption;
QHash<int, KItemListWidget*> m_visibleItems;
QHash<KItemListWidget*, KItemListGroupHeader*> m_visibleGroups;
QHash<int, KItemListWidget *> m_visibleItems;
QHash<KItemListWidget *, KItemListGroupHeader *> 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<int, Cell> 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<QVariantAnimation*> m_rubberBandAnimations;
QList<QVariantAnimation *> 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<QGraphicsWidget*> m_createdWidgets;
QList<QGraphicsWidget*> m_recycleableWidgets;
QSet<QGraphicsWidget *> m_createdWidgets;
QList<QGraphicsWidget *> 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<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const = 0;
virtual void calculateItemSizeHints(QVector<std::pair<qreal, bool>> &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 <class T>
template<class T>
class KItemListWidgetCreator : public KItemListWidgetCreatorBase
{
public:
KItemListWidgetCreator();
~KItemListWidgetCreator() override;
KItemListWidget* create(KItemListView* view) override;
KItemListWidget *create(KItemListView *view) override;
void calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const override;
void calculateItemSizeHints(QVector<std::pair<qreal, bool>> &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 <class T>
KItemListWidgetCreator<T>::KItemListWidgetCreator() :
m_informant(T::createInformant())
template<class T>
KItemListWidgetCreator<T>::KItemListWidgetCreator()
: m_informant(T::createInformant())
{
}
template <class T>
template<class T>
KItemListWidgetCreator<T>::~KItemListWidgetCreator()
{
delete m_informant;
}
template <class T>
KItemListWidget* KItemListWidgetCreator<T>::create(KItemListView* view)
template<class T>
KItemListWidget *KItemListWidgetCreator<T>::create(KItemListView *view)
{
KItemListWidget* widget = static_cast<KItemListWidget*>(popRecycleableWidget());
KItemListWidget *widget = static_cast<KItemListWidget *>(popRecycleableWidget());
if (!widget) {
widget = new T(m_informant, view);
addCreatedWidget(widget);
@ -874,15 +860,15 @@ KItemListWidget* KItemListWidgetCreator<T>::create(KItemListView* view)
}
template<class T>
void KItemListWidgetCreator<T>::calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
void KItemListWidgetCreator<T>::calculateItemSizeHints(QVector<std::pair<qreal, bool>> &logicalHeightHints,
qreal &logicalWidthHint,
const KItemListView *view) const
{
return m_informant->calculateItemSizeHints(logicalHeightHints, logicalWidthHint, view);
}
template<class T>
qreal KItemListWidgetCreator<T>::preferredRoleColumnWidth(const QByteArray& role,
int index,
const KItemListView* view) const
qreal KItemListWidgetCreator<T>::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 <class T>
template<class T>
class KItemListGroupHeaderCreator : public KItemListGroupHeaderCreatorBase
{
public:
~KItemListGroupHeaderCreator() override;
KItemListGroupHeader* create(KItemListView* view) override;
KItemListGroupHeader *create(KItemListView *view) override;
};
template <class T>
template<class T>
KItemListGroupHeaderCreator<T>::~KItemListGroupHeaderCreator()
{
}
template <class T>
KItemListGroupHeader* KItemListGroupHeaderCreator<T>::create(KItemListView* view)
template<class T>
KItemListGroupHeader *KItemListGroupHeaderCreator<T>::create(KItemListView *view)
{
KItemListGroupHeader* widget = static_cast<KItemListGroupHeader*>(popRecycleableWidget());
KItemListGroupHeader *widget = static_cast<KItemListGroupHeader *>(popRecycleableWidget());
if (!widget) {
widget = new T(view);
addCreatedWidget(widget);

View File

@ -16,13 +16,13 @@
#include <QGraphicsScene>
#include <QGraphicsView>
KItemListView* KItemListViewAccessible::view() const
KItemListView *KItemListViewAccessible::view() const
{
return qobject_cast<KItemListView*>(object());
return qobject_cast<KItemListView *>(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<QAccessibleTableInterface*>(this);
return static_cast<QAccessibleTableInterface *>(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<QAccessibleInterface*> KItemListViewAccessible::selectedCells() const
QList<QAccessibleInterface *> KItemListViewAccessible::selectedCells() const
{
QList<QAccessibleInterface*> cells;
QList<QAccessibleInterface *> cells;
const auto items = view()->controller()->selectionManager()->selectedItems();
cells.reserve(items.count());
for (int index : items) {
@ -149,7 +149,7 @@ QList<int> KItemListViewAccessible::selectedRows() const
return QList<int>();
}
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<int> 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<const KItemListAccessibleCell*>(interface);
const KItemListAccessibleCell *widget = static_cast<const KItemListAccessibleCell *>(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<QAccessibleTableCellInterface*>(this);
return static_cast<QAccessibleTableCellInterface *>(this);
}
return nullptr;
}
@ -284,14 +285,14 @@ int KItemListAccessibleCell::rowExtent() const
return 1;
}
QList<QAccessibleInterface*> KItemListAccessibleCell::rowHeaderCells() const
QList<QAccessibleInterface *> KItemListAccessibleCell::rowHeaderCells() const
{
return QList<QAccessibleInterface*>();
return QList<QAccessibleInterface *>();
}
QList<QAccessibleInterface*> KItemListAccessibleCell::columnHeaderCells() const
QList<QAccessibleInterface *> KItemListAccessibleCell::columnHeaderCells() const
{
return QList<QAccessibleInterface*>();
return QList<QAccessibleInterface *>();
}
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<KItemListContainer*>(object());
return qobject_cast<KItemListContainer *>(object());
}
#endif // QT_NO_ACCESSIBILITY

View File

@ -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<QAccessibleInterface*> selectedCells() const override;
QList<QAccessibleInterface *> selectedCells() const override;
QList<int> selectedColumns() const override;
QList<int> 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<AccessibleIdWrapper> 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<QAccessibleInterface*> columnHeaderCells() const override;
QList<QAccessibleInterface *> columnHeaderCells() const override;
int columnIndex() const override;
int rowExtent() const override;
QList<QAccessibleInterface*> rowHeaderCells() const override;
QList<QAccessibleInterface *> 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

View File

@ -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<QByteArray, QVariant>& data,
const QSet<QByteArray>& roles)
void KItemListWidget::setData(const QHash<QByteArray, QVariant> &data, const QSet<QByteArray> &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<QByteArray, QVariant> 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<QByteArray>& roles)
void KItemListWidget::setVisibleRoles(const QList<QByteArray> &roles)
{
const QList<QByteArray> previousRoles = m_visibleRoles;
m_visibleRoles = roles;
@ -166,8 +159,7 @@ QList<QByteArray> 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<QByteArray, QVariant>& current,
const QSet<QByteArray>& roles)
void KItemListWidget::dataChanged(const QHash<QByteArray, QVariant> &current, const QSet<QByteArray> &roles)
{
Q_UNUSED(current)
Q_UNUSED(roles)
}
void KItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
const QList<QByteArray>& previous)
void KItemListWidget::visibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &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 &current, 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 &current, const QBitArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
void KItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
void KItemListWidget::editedRoleChanged(const QByteArray &current, 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);
}

View File

@ -35,11 +35,9 @@ public:
KItemListWidgetInformant();
virtual ~KItemListWidgetInformant();
virtual void calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const = 0;
virtual void calculateItemSizeHints(QVector<std::pair<qreal, bool>> &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<QByteArray, QVariant>& data, const QSet<QByteArray>& roles = QSet<QByteArray>());
void setData(const QHash<QByteArray, QVariant> &data, const QSet<QByteArray> &roles = QSet<QByteArray>());
QHash<QByteArray, QVariant> 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<QByteArray>& roles);
void setVisibleRoles(const QList<QByteArray> &roles);
QList<QByteArray> 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<QByteArray, QVariant>& current, const QSet<QByteArray>& roles = QSet<QByteArray>());
virtual void visibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous);
virtual void columnWidthChanged(const QByteArray& role, qreal current, qreal previous);
virtual void dataChanged(const QHash<QByteArray, QVariant> &current, const QSet<QByteArray> &roles = QSet<QByteArray>());
virtual void visibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &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 &current, 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 &current, const QBitArray &previous);
virtual void editedRoleChanged(const QByteArray &current, 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

View File

@ -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<QPair<int, QVariant> > KItemModelBase::groups() const
QList<QPair<int, QVariant>> KItemModelBase::groups() const
{
return QList<QPair<int, QVariant> >();
return QList<QPair<int, QVariant>>();
}
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 &current, const QByteArray &previous, bool resortItems)
{
Q_UNUSED(current)
Q_UNUSED(previous)

View File

@ -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<QByteArray, QVariant>& values);
virtual bool setData(int index, const QHash<QByteArray, QVariant> &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<QPair<int, QVariant> > groups() const;
virtual QList<QPair<int, QVariant>> 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<int>& movedToIndexes);
void itemsMoved(const KItemRange &itemRange, const QList<int> &movedToIndexes);
void itemsChanged(const KItemRangeList& itemRanges, const QSet<QByteArray>& roles);
void itemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &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 &current, 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 &current, 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

View File

@ -12,37 +12,41 @@
#include <QList>
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<KItemRange>
{
public:
KItemRangeList() : QList<KItemRange>() {}
explicit KItemRangeList(const QList<KItemRange>& list) : QList<KItemRange>(list) {}
KItemRangeList()
: QList<KItemRange>()
{
}
explicit KItemRangeList(const QList<KItemRange> &list)
: QList<KItemRange>(list)
{
}
template<class Container>
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<class Container>
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();

View File

@ -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<int>::iterator end = rangeBoundaries.end();
QVector<int>::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<int>::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;
}

View File

@ -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;

View File

@ -11,20 +11,19 @@
#include <KRatingPainter>
#include <QPainter>
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 &current, const
m_dirtyCache = true;
}
void KStandardItemListGroupHeader::dataChanged(const QVariant& current, const QVariant& previous)
void KStandardItemListGroupHeader::dataChanged(const QVariant &current, 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;
}
}

View File

@ -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 &current, const QByteArray &previous) override;
void dataChanged(const QVariant& current, const QVariant& previous) override;
void resizeEvent(QGraphicsSceneResizeEvent* event) override;
void dataChanged(const QVariant &current, const QVariant &previous) override;
void resizeEvent(QGraphicsSceneResizeEvent *event) override;
private:
void updateCache();
@ -38,5 +38,3 @@ private:
QPixmap m_pixmap;
};
#endif

View File

@ -10,9 +10,9 @@
#include <KIconLoader>
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<KStandardItemListWidget>();
}
KItemListGroupHeaderCreatorBase* KStandardItemListView::defaultGroupHeaderCreator() const
KItemListGroupHeaderCreatorBase *KStandardItemListView::defaultGroupHeaderCreator() const
{
return new KItemListGroupHeaderCreator<KStandardItemListGroupHeader>();
}
void KStandardItemListView::initializeItemListWidget(KItemListWidget* item)
void KStandardItemListView::initializeItemListWidget(KItemListWidget *item)
{
KStandardItemListWidget* standardItemListWidget = qobject_cast<KStandardItemListWidget*>(item);
KStandardItemListWidget *standardItemListWidget = qobject_cast<KStandardItemListWidget *>(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<QByteArray>& changedRoles) const
bool KStandardItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray> &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<QByteArray>& 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);
}
}
}

View File

@ -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<QByteArray>& changedRoles) const override;
KItemListWidgetCreatorBase *defaultWidgetCreator() const override;
KItemListGroupHeaderCreatorBase *defaultGroupHeaderCreator() const override;
void initializeItemListWidget(KItemListWidget *item) override;
bool itemSizeHintUpdateRequired(const QSet<QByteArray> &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

View File

@ -26,8 +26,8 @@
// #define KSTANDARDITEMLISTWIDGET_DEBUG
KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
KItemListWidgetInformant()
KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
: KItemListWidgetInformant()
{
}
@ -35,9 +35,11 @@ KStandardItemListWidgetInformant::~KStandardItemListWidgetInformant()
{
}
void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<std::pair<qreal, bool>> &logicalHeightHints,
qreal &logicalWidthHint,
const KItemListView *view) const
{
switch (static_cast<const KStandardItemListView*>(view)->itemLayout()) {
switch (static_cast<const KStandardItemListView *>(view)->itemLayout()) {
case KStandardItemListView::IconsLayout:
calculateIconsLayoutItemSizeHints(logicalHeightHints, logicalWidthHint, view);
break;
@ -56,24 +58,22 @@ void KStandardItemListWidgetInformant::calculateItemSizeHints(QVector<std::pair<
}
}
qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray& role,
int index,
const KItemListView* view) const
qreal KStandardItemListWidgetInformant::preferredRoleColumnWidth(const QByteArray &role, int index, const KItemListView *view) const
{
const QHash<QByteArray, QVariant> 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<QByteArray, QVariant>& values) const
QString KStandardItemListWidgetInformant::roleText(const QByteArray &role, const QHash<QByteArray, QVariant> &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<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
void KStandardItemListWidgetInformant::calculateIconsLayoutItemSizeHints(QVector<std::pair<qreal, bool>> &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<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
void KStandardItemListWidgetInformant::calculateCompactLayoutItemSizeHints(QVector<std::pair<qreal, bool>> &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<QByteArray>& visibleRoles = view->visibleRoles();
const QList<QByteArray> &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<QByteArray, QVariant>& values = view->model()->data(index);
for (const QByteArray& role : visibleRoles) {
const QString& text = roleText(role, values);
const QHash<QByteArray, QVariant> &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<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const
void KStandardItemListWidgetInformant::calculateDetailsLayoutItemSizeHints(QVector<std::pair<qreal, bool>> &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<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(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<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(this)->triggerCacheRefreshing();
return m_iconRect;
}
QRectF KStandardItemListWidget::textRect() const
{
const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(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<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(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<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(this)->triggerCacheRefreshing();
switch (m_layout) {
case IconsLayout:
@ -524,13 +531,13 @@ QRectF KStandardItemListWidget::selectionRect() const
QRectF KStandardItemListWidget::expansionToggleRect() const
{
const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(this)->triggerCacheRefreshing();
return m_isExpandable ? m_expansionArea : QRectF();
}
QRectF KStandardItemListWidget::selectionToggleRect() const
{
const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
const_cast<KStandardItemListWidget *>(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<QByteArray, QVariant>& values) const
QString KStandardItemListWidget::roleText(const QByteArray &role, const QHash<QByteArray, QVariant> &values) const
{
return static_cast<const KStandardItemListWidgetInformant*>(informant())->roleText(role, values);
return static_cast<const KStandardItemListWidgetInformant *>(informant())->roleText(role, values);
}
void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
const QSet<QByteArray>& roles)
void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant> &current, const QSet<QByteArray> &roles)
{
Q_UNUSED(current)
@ -693,7 +693,7 @@ void KStandardItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& 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<QByteArray, QVariant>& cur
QSetIterator<QByteArray> it(dirtyRoles);
while (it.hasNext()) {
const QByteArray& role = it.next();
const QByteArray &role = it.next();
m_dirtyContentRoles.insert(role);
}
}
void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray>& current,
const QList<QByteArray>& previous)
void KStandardItemListWidget::visibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &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 &current, 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 &current, 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 &current, 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<int>(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<QByteArray, QVariant> 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<QByteArray, QVariant> 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<QByteArray, QVariant> 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;
}

View File

@ -23,12 +23,12 @@ class DOLPHIN_EXPORT KStandardItemListWidgetInformant : public KItemListWidgetIn
public:
KStandardItemListWidgetInformant();
~KStandardItemListWidgetInformant() override;
void calculateItemSizeHints(QVector<std::pair<qreal /* height */, bool /* isElided */>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const override;
qreal preferredRoleColumnWidth(const QByteArray& role,
int index,
const KItemListView* view) const override;
void calculateItemSizeHints(QVector<std::pair<qreal /* height */, bool /* isElided */>> &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<QByteArray, QVariant> 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<QByteArray, QVariant>& values) const;
virtual QString roleText(const QByteArray &role, const QHash<QByteArray, QVariant> &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<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const;
void calculateCompactLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const;
void calculateDetailsLayoutItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint, const KItemListView* view) const;
void calculateIconsLayoutItemSizeHints(QVector<std::pair<qreal, bool>> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const;
void calculateCompactLayoutItemSizeHints(QVector<std::pair<qreal, bool>> &logicalHeightHints, qreal &logicalWidthHint, const KItemListView *view) const;
void calculateDetailsLayoutItemSizeHints(QVector<std::pair<qreal, bool>> &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<QByteArray, QVariant>& values) const;
QString roleText(const QByteArray &role, const QHash<QByteArray, QVariant> &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<QByteArray, QVariant>& current, const QSet<QByteArray>& roles = QSet<QByteArray>()) override;
void visibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous) override;
void columnWidthChanged(const QByteArray& role, qreal current, qreal previous) override;
void dataChanged(const QHash<QByteArray, QVariant> &current, const QSet<QByteArray> &roles = QSet<QByteArray>()) override;
void visibleRolesChanged(const QList<QByteArray> &current, const QList<QByteArray> &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 &current, 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 &current, const QBitArray &previous) override;
void editedRoleChanged(const QByteArray &current, 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<QByteArray, TextInfo*> m_textInfo; // PlacesItemListWidget needs to access this
QHash<QByteArray, TextInfo *> 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

View File

@ -14,20 +14,23 @@
#include <QCollator>
#include <QSize>
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<Property, QByteArray> 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<QByteArray> KBalooRolesProvider::roles() const
return m_roles;
}
QHash<QByteArray, QVariant> KBalooRolesProvider::roleValues(const Baloo::File& file,
const QSet<QByteArray>& roles) const
QHash<QByteArray, QVariant> KBalooRolesProvider::roleValues(const Baloo::File &file, const QSet<QByteArray> &roles) const
{
QHash<QByteArray, QVariant> values;
using entry = std::pair<const KFileMetaData::Property::Property&, const QVariant&>;
using entry = std::pair<const KFileMetaData::Property::Property &, const QVariant &>;
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<QByteArray, QVariant> KBalooRolesProvider::roleValues(const Baloo::File& f
if (distance > 1) {
QVariantList list;
list.reserve(static_cast<int>(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<QByteArray, QVariant> 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"));
}

View File

@ -14,8 +14,9 @@
#include <QSet>
#include <QVariant>
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<QByteArray, QVariant> roleValues(const Baloo::File& file,
const QSet<QByteArray>& roles) const;
QHash<QByteArray, QVariant> roleValues(const Baloo::File &file, const QSet<QByteArray> &roles) const;
protected:
KBalooRolesProvider();
@ -52,4 +52,3 @@ private:
};
#endif

View File

@ -10,26 +10,26 @@
#include <KDirWatch>
#include <QFileInfo>
#include <QDir>
#include <QFileInfo>
#include <QThread>
namespace {
/// cache of directory counting result
static QHash<QString, QPair<int, long>> *s_cache;
namespace
{
/// cache of directory counting result
static QHash<QString, QPair<int, long>> *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<QString> 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;

View File

@ -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<QString> m_priorityQueue;
std::list<QString> m_queue;
static QThread* m_workerThread;
static QThread *m_workerThread;
KDirectoryContentsCounterWorker* m_worker;
KDirectoryContentsCounterWorker *m_worker;
bool m_workerIsBusy;
KDirWatch* m_dirWatcher;
QSet<QString> m_watchedDirs; // Required as sadly KDirWatch does not offer a getter method
// to get all watched directories.
KDirWatch *m_dirWatcher;
QSet<QString> m_watchedDirs; // Required as sadly KDirWatch does not offer a getter method
// to get all watched directories.
};
#endif

View File

@ -17,17 +17,15 @@
#include "dolphin_detailsmodesettings.h"
KDirectoryContentsCounterWorker::KDirectoryContentsCounterWorker(QObject* parent) :
QObject(parent)
KDirectoryContentsCounterWorker::KDirectoryContentsCounterWorker(QObject *parent)
: QObject(parent)
{
qRegisterMetaType<KDirectoryContentsCounterWorker::Options>();
}
#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);

View File

@ -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)

View File

@ -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);
}

View File

@ -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<QUrl> cutItems() const;

View File

@ -10,11 +10,11 @@
#include <KFileItem>
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;
}

View File

@ -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

View File

@ -21,10 +21,8 @@
* SPDX-FileCopyrightText: 2011 Nokia Corporation and/or its subsidiary(-ies).
*/
template <typename RandomAccessIterator, typename LessThan>
static void mergeSort(RandomAccessIterator begin,
RandomAccessIterator end,
const LessThan& lessThan)
template<typename RandomAccessIterator, typename LessThan>
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 <typename RandomAccessIterator, typename LessThan>
static void parallelMergeSort(RandomAccessIterator begin,
RandomAccessIterator end,
LessThan lessThan,
int numberOfThreads,
int parallelMergeSortingThreshold = 100)
template<typename RandomAccessIterator, typename LessThan>
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<void> future = QtConcurrent::run(parallelMergeSort<RandomAccessIterator, LessThan>, begin, middle, lessThan, newNumberOfThreads, parallelMergeSortingThreshold);
QFuture<void> future =
QtConcurrent::run(parallelMergeSort<RandomAccessIterator, LessThan>, 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 <typename RandomAccessIterator, typename LessThan>
static void merge(RandomAccessIterator begin,
RandomAccessIterator pivot,
RandomAccessIterator end,
const LessThan& lessThan)
template<typename RandomAccessIterator, typename LessThan>
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<RandomAccessIterator,
decltype(*firstCut), const LessThan&>(pivot, end, *firstCut, lessThan);
secondCut = std::lower_bound<RandomAccessIterator, decltype(*firstCut), const LessThan &>(pivot, end, *firstCut, lessThan);
len2Half = secondCut - pivot;
} else {
len2Half = len2 / 2;
secondCut = pivot + len2Half;
firstCut = std::upper_bound<RandomAccessIterator,
decltype(*secondCut), const LessThan&>(begin, pivot, *secondCut, lessThan);
firstCut = std::upper_bound<RandomAccessIterator, decltype(*secondCut), const LessThan &>(begin, pivot, *secondCut, lessThan);
}
std::rotate(firstCut, pivot, secondCut);
@ -129,4 +120,3 @@ static void merge(RandomAccessIterator begin,
}
#endif

View File

@ -12,21 +12,20 @@
#include <QPainter>
#include <QStyleOptionHeader>
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<QByteArray>& roles)
void KItemListHeaderWidget::setColumns(const QList<QByteArray> &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<QByteArray> 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 &current, 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;
}

View File

@ -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<QByteArray>& roles);
void setColumns(const QList<QByteArray> &roles);
QList<QByteArray> 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 &current, 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 &current, 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<QByteArray> 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

View File

@ -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 &current, const KItemSet &previous)
{
if (!previous.isEmpty() && current.isEmpty() && previous.count() > 0 && current.count() == 0) {
// The selection has been emptied. We should cancel the search.

View File

@ -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 &current, 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

View File

@ -8,10 +8,10 @@
#include <KIO/Global>
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<QFocusEvent*>(event);
QFocusEvent *focusEvent = static_cast<QFocusEvent *>(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);
}
}

View File

@ -11,15 +11,14 @@
#include <KTextEdit>
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:
/**

View File

@ -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;
}

View File

@ -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 &current, const QPointF &previous);
void endPositionChanged(const QPointF &current, const QPointF &previous);
private:
bool m_active;
@ -45,5 +45,3 @@ private:
};
#endif

View File

@ -11,10 +11,10 @@
#include <QIcon>
#include <QPainter>
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;
}

View File

@ -11,7 +11,6 @@
#include <QGraphicsWidget>
#include <QPixmap>
/**
* @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

View File

@ -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<std::pair<qreal, bool>>::iterator begin = m_logicalHeightHintCache.begin();
const QVector<std::pair<qreal, bool>>::iterator end = m_logicalHeightHintCache.end();
@ -112,7 +112,7 @@ void KItemListSizeHintResolver::itemsRemoved(const KItemRangeList& itemRanges)
}
}
void KItemListSizeHintResolver::itemsMoved(const KItemRange& range, const QList<int>& movedToIndexes)
void KItemListSizeHintResolver::itemsMoved(const KItemRange &range, const QList<int> &movedToIndexes)
{
QVector<std::pair<qreal, bool>> 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<QByteArray>& roles)
void KItemListSizeHintResolver::itemsChanged(int index, int count, const QSet<QByteArray> &roles)
{
Q_UNUSED(roles)
while (count) {

Some files were not shown because too many files have changed in this diff Show More