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)
*/
#include "dbusinterface.h"
-#include "global.h"
#include "dolphin_generalsettings.h"
+#include "global.h"
#include <KPropertiesDialog>
#include <KWindowSystem>
#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()) {
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);
#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()) {
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());
}
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;
};
#include "dolphincontextmenu.h"
-#include "dolphin_generalsettings.h"
#include "dolphin_contextmenusettings.h"
+#include "dolphin_generalsettings.h"
#include "dolphinmainwindow.h"
#include "dolphinnewfilemenu.h"
#include "dolphinplacesmodelsingleton.h"
#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);
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();
}
}
-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) {
{
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);
}
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)) {
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")));
}
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());
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);
{
Q_ASSERT(!m_fileInfo.isNull());
- const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
+ const KFileItemListProperties &selectedItemsProps = selectedItemsProperties();
m_fileItemActions->setItemListProperties(selectedItemsProps);
} 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()));
});
// 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;
// insert 'Properties...' entry
addSeparator();
- QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
+ QAction *propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
addAction(propertiesAction);
}
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);
// 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();
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);
}
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;
}
}
-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;
return action;
}
-KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
+KFileItemListProperties &DolphinContextMenu::selectedItemsProperties() const
{
if (!m_selectedItemsProperties) {
m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
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);
}
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();
}
}
-
* @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:
/**
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.
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,
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
#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
{
}
};
-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);
}
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;
/**
private:
bool m_locked;
- QWidget* m_dockTitleBar;
+ QWidget *m_dockTitleBar;
};
#endif
#include "dolphinmainwindow.h"
-#include "dolphinmainwindowadaptor.h"
-#include "global.h"
+#include "dolphin_generalsettings.h"
#include "dolphinbookmarkhandler.h"
-#include "dolphindockwidget.h"
#include "dolphincontextmenu.h"
+#include "dolphindockwidget.h"
+#include "dolphinmainwindowadaptor.h"
#include "dolphinnavigatorswidgetaction.h"
#include "dolphinnewfilemenu.h"
-#include "dolphinrecenttabsmenu.h"
#include "dolphinplacesmodelsingleton.h"
+#include "dolphinrecenttabsmenu.h"
+#include "dolphintabpage.h"
#include "dolphinurlnavigatorscontroller.h"
#include "dolphinviewcontainer.h"
-#include "dolphintabpage.h"
+#include "global.h"
#include "middleclickactioneventfilter.h"
#include "panels/folders/folderspanel.h"
#include "panels/places/placespanel.h"
#include "selectionmode/actiontexthelper.h"
#include "settings/dolphinsettingsdialog.h"
#include "statusbar/dolphinstatusbar.h"
-#include "views/dolphinviewactionhandler.h"
+#include "views/dolphinnewfilemenuobserver.h"
#include "views/dolphinremoteencoding.h"
+#include "views/dolphinviewactionhandler.h"
#include "views/draganddrophelper.h"
#include "views/viewproperties.h"
-#include "views/dolphinnewfilemenuobserver.h"
-#include "dolphin_generalsettings.h"
#include <KActionCollection>
#include <KActionMenu>
#include <KWindowSystem>
#include <KXMLGUIFactory>
-#include <kwidgetsaddons_version.h>
#include <kio_version.h>
+#include <kwidgetsaddons_version.h>
#include <QApplication>
#include <QClipboard>
#include <QTimer>
#include <QToolButton>
-namespace {
- // Used for GeneralSettings::version() to determine whether
- // an updated version of Dolphin is running, so as to migrate
- // removed/renamed ...etc config entries; increment it in such
- // cases
- const int CurrentDolphinVersion = 202;
- // The maximum number of entries in the back/forward popup menu
- const int MaxNumberOfNavigationentries = 12;
- // The maximum number of "Activate Tab" shortcuts
- const int MaxActivateTabShortcuts = 9;
-}
-
-DolphinMainWindow::DolphinMainWindow() :
- KXmlGuiWindow(nullptr),
- m_newFileMenu(nullptr),
- m_tabWidget(nullptr),
- m_activeViewContainer(nullptr),
- m_actionHandler(nullptr),
- m_remoteEncoding(nullptr),
- m_settingsDialog(),
- m_bookmarkHandler(nullptr),
- m_lastHandleUrlOpenJob(nullptr),
- m_terminalPanel(nullptr),
- m_placesPanel(nullptr),
- m_tearDownFromPlacesRequested(false),
- m_backAction(nullptr),
- m_forwardAction(nullptr)
+namespace
+{
+// Used for GeneralSettings::version() to determine whether
+// an updated version of Dolphin is running, so as to migrate
+// removed/renamed ...etc config entries; increment it in such
+// cases
+const int CurrentDolphinVersion = 202;
+// The maximum number of entries in the back/forward popup menu
+const int MaxNumberOfNavigationentries = 12;
+// The maximum number of "Activate Tab" shortcuts
+const int MaxActivateTabShortcuts = 9;
+}
+
+DolphinMainWindow::DolphinMainWindow()
+ : KXmlGuiWindow(nullptr)
+ , m_newFileMenu(nullptr)
+ , m_tabWidget(nullptr)
+ , m_activeViewContainer(nullptr)
+ , m_actionHandler(nullptr)
+ , m_remoteEncoding(nullptr)
+ , m_settingsDialog()
+ , m_bookmarkHandler(nullptr)
+ , m_lastHandleUrlOpenJob(nullptr)
+ , m_terminalPanel(nullptr)
+ , m_placesPanel(nullptr)
+ , m_tearDownFromPlacesRequested(false)
+ , m_backAction(nullptr)
+ , m_forwardAction(nullptr)
{
Q_INIT_RESOURCE(dolphin);
new MainWindowAdaptor(this);
#ifndef Q_OS_WIN
- setWindowFlags(Qt::WindowContextHelpButtonHint);
+ setWindowFlags(Qt::WindowContextHelpButtonHint);
#endif
setComponentName(QStringLiteral("dolphin"), QGuiApplication::applicationDisplayName());
setObjectName(QStringLiteral("Dolphin#"));
setStateConfigGroup("State");
- connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage,
- this, &DolphinMainWindow::showErrorMessage);
+ connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage, this, &DolphinMainWindow::showErrorMessage);
- KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self();
+ KIO::FileUndoManager *undoManager = KIO::FileUndoManager::self();
undoManager->setUiInterface(new UndoUiInterface());
- connect(undoManager, &KIO::FileUndoManager::undoAvailable,
- this, &DolphinMainWindow::slotUndoAvailable);
- connect(undoManager, &KIO::FileUndoManager::undoTextChanged,
- this, &DolphinMainWindow::slotUndoTextChanged);
- connect(undoManager, &KIO::FileUndoManager::jobRecordingStarted,
- this, &DolphinMainWindow::clearStatusBar);
- connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished,
- this, &DolphinMainWindow::showCommand);
+ connect(undoManager, &KIO::FileUndoManager::undoAvailable, this, &DolphinMainWindow::slotUndoAvailable);
+ connect(undoManager, &KIO::FileUndoManager::undoTextChanged, this, &DolphinMainWindow::slotUndoTextChanged);
+ connect(undoManager, &KIO::FileUndoManager::jobRecordingStarted, this, &DolphinMainWindow::clearStatusBar);
+ connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinMainWindow::showCommand);
const bool firstRun = (GeneralSettings::version() < 200);
if (firstRun) {
actionCollection()->addAction(QStringLiteral("url_navigators"), navigatorsWidgetAction);
m_tabWidget = new DolphinTabWidget(navigatorsWidgetAction, this);
m_tabWidget->setObjectName("tabWidget");
- connect(m_tabWidget, &DolphinTabWidget::activeViewChanged,
- this, &DolphinMainWindow::activeViewChanged);
- connect(m_tabWidget, &DolphinTabWidget::tabCountChanged,
- this, &DolphinMainWindow::tabCountChanged);
- connect(m_tabWidget, &DolphinTabWidget::currentUrlChanged,
- this, &DolphinMainWindow::updateWindowTitle);
+ connect(m_tabWidget, &DolphinTabWidget::activeViewChanged, this, &DolphinMainWindow::activeViewChanged);
+ connect(m_tabWidget, &DolphinTabWidget::tabCountChanged, this, &DolphinMainWindow::tabCountChanged);
+ connect(m_tabWidget, &DolphinTabWidget::currentUrlChanged, this, &DolphinMainWindow::updateWindowTitle);
setCentralWidget(m_tabWidget);
m_actionTextHelper = new SelectionMode::ActionTextHelper(this);
connect(m_actionHandler, &DolphinViewActionHandler::selectionModeChangeTriggered, this, &DolphinMainWindow::slotSetSelectionMode);
m_remoteEncoding = new DolphinRemoteEncoding(this, m_actionHandler);
- connect(this, &DolphinMainWindow::urlChanged,
- m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl);
+ connect(this, &DolphinMainWindow::urlChanged, m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl);
setupDockWidgets();
setupGUI(Save | Create | ToolBar);
stateChanged(QStringLiteral("new_file"));
- QClipboard* clipboard = QApplication::clipboard();
- connect(clipboard, &QClipboard::dataChanged,
- this, &DolphinMainWindow::updatePasteAction);
+ QClipboard *clipboard = QApplication::clipboard();
+ connect(clipboard, &QClipboard::dataChanged, this, &DolphinMainWindow::updatePasteAction);
- QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
+ QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
toggleFilterBarAction->setChecked(GeneralSettings::filterBar());
if (firstRun) {
}
const bool showMenu = !menuBar()->isHidden();
- QAction* showMenuBarAction = actionCollection()->action(KStandardAction::name(KStandardAction::ShowMenubar));
- showMenuBarAction->setChecked(showMenu); // workaround for bug #171080
+ QAction *showMenuBarAction = actionCollection()->action(KStandardAction::name(KStandardAction::ShowMenubar));
+ showMenuBarAction->setChecked(showMenu); // workaround for bug #171080
- auto hamburgerMenu = static_cast<KHamburgerMenu *>(actionCollection()->action(
- KStandardAction::name(KStandardAction::HamburgerMenu)));
+ auto hamburgerMenu = static_cast<KHamburgerMenu *>(actionCollection()->action(KStandardAction::name(KStandardAction::HamburgerMenu)));
hamburgerMenu->setMenuBar(menuBar());
hamburgerMenu->setShowMenuBarAction(showMenuBarAction);
- connect(hamburgerMenu, &KHamburgerMenu::aboutToShowMenu,
- this, &DolphinMainWindow::updateHamburgerMenu);
+ connect(hamburgerMenu, &KHamburgerMenu::aboutToShowMenu, this, &DolphinMainWindow::updateHamburgerMenu);
hamburgerMenu->hideActionsOf(toolBar());
if (GeneralSettings::version() < 201 && !toolBar()->actions().contains(hamburgerMenu)) {
addHamburgerMenuToToolbar();
showErrorMessage(errorMessage);
});
- connect(GeneralSettings::self(), &GeneralSettings::splitViewChanged,
- this, &DolphinMainWindow::slotSplitViewChanged);
+ connect(GeneralSettings::self(), &GeneralSettings::splitViewChanged, this, &DolphinMainWindow::slotSplitViewChanged);
}
DolphinMainWindow::~DolphinMainWindow()
disconnect(QGuiApplication::clipboard(), &QClipboard::dataChanged, this, &DolphinMainWindow::updatePasteAction);
}
-QVector<DolphinViewContainer*> DolphinMainWindow::viewContainers() const
+QVector<DolphinViewContainer *> DolphinMainWindow::viewContainers() const
{
- QVector<DolphinViewContainer*> viewContainers;
+ QVector<DolphinViewContainer *> viewContainers;
for (int i = 0; i < m_tabWidget->count(); ++i) {
DolphinTabPage *tabPage = m_tabWidget->tabPageAt(i);
return viewContainers;
}
-void DolphinMainWindow::openDirectories(const QList<QUrl>& dirs, bool splitView)
+void DolphinMainWindow::openDirectories(const QList<QUrl> &dirs, bool splitView)
{
m_tabWidget->openDirectories(dirs, splitView);
}
-void DolphinMainWindow::openDirectories(const QStringList& dirs, bool splitView)
+void DolphinMainWindow::openDirectories(const QStringList &dirs, bool splitView)
{
openDirectories(QUrl::fromStringList(dirs), splitView);
}
-void DolphinMainWindow::openFiles(const QList<QUrl>& files, bool splitView)
+void DolphinMainWindow::openFiles(const QList<QUrl> &files, bool splitView)
{
m_tabWidget->openFiles(files, splitView);
}
#endif
}
-void DolphinMainWindow::openFiles(const QStringList& files, bool splitView)
+void DolphinMainWindow::openFiles(const QStringList &files, bool splitView)
{
openFiles(QUrl::fromStringList(files), splitView);
}
void DolphinMainWindow::showCommand(CommandType command)
{
- DolphinStatusBar* statusBar = m_activeViewContainer->statusBar();
+ DolphinStatusBar *statusBar = m_activeViewContainer->statusBar();
switch (command) {
case KIO::FileUndoManager::Copy:
statusBar->setText(i18nc("@info:status", "Successfully copied."));
Q_EMIT urlChanged(url);
}
-void DolphinMainWindow::slotTerminalDirectoryChanged(const QUrl& url)
+void DolphinMainWindow::slotTerminalDirectoryChanged(const QUrl &url)
{
if (m_tearDownFromPlacesRequested && url == QUrl::fromLocalFile(QDir::homePath())) {
m_placesPanel->proceedWithTearDown();
void DolphinMainWindow::slotEditableStateChanged(bool editable)
{
- KToggleAction* editableLocationAction =
- static_cast<KToggleAction*>(actionCollection()->action(QStringLiteral("editable_location")));
+ KToggleAction *editableLocationAction = static_cast<KToggleAction *>(actionCollection()->action(QStringLiteral("editable_location")));
editableLocationAction->setChecked(editable);
}
-void DolphinMainWindow::slotSelectionChanged(const KFileItemList& selection)
+void DolphinMainWindow::slotSelectionChanged(const KFileItemList &selection)
{
updateFileAndEditActions();
const int selectedUrlsCount = m_tabWidget->currentTabPage()->selectedItemsCount();
- QAction* compareFilesAction = actionCollection()->action(QStringLiteral("compare_files"));
+ QAction *compareFilesAction = actionCollection()->action(QStringLiteral("compare_files"));
if (selectedUrlsCount == 2) {
compareFilesAction->setEnabled(isKompareInstalled());
} else {
const KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigatorInternalWithHistory();
const int index = urlNavigator->historyIndex();
- QAction* backAction = actionCollection()->action(KStandardAction::name(KStandardAction::Back));
+ QAction *backAction = actionCollection()->action(KStandardAction::name(KStandardAction::Back));
if (backAction) {
backAction->setToolTip(i18nc("@info", "Go back"));
backAction->setWhatsThis(i18nc("@info:whatsthis go back", "Return to the previously viewed folder."));
backAction->setEnabled(index < urlNavigator->historySize() - 1);
}
- QAction* forwardAction = actionCollection()->action(KStandardAction::name(KStandardAction::Forward));
+ QAction *forwardAction = actionCollection()->action(KStandardAction::name(KStandardAction::Forward));
if (forwardAction) {
forwardAction->setToolTip(i18nc("@info", "Go forward"));
- forwardAction->setWhatsThis(xi18nc("@info:whatsthis go forward",
- "This undoes a <interface>Go|Back</interface> action."));
+ forwardAction->setWhatsThis(xi18nc("@info:whatsthis go forward", "This undoes a <interface>Go|Back</interface> action."));
forwardAction->setEnabled(index > 0);
}
}
void DolphinMainWindow::updateFilterBarAction(bool show)
{
- QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
+ QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
toggleFilterBarAction->setChecked(show);
}
}
}
-void DolphinMainWindow::openNewTab(const QUrl& url)
+void DolphinMainWindow::openNewTab(const QUrl &url)
{
m_tabWidget->openNewTab(url, QUrl());
}
void DolphinMainWindow::openInNewTab()
{
- const KFileItemList& list = m_activeViewContainer->view()->selectedItems();
+ const KFileItemList &list = m_activeViewContainer->view()->selectedItems();
bool tabCreated = false;
- for (const KFileItem& item : list) {
- const QUrl& url = DolphinView::openItemAsFolderUrl(item);
+ for (const KFileItem &item : list) {
+ const QUrl &url = DolphinView::openItemAsFolderUrl(item);
if (!url.isEmpty()) {
openNewTab(url);
tabCreated = true;
if (list.isEmpty()) {
newWindowUrl = m_activeViewContainer->url();
} else if (list.count() == 1) {
- const KFileItem& item = list.first();
+ const KFileItem &item = list.first();
newWindowUrl = DolphinView::openItemAsFolderUrl(item);
}
if (QFileInfo::exists(linkDestination)) {
KIO::highlightInFileManager({QUrl::fromLocalFile(linkDestination).adjusted(QUrl::StripTrailingSlash)});
} else {
- m_activeViewContainer->showMessage(xi18nc("@info", "Could not access <filename>%1</filename>.", linkDestination),
- DolphinViewContainer::Warning);
+ m_activeViewContainer->showMessage(xi18nc("@info", "Could not access <filename>%1</filename>.", linkDestination), DolphinViewContainer::Warning);
}
}
-void DolphinMainWindow::showEvent(QShowEvent* event)
+void DolphinMainWindow::showEvent(QShowEvent *event)
{
KXmlGuiWindow::showEvent(event);
}
}
-void DolphinMainWindow::closeEvent(QCloseEvent* event)
+void DolphinMainWindow::closeEvent(QCloseEvent *event)
{
// Find out if Dolphin is closed directly by the user or
// by the session manager because the session is closed
closedByUser = false;
}
- if (m_tabWidget->count() > 1
- && GeneralSettings::confirmClosingMultipleTabs()
- && !GeneralSettings::rememberOpenedTabs()
- && closedByUser) {
+ if (m_tabWidget->count() > 1 && GeneralSettings::confirmClosingMultipleTabs() && !GeneralSettings::rememberOpenedTabs() && closedByUser) {
// Ask the user if he really wants to quit and close all tabs.
// Open a confirmation dialog with 3 buttons:
// QDialogButtonBox::Yes -> Quit
QDialog *dialog = new QDialog(this, Qt::Dialog);
dialog->setWindowTitle(i18nc("@title:window", "Confirmation"));
dialog->setModal(true);
- QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel);
- KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), KGuiItem(i18nc("@action:button 'Quit Dolphin' button", "&Quit %1", QGuiApplication::applicationDisplayName()), QIcon::fromTheme(QStringLiteral("application-exit"))));
+ QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel);
+ KGuiItem::assign(buttons->button(QDialogButtonBox::Yes),
+ KGuiItem(i18nc("@action:button 'Quit Dolphin' button", "&Quit %1", QGuiApplication::applicationDisplayName()),
+ QIcon::fromTheme(QStringLiteral("application-exit"))));
KGuiItem::assign(buttons->button(QDialogButtonBox::No), KGuiItem(i18n("C&lose Current Tab"), QIcon::fromTheme(QStringLiteral("tab-close"))));
KGuiItem::assign(buttons->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel());
buttons->button(QDialogButtonBox::Yes)->setDefault(true);
bool doNotAskAgainCheckboxResult = false;
const auto result = KMessageBox::createKMessageBox(dialog,
- buttons,
- QMessageBox::Warning,
- i18n("You have multiple tabs open in this window, are you sure you want to quit?"),
- QStringList(),
- i18n("Do not ask again"),
- &doNotAskAgainCheckboxResult,
- KMessageBox::Notify);
+ buttons,
+ QMessageBox::Warning,
+ i18n("You have multiple tabs open in this window, are you sure you want to quit?"),
+ QStringList(),
+ i18n("Do not ask again"),
+ &doNotAskAgainCheckboxResult,
+ KMessageBox::Notify);
if (doNotAskAgainCheckboxResult) {
GeneralSettings::setConfirmClosingMultipleTabs(false);
}
switch (result) {
- case QDialogButtonBox::Yes:
- // Quit
- break;
- case QDialogButtonBox::No:
- // Close only the current tab
- m_tabWidget->closeTab();
- Q_FALLTHROUGH();
- default:
- event->ignore();
- return;
+ case QDialogButtonBox::Yes:
+ // Quit
+ break;
+ case QDialogButtonBox::No:
+ // Close only the current tab
+ m_tabWidget->closeTab();
+ Q_FALLTHROUGH();
+ default:
+ event->ignore();
+ return;
}
}
QDialogButtonBox *buttons = new QDialogButtonBox(standardButtons);
KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), KStandardGuiItem::quit());
if (!m_terminalPanel->isVisible()) {
- KGuiItem::assign(
- buttons->button(QDialogButtonBox::No),
- KGuiItem(i18n("Show &Terminal Panel"), QIcon::fromTheme(QStringLiteral("dialog-scripts"))));
+ KGuiItem::assign(buttons->button(QDialogButtonBox::No), KGuiItem(i18n("Show &Terminal Panel"), QIcon::fromTheme(QStringLiteral("dialog-scripts"))));
}
KGuiItem::assign(buttons->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel());
bool doNotAskAgainCheckboxResult = false;
const auto result = KMessageBox::createKMessageBox(
- dialog,
- buttons,
- QMessageBox::Warning,
- i18n("The program '%1' is still running in the Terminal panel. Are you sure you want to quit?", m_terminalPanel->runningProgramName()),
- QStringList(),
- i18n("Do not ask again"),
- &doNotAskAgainCheckboxResult,
- KMessageBox::Dangerous);
+ dialog,
+ buttons,
+ QMessageBox::Warning,
+ i18n("The program '%1' is still running in the Terminal panel. Are you sure you want to quit?", m_terminalPanel->runningProgramName()),
+ QStringList(),
+ i18n("Do not ask again"),
+ &doNotAskAgainCheckboxResult,
+ KMessageBox::Dangerous);
if (doNotAskAgainCheckboxResult) {
GeneralSettings::setConfirmClosingTerminalRunningProgram(false);
}
switch (result) {
- case QDialogButtonBox::Yes:
- // Quit
- break;
- case QDialogButtonBox::No:
- actionCollection()->action("show_terminal_panel")->trigger();
- // Do not quit, ignore quit event
- Q_FALLTHROUGH();
- default:
- event->ignore();
- return;
+ case QDialogButtonBox::Yes:
+ // Quit
+ break;
+ case QDialogButtonBox::No:
+ actionCollection()->action("show_terminal_panel")->trigger();
+ // Do not quit, ignore quit event
+ Q_FALLTHROUGH();
+ default:
+ event->ignore();
+ return;
}
}
- if (GeneralSettings::rememberOpenedTabs()) {
+ if (GeneralSettings::rememberOpenedTabs()) {
KConfigGui::setSessionConfig(QStringLiteral("dolphin"), QStringLiteral("dolphin"));
KConfig *config = KConfigGui::sessionConfig();
saveGlobalProperties(config);
KXmlGuiWindow::closeEvent(event);
}
-void DolphinMainWindow::saveProperties(KConfigGroup& group)
+void DolphinMainWindow::saveProperties(KConfigGroup &group)
{
m_tabWidget->saveProperties(group);
}
-void DolphinMainWindow::readProperties(const KConfigGroup& group)
+void DolphinMainWindow::readProperties(const KConfigGroup &group)
{
m_tabWidget->readProperties(group);
}
close();
}
-void DolphinMainWindow::showErrorMessage(const QString& message)
+void DolphinMainWindow::showErrorMessage(const QString &message)
{
m_activeViewContainer->showMessage(message, DolphinViewContainer::Error);
}
void DolphinMainWindow::slotUndoAvailable(bool available)
{
- QAction* undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo));
+ QAction *undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo));
if (undoAction) {
undoAction->setEnabled(available);
}
}
-void DolphinMainWindow::slotUndoTextChanged(const QString& text)
+void DolphinMainWindow::slotUndoTextChanged(const QString &text)
{
- QAction* undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo));
+ QAction *undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo));
if (undoAction) {
undoAction->setText(text);
}
void DolphinMainWindow::updateSearchAction()
{
- QAction* toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search"));
+ QAction *toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search"));
toggleSearchAction->setChecked(m_activeViewContainer->isSearchModeEnabled());
}
void DolphinMainWindow::updatePasteAction()
{
- QAction* pasteAction = actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
+ QAction *pasteAction = actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
QPair<bool, QString> pasteInfo = m_activeViewContainer->view()->pasteInfo();
pasteAction->setEnabled(pasteInfo.first);
pasteAction->setText(pasteInfo.second);
}
}
-void DolphinMainWindow::slotGoBack(QAction* action)
+void DolphinMainWindow::slotGoBack(QAction *action)
{
int gotoIndex = action->data().value<int>();
const KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigatorInternalWithHistory();
}
}
-void DolphinMainWindow::slotBackForwardActionMiddleClicked(QAction* action)
+void DolphinMainWindow::slotBackForwardActionMiddleClicked(QAction *action)
{
if (action) {
const KUrlNavigator *urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory();
}
}
-void DolphinMainWindow::slotGoForward(QAction* action)
+void DolphinMainWindow::slotGoForward(QAction *action)
{
int gotoIndex = action->data().value<int>();
const KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigatorInternalWithHistory();
// if the URL navigator is editable and focused, select the whole
// URL instead of all items of the view
- KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator();
- QLineEdit* lineEdit = urlNavigator->editor()->lineEdit();
- const bool selectUrl = urlNavigator->isUrlEditable() &&
- lineEdit->hasFocus();
+ KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigator();
+ QLineEdit *lineEdit = urlNavigator->editor()->lineEdit();
+ const bool selectUrl = urlNavigator->isUrlEditable() && lineEdit->hasFocus();
if (selectUrl) {
lineEdit->selectAll();
} else {
void DolphinMainWindow::toggleSplitView()
{
- DolphinTabPage* tabPage = m_tabWidget->currentTabPage();
+ DolphinTabPage *tabPage = m_tabWidget->currentTabPage();
tabPage->setSplitViewEnabled(!tabPage->splitViewEnabled(), WithAnimation);
updateViewActions();
void DolphinMainWindow::toggleSplitStash()
{
- DolphinTabPage* tabPage = m_tabWidget->currentTabPage();
+ DolphinTabPage *tabPage = m_tabWidget->currentTabPage();
tabPage->setSplitViewEnabled(false, WithAnimation);
tabPage->setSplitViewEnabled(true, WithAnimation, QUrl("stash:/"));
}
const bool checked = !m_activeViewContainer->isFilterBarVisible();
m_activeViewContainer->setFilterBarVisible(checked);
- QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
+ QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
toggleFilterBarAction->setChecked(checked);
}
{
clearStatusBar();
- QAction* action = actionCollection()->action(QStringLiteral("editable_location"));
- KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator();
+ QAction *action = actionCollection()->action(QStringLiteral("editable_location"));
+ KUrlNavigator *urlNavigator = m_activeViewContainer->urlNavigator();
urlNavigator->setUrlEditable(action->isChecked());
}
void DolphinMainWindow::replaceLocation()
{
- KUrlNavigator* navigator = m_activeViewContainer->urlNavigator();
- QLineEdit* lineEdit = navigator->editor()->lineEdit();
+ KUrlNavigator *navigator = m_activeViewContainer->urlNavigator();
+ QLineEdit *lineEdit = navigator->editor()->lineEdit();
// If the text field currently has focus and everything is selected,
// pressing the keyboard shortcut returns the whole thing to breadcrumb mode
- if (navigator->isUrlEditable()
- && lineEdit->hasFocus()
- && lineEdit->selectedText() == lineEdit->text() ) {
+ if (navigator->isUrlEditable() && lineEdit->hasFocus() && lineEdit->selectedText() == lineEdit->text()) {
navigator->setUrlEditable(false);
} else {
navigator->setUrlEditable(true);
{
const bool newLockState = !GeneralSettings::lockPanels();
const auto childrenObjects = children();
- for (QObject* child : childrenObjects) {
- DolphinDockWidget* dock = qobject_cast<DolphinDockWidget*>(child);
+ for (QObject *child : childrenObjects) {
+ DolphinDockWidget *dock = qobject_cast<DolphinDockWidget *>(child);
if (dock) {
dock->setLocked(newLockState);
}
void DolphinMainWindow::goBackInNewTab()
{
- const KUrlNavigator* urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory();
+ const KUrlNavigator *urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory();
const int index = urlNavigator->historyIndex() + 1;
openNewTab(urlNavigator->locationUrl(index));
}
void DolphinMainWindow::goForwardInNewTab()
{
- const KUrlNavigator* urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory();
+ const KUrlNavigator *urlNavigator = activeViewContainer()->urlNavigatorInternalWithHistory();
const int index = urlNavigator->historyIndex() - 1;
openNewTab(urlNavigator->locationUrl(index));
}
QPointer<QAction> DolphinMainWindow::preferredSearchTool()
{
m_searchTools.clear();
- KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames(
- &m_searchTools, { "files-find" }, m_activeViewContainer->url()
- );
- QList<QAction*> actions = m_searchTools.actions();
+ KMoreToolsMenuFactory("dolphin/search-tools").fillMenuFromGroupingNames(&m_searchTools, {"files-find"}, m_activeViewContainer->url());
+ QList<QAction *> actions = m_searchTools.actions();
if (actions.isEmpty()) {
return nullptr;
}
- QAction* action = actions.first();
+ QAction *action = actions.first();
if (action->isSeparator()) {
return nullptr;
}
void DolphinMainWindow::updateOpenPreferredSearchToolAction()
{
- QAction* openPreferredSearchTool = actionCollection()->action(QStringLiteral("open_preferred_search_tool"));
+ QAction *openPreferredSearchTool = actionCollection()->action(QStringLiteral("open_preferred_search_tool"));
if (!openPreferredSearchTool) {
return;
}
{
QList<QUrl> urls = {};
- for (const KFileItem& item : m_activeViewContainer->view()->selectedItems()) {
+ for (const KFileItem &item : m_activeViewContainer->view()->selectedItems()) {
QUrl url = item.targetUrl();
if (item.isFile()) {
url.setPath(QFileInfo(url.path()).absolutePath());
}
if (urls.count() > 5) {
- QString question = i18np("Are you sure you want to open 1 terminal window?",
- "Are you sure you want to open %1 terminal windows?", urls.count());
+ QString question = i18np("Are you sure you want to open 1 terminal window?", "Are you sure you want to open %1 terminal windows?", urls.count());
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- const int answer = KMessageBox::warningTwoActions(this, question, {},
+ const int answer = KMessageBox::warningTwoActions(
+ this,
+ question,
+ {},
#else
- const int answer = KMessageBox::warningYesNo(this, question, {},
+ const int answer = KMessageBox::warningYesNo(
+ this,
+ question,
+ {},
#endif
- KGuiItem(i18ncp("@action:button", "Open %1 Terminal", "Open %1 Terminals", urls.count()),
- QStringLiteral("utilities-terminal")),
- KStandardGuiItem::cancel());
+ KGuiItem(i18ncp("@action:button", "Open %1 Terminal", "Open %1 Terminals", urls.count()), QStringLiteral("utilities-terminal")),
+ KStandardGuiItem::cancel());
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
if (answer != KMessageBox::PrimaryAction) {
#else
}
}
- for (const QUrl& url : urls) {
+ for (const QUrl &url : urls) {
openTerminalJob(url);
}
}
-void DolphinMainWindow::openTerminalJob(const QUrl& url)
+void DolphinMainWindow::openTerminalJob(const QUrl &url)
{
if (url.isLocalFile()) {
auto job = new KTerminalLauncherJob(QString());
return;
}
- // Not a local file, with protocol Class ":local", try stat'ing
+ // Not a local file, with protocol Class ":local", try stat'ing
if (KProtocolInfo::protocolClass(url.scheme()) == QLatin1String(":local")) {
KIO::StatJob *job = KIO::mostLocalUrl(url);
KJobWidgets::setWindow(job, this);
void DolphinMainWindow::editSettings()
{
if (!m_settingsDialog) {
- DolphinViewContainer* container = activeViewContainer();
+ DolphinViewContainer *container = activeViewContainer();
container->view()->writeSettings();
const QUrl url = container->url();
- DolphinSettingsDialog* settingsDialog = new DolphinSettingsDialog(url, this, actionCollection());
+ DolphinSettingsDialog *settingsDialog = new DolphinSettingsDialog(url, this, actionCollection());
connect(settingsDialog, &DolphinSettingsDialog::settingsChanged, this, &DolphinMainWindow::refreshViews);
- connect(settingsDialog, &DolphinSettingsDialog::settingsChanged,
- &DolphinUrlNavigatorsController::slotReadSettings);
+ connect(settingsDialog, &DolphinSettingsDialog::settingsChanged, &DolphinUrlNavigatorsController::slotReadSettings);
settingsDialog->setAttribute(Qt::WA_DeleteOnClose);
settingsDialog->show();
m_settingsDialog = settingsDialog;
}
}
-void DolphinMainWindow::handleUrl(const QUrl& url)
+void DolphinMainWindow::handleUrl(const QUrl &url)
{
delete m_lastHandleUrlOpenJob;
m_lastHandleUrlOpenJob = nullptr;
#endif
m_lastHandleUrlOpenJob->setShowOpenOrExecuteDialog(true);
- connect(m_lastHandleUrlOpenJob, &KIO::OpenUrlJob::mimeTypeFound, this,
- [this, url](const QString &mimetype) {
- if (mimetype == QLatin1String("inode/directory")) {
- // If it's a dir, we'll take it from here
- m_lastHandleUrlOpenJob->kill();
- m_lastHandleUrlOpenJob = nullptr;
- activeViewContainer()->setUrl(url);
- }
+ connect(m_lastHandleUrlOpenJob, &KIO::OpenUrlJob::mimeTypeFound, this, [this, url](const QString &mimetype) {
+ if (mimetype == QLatin1String("inode/directory")) {
+ // If it's a dir, we'll take it from here
+ m_lastHandleUrlOpenJob->kill();
+ m_lastHandleUrlOpenJob = nullptr;
+ activeViewContainer()->setUrl(url);
+ }
});
connect(m_lastHandleUrlOpenJob, &KIO::OpenUrlJob::result, this, [this]() {
newFileMenu()->setEnabled(isFolderWritable && m_activeViewContainer->url().scheme() != QLatin1String("trash"));
}
-void DolphinMainWindow::openContextMenu(const QPoint& pos,
- const KFileItem& item,
- const KFileItemList &selectedItems,
- const QUrl& url)
+void DolphinMainWindow::openContextMenu(const QPoint &pos, const KFileItem &item, const KFileItemList &selectedItems, const QUrl &url)
{
QPointer<DolphinContextMenu> contextMenu = new DolphinContextMenu(this, item, selectedItems, url, &m_fileItemActions);
contextMenu.data()->exec(pos);
void DolphinMainWindow::updateHamburgerMenu()
{
- KActionCollection* ac = actionCollection();
- auto hamburgerMenu = static_cast<KHamburgerMenu *>(
- ac->action(KStandardAction::name(KStandardAction::HamburgerMenu)));
+ KActionCollection *ac = actionCollection();
+ auto hamburgerMenu = static_cast<KHamburgerMenu *>(ac->action(KStandardAction::name(KStandardAction::HamburgerMenu)));
auto menu = hamburgerMenu->menu();
if (!menu) {
menu = new QMenu(this);
menu->addAction(ac->action(QStringLiteral("go_forward")));
menu->addMenu(m_newFileMenu->menu());
- if (!toolBar()->isVisible()
- || !toolbarActions.contains(ac->action(QStringLiteral("toggle_selection_mode_tool_bar")))
- ) {
+ if (!toolBar()->isVisible() || !toolbarActions.contains(ac->action(QStringLiteral("toggle_selection_mode_tool_bar")))) {
menu->addAction(ac->action(QStringLiteral("toggle_selection_mode")));
}
menu->addAction(ac->action(QStringLiteral("basic_actions")));
menu->addAction(ac->action(KStandardAction::name(KStandardAction::Undo)));
if (!toolBar()->isVisible()
|| (!toolbarActions.contains(ac->action(QStringLiteral("toggle_search")))
- && !toolbarActions.contains(ac->action(QStringLiteral("open_preferred_search_tool"))))
- ) {
+ && !toolbarActions.contains(ac->action(QStringLiteral("open_preferred_search_tool"))))) {
menu->addAction(ac->action(KStandardAction::name(KStandardAction::Find)));
// This way a search action will only be added if none of the three available
// search actions is present on the toolbar.
}
- if (!toolBar()->isVisible()
- || !toolbarActions.contains(ac->action(QStringLiteral("toggle_filter")))
- ) {
+ if (!toolBar()->isVisible() || !toolbarActions.contains(ac->action(QStringLiteral("toggle_filter")))) {
menu->addAction(ac->action(QStringLiteral("show_filter_bar")));
// This way a filter action will only be added if none of the two available
// filter actions is present on the toolbar.
// The third group contains actions to change what one sees in the view
// and to change the more general UI.
if (!toolBar()->isVisible()
- || (!toolbarActions.contains(ac->action(QStringLiteral("icons")))
- && !toolbarActions.contains(ac->action(QStringLiteral("compact")))
- && !toolbarActions.contains(ac->action(QStringLiteral("details")))
- && !toolbarActions.contains(ac->action(QStringLiteral("view_mode"))))
- ) {
+ || (!toolbarActions.contains(ac->action(QStringLiteral("icons"))) && !toolbarActions.contains(ac->action(QStringLiteral("compact")))
+ && !toolbarActions.contains(ac->action(QStringLiteral("details"))) && !toolbarActions.contains(ac->action(QStringLiteral("view_mode"))))) {
menu->addAction(ac->action(QStringLiteral("view_mode")));
}
menu->addAction(ac->action(QStringLiteral("show_hidden_files")));
// The "Configure" menu is not added to the actionCollection() because there is hardly
// a good reason for users to put it on their toolbar.
- auto configureMenu = menu->addMenu(QIcon::fromTheme(QStringLiteral("configure")),
- i18nc("@action:inmenu menu for configure actions", "Configure"));
+ auto configureMenu = menu->addMenu(QIcon::fromTheme(QStringLiteral("configure")), i18nc("@action:inmenu menu for configure actions", "Configure"));
configureMenu->addAction(ac->action(KStandardAction::name(KStandardAction::SwitchApplicationLanguage)));
configureMenu->addAction(ac->action(KStandardAction::name(KStandardAction::KeyBindings)));
configureMenu->addAction(ac->action(KStandardAction::name(KStandardAction::ConfigureToolbars)));
hamburgerMenu->hideActionsOf(configureMenu);
}
-void DolphinMainWindow::slotPlaceActivated(const QUrl& url)
+void DolphinMainWindow::slotPlaceActivated(const QUrl &url)
{
- DolphinViewContainer* view = activeViewContainer();
+ DolphinViewContainer *view = activeViewContainer();
if (view->url() == url) {
view->clearFilterBar(); // Fixes bug 259382.
actionCollection()->action(QStringLiteral("undo_close_tab"))->setEnabled(count > 0);
}
-void DolphinMainWindow::activeViewChanged(DolphinViewContainer* viewContainer)
+void DolphinMainWindow::activeViewChanged(DolphinViewContainer *viewContainer)
{
- DolphinViewContainer* oldViewContainer = m_activeViewContainer;
+ DolphinViewContainer *oldViewContainer = m_activeViewContainer;
Q_ASSERT(viewContainer);
m_activeViewContainer = viewContainer;
if (oldViewContainer) {
- const QAction* toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search"));
+ const QAction *toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search"));
toggleSearchAction->disconnect(oldViewContainer);
// Disconnect all signals between the old view container (container,
oldViewContainer->disconnect(this);
oldViewContainer->view()->disconnect(this);
oldViewContainer->urlNavigatorInternalWithHistory()->disconnect(this);
- auto navigators = static_cast<DolphinNavigatorsWidgetAction *>
- (actionCollection()->action(QStringLiteral("url_navigators")));
+ auto navigators = static_cast<DolphinNavigatorsWidgetAction *>(actionCollection()->action(QStringLiteral("url_navigators")));
navigators->primaryUrlNavigator()->disconnect(this);
if (auto secondaryUrlNavigator = navigators->secondaryUrlNavigator()) {
secondaryUrlNavigator->disconnect(this);
}
// except the requestItemInfo so that on hover the information panel can still be updated
- connect(oldViewContainer->view(), &DolphinView::requestItemInfo,
- this, &DolphinMainWindow::requestItemInfo);
+ connect(oldViewContainer->view(), &DolphinView::requestItemInfo, this, &DolphinMainWindow::requestItemInfo);
// Disconnect other slots.
- disconnect(nullptr, &DolphinViewContainer::selectionModeChanged,
- actionCollection()->action(QStringLiteral("toggle_selection_mode")), &QAction::setChecked);
+ disconnect(nullptr,
+ &DolphinViewContainer::selectionModeChanged,
+ actionCollection()->action(QStringLiteral("toggle_selection_mode")),
+ &QAction::setChecked);
}
connectViewSignals(viewContainer);
}
}
-void DolphinMainWindow::slotStorageTearDownFromPlacesRequested(const QString& mountPath)
+void DolphinMainWindow::slotStorageTearDownFromPlacesRequested(const QString &mountPath)
{
connect(m_placesPanel, &PlacesPanel::storageTearDownSuccessful, this, [this, mountPath]() {
setViewsToHomeIfMountPathOpen(mountPath);
}
}
-void DolphinMainWindow::slotStorageTearDownExternallyRequested(const QString& mountPath)
+void DolphinMainWindow::slotStorageTearDownExternallyRequested(const QString &mountPath)
{
connect(m_placesPanel, &PlacesPanel::storageTearDownSuccessful, this, [this, mountPath]() {
setViewsToHomeIfMountPathOpen(mountPath);
dialog.configure();
}
-void DolphinMainWindow::setViewsToHomeIfMountPathOpen(const QString& mountPath)
+void DolphinMainWindow::setViewsToHomeIfMountPathOpen(const QString &mountPath)
{
- const QVector<DolphinViewContainer*> theViewContainers = viewContainers();
+ const QVector<DolphinViewContainer *> theViewContainers = viewContainers();
for (DolphinViewContainer *viewContainer : theViewContainers) {
if (viewContainer && viewContainer->url().toLocalFile().startsWith(mountPath)) {
viewContainer->setUrl(QUrl::fromLocalFile(QDir::homePath()));
// setup 'File' menu
m_newFileMenu = new DolphinNewFileMenu(actionCollection(), this);
- QMenu* menu = m_newFileMenu->menu();
+ QMenu *menu = m_newFileMenu->menu();
menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
menu->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
m_newFileMenu->setPopupMode(QToolButton::InstantPopup);
- connect(menu, &QMenu::aboutToShow,
- this, &DolphinMainWindow::updateNewMenu);
+ connect(menu, &QMenu::aboutToShow, this, &DolphinMainWindow::updateNewMenu);
- QAction* newWindow = KStandardAction::openNew(this, &DolphinMainWindow::openNewMainWindow, actionCollection());
+ QAction *newWindow = KStandardAction::openNew(this, &DolphinMainWindow::openNewMainWindow, actionCollection());
newWindow->setText(i18nc("@action:inmenu File", "New &Window"));
newWindow->setToolTip(i18nc("@info", "Open a new Dolphin window"));
- newWindow->setWhatsThis(xi18nc("@info:whatsthis", "This opens a new "
- "window just like this one with the current location and view."
- "<nl/>You can drag and drop items between windows."));
+ newWindow->setWhatsThis(xi18nc("@info:whatsthis",
+ "This opens a new "
+ "window just like this one with the current location and view."
+ "<nl/>You can drag and drop items between windows."));
newWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new")));
- QAction* newTab = actionCollection()->addAction(QStringLiteral("new_tab"));
+ QAction *newTab = actionCollection()->addAction(QStringLiteral("new_tab"));
newTab->setIcon(QIcon::fromTheme(QStringLiteral("tab-new")));
newTab->setText(i18nc("@action:inmenu File", "New Tab"));
- newTab->setWhatsThis(xi18nc("@info:whatsthis", "This opens a new "
- "<emphasis>Tab</emphasis> with the current location and view.<nl/>"
- "A tab is an additional view within this window. "
- "You can drag and drop items between tabs."));
+ newTab->setWhatsThis(xi18nc("@info:whatsthis",
+ "This opens a new "
+ "<emphasis>Tab</emphasis> with the current location and view.<nl/>"
+ "A tab is an additional view within this window. "
+ "You can drag and drop items between tabs."));
actionCollection()->setDefaultShortcuts(newTab, {Qt::CTRL | Qt::Key_T, Qt::CTRL | Qt::SHIFT | Qt::Key_N});
connect(newTab, &QAction::triggered, this, &DolphinMainWindow::openNewActivatedTab);
- QAction* addToPlaces = actionCollection()->addAction(QStringLiteral("add_to_places"));
+ QAction *addToPlaces = actionCollection()->addAction(QStringLiteral("add_to_places"));
addToPlaces->setIcon(QIcon::fromTheme(QStringLiteral("bookmark-new")));
addToPlaces->setText(i18nc("@action:inmenu Add current folder to places", "Add to Places"));
- addToPlaces->setWhatsThis(xi18nc("@info:whatsthis", "This adds the selected folder "
- "to the Places panel."));
+ addToPlaces->setWhatsThis(xi18nc("@info:whatsthis",
+ "This adds the selected folder "
+ "to the Places panel."));
connect(addToPlaces, &QAction::triggered, this, &DolphinMainWindow::addToPlaces);
- QAction* closeTab = KStandardAction::close(m_tabWidget, QOverload<>::of(&DolphinTabWidget::closeTab), actionCollection());
+ QAction *closeTab = KStandardAction::close(m_tabWidget, QOverload<>::of(&DolphinTabWidget::closeTab), actionCollection());
closeTab->setText(i18nc("@action:inmenu File", "Close Tab"));
- closeTab->setWhatsThis(i18nc("@info:whatsthis", "This closes the "
- "currently viewed tab. If no more tabs are left this window "
- "will close instead."));
+ closeTab->setWhatsThis(i18nc("@info:whatsthis",
+ "This closes the "
+ "currently viewed tab. If no more tabs are left this window "
+ "will close instead."));
- QAction* quitAction = KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection());
+ QAction *quitAction = KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection());
quitAction->setWhatsThis(i18nc("@info:whatsthis quit", "This closes this window."));
// setup 'Edit' menu
- KStandardAction::undo(this,
- &DolphinMainWindow::undo,
- actionCollection());
+ KStandardAction::undo(this, &DolphinMainWindow::undo, actionCollection());
// i18n: This will be the last paragraph for the whatsthis for all three:
// Cut, Copy and Paste
- const QString cutCopyPastePara = xi18nc("@info:whatsthis", "<para><emphasis>Cut, "
- "Copy</emphasis> and <emphasis>Paste</emphasis> work between many "
- "applications and are among the most used commands. That's why their "
- "<emphasis>keyboard shortcuts</emphasis> are prominently placed right "
- "next to each other on the keyboard: <shortcut>Ctrl+X</shortcut>, "
- "<shortcut>Ctrl+C</shortcut> and <shortcut>Ctrl+V</shortcut>.</para>");
- QAction* cutAction = KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection());
+ const QString cutCopyPastePara = xi18nc("@info:whatsthis",
+ "<para><emphasis>Cut, "
+ "Copy</emphasis> and <emphasis>Paste</emphasis> work between many "
+ "applications and are among the most used commands. That's why their "
+ "<emphasis>keyboard shortcuts</emphasis> are prominently placed right "
+ "next to each other on the keyboard: <shortcut>Ctrl+X</shortcut>, "
+ "<shortcut>Ctrl+C</shortcut> and <shortcut>Ctrl+V</shortcut>.</para>");
+ QAction *cutAction = KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection());
m_actionTextHelper->registerTextWhenNothingIsSelected(cutAction, i18nc("@action", "Cut…"));
- cutAction->setWhatsThis(xi18nc("@info:whatsthis cut", "This copies the items "
- "in your current selection to the <emphasis>clipboard</emphasis>.<nl/>"
- "Use the <emphasis>Paste</emphasis> action afterwards to copy them from "
- "the clipboard to a new location. The items will be removed from their "
- "initial location.") + cutCopyPastePara);
- QAction* copyAction = KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection());
+ cutAction->setWhatsThis(xi18nc("@info:whatsthis cut",
+ "This copies the items "
+ "in your current selection to the <emphasis>clipboard</emphasis>.<nl/>"
+ "Use the <emphasis>Paste</emphasis> action afterwards to copy them from "
+ "the clipboard to a new location. The items will be removed from their "
+ "initial location.")
+ + cutCopyPastePara);
+ QAction *copyAction = KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection());
m_actionTextHelper->registerTextWhenNothingIsSelected(copyAction, i18nc("@action", "Copy…"));
- copyAction->setWhatsThis(xi18nc("@info:whatsthis copy", "This copies the "
- "items in your current selection to the <emphasis>clipboard</emphasis>."
- "<nl/>Use the <emphasis>Paste</emphasis> action afterwards to copy them "
- "from the clipboard to a new location.") + cutCopyPastePara);
- QAction* paste = KStandardAction::paste(this, &DolphinMainWindow::paste, actionCollection());
+ copyAction->setWhatsThis(xi18nc("@info:whatsthis copy",
+ "This copies the "
+ "items in your current selection to the <emphasis>clipboard</emphasis>."
+ "<nl/>Use the <emphasis>Paste</emphasis> action afterwards to copy them "
+ "from the clipboard to a new location.")
+ + cutCopyPastePara);
+ QAction *paste = KStandardAction::paste(this, &DolphinMainWindow::paste, actionCollection());
// The text of the paste-action is modified dynamically by Dolphin
// (e. g. to "Paste One Folder"). To prevent that the size of the toolbar changes
// due to the long text, the text "Paste" is used:
paste->setIconText(i18nc("@action:inmenu Edit", "Paste"));
- paste->setWhatsThis(xi18nc("@info:whatsthis paste", "This copies the items from "
- "your <emphasis>clipboard</emphasis> to the currently viewed folder.<nl/>"
- "If the items were added to the clipboard by the <emphasis>Cut</emphasis> "
- "action they are removed from their old location.") + cutCopyPastePara);
-
- QAction* copyToOtherViewAction = actionCollection()->addAction(QStringLiteral("copy_to_inactive_split_view"));
+ paste->setWhatsThis(xi18nc("@info:whatsthis paste",
+ "This copies the items from "
+ "your <emphasis>clipboard</emphasis> to the currently viewed folder.<nl/>"
+ "If the items were added to the clipboard by the <emphasis>Cut</emphasis> "
+ "action they are removed from their old location.")
+ + cutCopyPastePara);
+
+ QAction *copyToOtherViewAction = actionCollection()->addAction(QStringLiteral("copy_to_inactive_split_view"));
copyToOtherViewAction->setText(i18nc("@action:inmenu", "Copy to Inactive Split View"));
m_actionTextHelper->registerTextWhenNothingIsSelected(copyToOtherViewAction, i18nc("@action:inmenu", "Copy to Inactive Split View…"));
- copyToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Copy", "This copies the selected items from "
- "the <emphasis>active</emphasis> view to the inactive split view."));
+ copyToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Copy",
+ "This copies the selected items from "
+ "the <emphasis>active</emphasis> view to the inactive split view."));
copyToOtherViewAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy")));
copyToOtherViewAction->setIconText(i18nc("@action:inmenu Edit", "Copy to Inactive Split View"));
- actionCollection()->setDefaultShortcut(copyToOtherViewAction, Qt::SHIFT | Qt::Key_F5 );
+ actionCollection()->setDefaultShortcut(copyToOtherViewAction, Qt::SHIFT | Qt::Key_F5);
connect(copyToOtherViewAction, &QAction::triggered, this, &DolphinMainWindow::copyToInactiveSplitView);
- QAction* moveToOtherViewAction = actionCollection()->addAction(QStringLiteral("move_to_inactive_split_view"));
+ QAction *moveToOtherViewAction = actionCollection()->addAction(QStringLiteral("move_to_inactive_split_view"));
moveToOtherViewAction->setText(i18nc("@action:inmenu", "Move to Inactive Split View"));
m_actionTextHelper->registerTextWhenNothingIsSelected(moveToOtherViewAction, i18nc("@action:inmenu", "Move to Inactive Split View…"));
- moveToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Move", "This moves the selected items from "
- "the <emphasis>active</emphasis> view to the inactive split view."));
+ moveToOtherViewAction->setWhatsThis(xi18nc("@info:whatsthis Move",
+ "This moves the selected items from "
+ "the <emphasis>active</emphasis> view to the inactive split view."));
moveToOtherViewAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-cut")));
moveToOtherViewAction->setIconText(i18nc("@action:inmenu Edit", "Move to Inactive Split View"));
- actionCollection()->setDefaultShortcut(moveToOtherViewAction, Qt::SHIFT | Qt::Key_F6 );
+ actionCollection()->setDefaultShortcut(moveToOtherViewAction, Qt::SHIFT | Qt::Key_F6);
connect(moveToOtherViewAction, &QAction::triggered, this, &DolphinMainWindow::moveToInactiveSplitView);
- QAction* showFilterBar = actionCollection()->addAction(QStringLiteral("show_filter_bar"));
+ QAction *showFilterBar = actionCollection()->addAction(QStringLiteral("show_filter_bar"));
showFilterBar->setText(i18nc("@action:inmenu Tools", "Filter..."));
showFilterBar->setToolTip(i18nc("@info:tooltip", "Show Filter Bar"));
- showFilterBar->setWhatsThis(xi18nc("@info:whatsthis", "This opens the "
- "<emphasis>Filter Bar</emphasis> at the bottom of the window.<nl/> "
- "There you can enter a text to filter the files and folders currently displayed. "
- "Only those that contain the text in their name will be kept in view."));
+ showFilterBar->setWhatsThis(xi18nc("@info:whatsthis",
+ "This opens the "
+ "<emphasis>Filter Bar</emphasis> at the bottom of the window.<nl/> "
+ "There you can enter a text to filter the files and folders currently displayed. "
+ "Only those that contain the text in their name will be kept in view."));
showFilterBar->setIcon(QIcon::fromTheme(QStringLiteral("view-filter")));
actionCollection()->setDefaultShortcuts(showFilterBar, {Qt::CTRL | Qt::Key_I, Qt::Key_Slash});
connect(showFilterBar, &QAction::triggered, this, &DolphinMainWindow::showFilterBar);
QAction *searchAction = KStandardAction::find(this, &DolphinMainWindow::find, actionCollection());
searchAction->setText(i18n("Search..."));
searchAction->setToolTip(i18nc("@info:tooltip", "Search for files and folders"));
- searchAction->setWhatsThis(xi18nc("@info:whatsthis find", "<para>This helps you "
- "find files and folders by opening a <emphasis>find bar</emphasis>. "
- "There you can enter search terms and specify settings to find the "
- "objects you are looking for.</para><para>Use this help again on "
- "the find bar so we can have a look at it while the settings are "
- "explained.</para>"));
+ searchAction->setWhatsThis(xi18nc("@info:whatsthis find",
+ "<para>This helps you "
+ "find files and folders by opening a <emphasis>find bar</emphasis>. "
+ "There you can enter search terms and specify settings to find the "
+ "objects you are looking for.</para><para>Use this help again on "
+ "the find bar so we can have a look at it while the settings are "
+ "explained.</para>"));
// toggle_search acts as a copy of the main searchAction to be used mainly
// in the toolbar, with no default shortcut attached, to avoid messing with
// i18n: Opens a selection mode for selecting files/folders.
// The text is kept so unspecific because it will be shown on the toolbar where space is at a premium.
toggleSelectionModeAction->setIconText(i18nc("@action:intoolbar", "Select"));
- toggleSelectionModeAction->setWhatsThis(xi18nc("@info:whatsthis", "<para>This application only knows which files or folders should be acted on if they are"
+ toggleSelectionModeAction->setWhatsThis(xi18nc(
+ "@info:whatsthis",
+ "<para>This application only knows which files or folders should be acted on if they are"
" <emphasis>selected</emphasis> first. Press this to toggle a <emphasis>Selection Mode</emphasis> which makes selecting and deselecting as easy as "
"pressing an item once.</para><para>While in this mode, a quick access bar at the bottom shows available actions for the currently selected items."
"</para>"));
// A special version of the toggleSelectionModeAction for the toolbar that also contains a menu
// with the selectAllAction and invertSelectionAction.
- auto *toggleSelectionModeToolBarAction = new KToolBarPopupAction(toggleSelectionModeAction->icon(), toggleSelectionModeAction->iconText(), actionCollection());
+ auto *toggleSelectionModeToolBarAction =
+ new KToolBarPopupAction(toggleSelectionModeAction->icon(), toggleSelectionModeAction->iconText(), actionCollection());
toggleSelectionModeToolBarAction->setToolTip(toggleSelectionModeAction->text());
toggleSelectionModeToolBarAction->setWhatsThis(toggleSelectionModeAction->whatsThis());
actionCollection()->addAction(QStringLiteral("toggle_selection_mode_tool_bar"), toggleSelectionModeToolBarAction);
connect(toggleSelectionModeToolBarAction, &QAction::triggered, toggleSelectionModeAction, &QAction::trigger);
connect(toggleSelectionModeAction, &QAction::toggled, toggleSelectionModeToolBarAction, &QAction::setChecked);
- QAction* selectAllAction = KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection());
- selectAllAction->setWhatsThis(xi18nc("@info:whatsthis", "This selects all "
- "files and folders in the current location."));
+ QAction *selectAllAction = KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection());
+ selectAllAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "This selects all "
+ "files and folders in the current location."));
- QAction* invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection"));
+ QAction *invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection"));
invertSelection->setText(i18nc("@action:inmenu Edit", "Invert Selection"));
- invertSelection->setWhatsThis(xi18nc("@info:whatsthis invert", "This selects all "
- "objects that you have currently <emphasis>not</emphasis> selected instead."));
+ invertSelection->setWhatsThis(xi18nc("@info:whatsthis invert",
+ "This selects all "
+ "objects that you have currently <emphasis>not</emphasis> selected instead."));
invertSelection->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-invert")));
actionCollection()->setDefaultShortcut(invertSelection, Qt::CTRL | Qt::SHIFT | Qt::Key_A);
connect(invertSelection, &QAction::triggered, this, &DolphinMainWindow::invertSelection);
// setup 'View' menu
// (note that most of it is set up in DolphinViewActionHandler)
- QAction* split = actionCollection()->addAction(QStringLiteral("split_view"));
- split->setWhatsThis(xi18nc("@info:whatsthis find", "<para>This splits "
- "the folder view below into two autonomous views.</para><para>This "
- "way you can see two locations at once and move items between them "
- "quickly.</para>Click this again afterwards to recombine the views."));
+ QAction *split = actionCollection()->addAction(QStringLiteral("split_view"));
+ split->setWhatsThis(xi18nc("@info:whatsthis find",
+ "<para>This splits "
+ "the folder view below into two autonomous views.</para><para>This "
+ "way you can see two locations at once and move items between them "
+ "quickly.</para>Click this again afterwards to recombine the views."));
actionCollection()->setDefaultShortcut(split, Qt::Key_F3);
connect(split, &QAction::triggered, this, &DolphinMainWindow::toggleSplitView);
- QAction* stashSplit = actionCollection()->addAction(QStringLiteral("split_stash"));
+ QAction *stashSplit = actionCollection()->addAction(QStringLiteral("split_stash"));
actionCollection()->setDefaultShortcut(stashSplit, Qt::CTRL | Qt::Key_S);
stashSplit->setText(i18nc("@action:intoolbar Stash", "Stash"));
stashSplit->setToolTip(i18nc("@info", "Opens the stash virtual directory in a split window"));
KStandardAction::redisplay(this, &DolphinMainWindow::reloadView, actionCollection());
- QAction* stop = actionCollection()->addAction(QStringLiteral("stop"));
+ QAction *stop = actionCollection()->addAction(QStringLiteral("stop"));
stop->setText(i18nc("@action:inmenu View", "Stop"));
stop->setToolTip(i18nc("@info", "Stop loading"));
stop->setWhatsThis(i18nc("@info", "This stops the loading of the contents of the current folder."));
stop->setIcon(QIcon::fromTheme(QStringLiteral("process-stop")));
connect(stop, &QAction::triggered, this, &DolphinMainWindow::stopLoading);
- KToggleAction* editableLocation = actionCollection()->add<KToggleAction>(QStringLiteral("editable_location"));
+ KToggleAction *editableLocation = actionCollection()->add<KToggleAction>(QStringLiteral("editable_location"));
editableLocation->setText(i18nc("@action:inmenu Navigation Bar", "Editable Location"));
editableLocation->setWhatsThis(xi18nc("@info:whatsthis",
- "This toggles the <emphasis>Location Bar</emphasis> to be "
- "editable so you can directly enter a location you want to go to.<nl/>"
- "You can also switch to editing by clicking to the right of the "
- "location and switch back by confirming the edited location."));
+ "This toggles the <emphasis>Location Bar</emphasis> to be "
+ "editable so you can directly enter a location you want to go to.<nl/>"
+ "You can also switch to editing by clicking to the right of the "
+ "location and switch back by confirming the edited location."));
actionCollection()->setDefaultShortcut(editableLocation, Qt::Key_F6);
connect(editableLocation, &KToggleAction::triggered, this, &DolphinMainWindow::toggleEditLocation);
- QAction* replaceLocation = actionCollection()->addAction(QStringLiteral("replace_location"));
+ QAction *replaceLocation = actionCollection()->addAction(QStringLiteral("replace_location"));
replaceLocation->setText(i18nc("@action:inmenu Navigation Bar", "Replace Location"));
// i18n: "enter" is used both in the meaning of "writing" and "going to" a new location here.
// Both meanings are useful but not necessary to understand the use of "Replace Location".
// So you might want to be more verbose in your language to convey the meaning but it's up to you.
replaceLocation->setWhatsThis(xi18nc("@info:whatsthis",
- "This switches to editing the location and selects it "
- "so you can quickly enter a different location."));
+ "This switches to editing the location and selects it "
+ "so you can quickly enter a different location."));
actionCollection()->setDefaultShortcut(replaceLocation, Qt::CTRL | Qt::Key_L);
connect(replaceLocation, &QAction::triggered, this, &DolphinMainWindow::replaceLocation);
backShortcuts.append(QKeySequence(Qt::Key_Backspace));
actionCollection()->setDefaultShortcuts(m_backAction, backShortcuts);
- DolphinRecentTabsMenu* recentTabsMenu = new DolphinRecentTabsMenu(this);
+ DolphinRecentTabsMenu *recentTabsMenu = new DolphinRecentTabsMenu(this);
actionCollection()->addAction(QStringLiteral("closed_tabs"), recentTabsMenu);
- connect(m_tabWidget, &DolphinTabWidget::rememberClosedTab,
- recentTabsMenu, &DolphinRecentTabsMenu::rememberClosedTab);
- connect(recentTabsMenu, &DolphinRecentTabsMenu::restoreClosedTab,
- m_tabWidget, &DolphinTabWidget::restoreClosedTab);
- connect(recentTabsMenu, &DolphinRecentTabsMenu::closedTabsCountChanged,
- this, &DolphinMainWindow::closedTabsCountChanged);
-
- QAction* undoCloseTab = actionCollection()->addAction(QStringLiteral("undo_close_tab"));
+ connect(m_tabWidget, &DolphinTabWidget::rememberClosedTab, recentTabsMenu, &DolphinRecentTabsMenu::rememberClosedTab);
+ connect(recentTabsMenu, &DolphinRecentTabsMenu::restoreClosedTab, m_tabWidget, &DolphinTabWidget::restoreClosedTab);
+ connect(recentTabsMenu, &DolphinRecentTabsMenu::closedTabsCountChanged, this, &DolphinMainWindow::closedTabsCountChanged);
+
+ QAction *undoCloseTab = actionCollection()->addAction(QStringLiteral("undo_close_tab"));
undoCloseTab->setText(i18nc("@action:inmenu File", "Undo close tab"));
- undoCloseTab->setWhatsThis(i18nc("@info:whatsthis undo close tab",
- "This returns you to the previously closed tab."));
+ undoCloseTab->setWhatsThis(i18nc("@info:whatsthis undo close tab", "This returns you to the previously closed tab."));
actionCollection()->setDefaultShortcut(undoCloseTab, Qt::CTRL | Qt::SHIFT | Qt::Key_T);
undoCloseTab->setIcon(QIcon::fromTheme(QStringLiteral("edit-undo")));
undoCloseTab->setEnabled(false);
connect(undoCloseTab, &QAction::triggered, recentTabsMenu, &DolphinRecentTabsMenu::undoCloseTab);
auto undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo));
- undoAction->setWhatsThis(xi18nc("@info:whatsthis", "This undoes "
- "the last change you made to files or folders.<nl/>"
- "Such changes include <interface>creating, renaming</interface> "
- "and <interface>moving</interface> them to a different location "
- "or to the <filename>Trash</filename>. <nl/>Changes that can't "
- "be undone will ask for your confirmation."));
+ undoAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "This undoes "
+ "the last change you made to files or folders.<nl/>"
+ "Such changes include <interface>creating, renaming</interface> "
+ "and <interface>moving</interface> them to a different location "
+ "or to the <filename>Trash</filename>. <nl/>Changes that can't "
+ "be undone will ask for your confirmation."));
undoAction->setEnabled(false); // undo should be disabled by default
{
m_backAction->menu()->installEventFilter(middleClickEventFilter);
m_forwardAction->menu()->installEventFilter(middleClickEventFilter);
KStandardAction::up(this, &DolphinMainWindow::goUp, actionCollection());
- QAction* homeAction = KStandardAction::home(this, &DolphinMainWindow::goHome, actionCollection());
- homeAction->setWhatsThis(xi18nc("@info:whatsthis", "Go to your "
- "<filename>Home</filename> folder.<nl/>Every user account "
- "has their own <filename>Home</filename> that contains their data "
- "including folders that contain personal application data."));
+ QAction *homeAction = KStandardAction::home(this, &DolphinMainWindow::goHome, actionCollection());
+ homeAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "Go to your "
+ "<filename>Home</filename> folder.<nl/>Every user account "
+ "has their own <filename>Home</filename> that contains their data "
+ "including folders that contain personal application data."));
// setup 'Tools' menu
- QAction* compareFiles = actionCollection()->addAction(QStringLiteral("compare_files"));
+ QAction *compareFiles = actionCollection()->addAction(QStringLiteral("compare_files"));
compareFiles->setText(i18nc("@action:inmenu Tools", "Compare Files"));
compareFiles->setIcon(QIcon::fromTheme(QStringLiteral("kompare")));
compareFiles->setEnabled(false);
connect(compareFiles, &QAction::triggered, this, &DolphinMainWindow::compareFiles);
- QAction* openPreferredSearchTool = actionCollection()->addAction(QStringLiteral("open_preferred_search_tool"));
+ QAction *openPreferredSearchTool = actionCollection()->addAction(QStringLiteral("open_preferred_search_tool"));
openPreferredSearchTool->setText(i18nc("@action:inmenu Tools", "Open Preferred Search Tool"));
openPreferredSearchTool->setWhatsThis(xi18nc("@info:whatsthis",
- "<para>This opens a preferred search tool for the viewed location.</para>"
- "<para>Use <emphasis>More Search Tools</emphasis> menu to configure it.</para>"));
+ "<para>This opens a preferred search tool for the viewed location.</para>"
+ "<para>Use <emphasis>More Search Tools</emphasis> menu to configure it.</para>"));
openPreferredSearchTool->setIcon(QIcon::fromTheme(QStringLiteral("search")));
actionCollection()->setDefaultShortcut(openPreferredSearchTool, Qt::CTRL | Qt::SHIFT | Qt::Key_F);
connect(openPreferredSearchTool, &QAction::triggered, this, &DolphinMainWindow::openPreferredSearchTool);
if (KAuthorized::authorize(QStringLiteral("shell_access"))) {
- QAction* openTerminal = actionCollection()->addAction(QStringLiteral("open_terminal"));
+ QAction *openTerminal = actionCollection()->addAction(QStringLiteral("open_terminal"));
openTerminal->setText(i18nc("@action:inmenu Tools", "Open Terminal"));
openTerminal->setWhatsThis(xi18nc("@info:whatsthis",
- "<para>This opens a <emphasis>terminal</emphasis> application for the viewed location.</para>"
- "<para>To learn more about terminals use the help in the terminal application.</para>"));
+ "<para>This opens a <emphasis>terminal</emphasis> application for the viewed location.</para>"
+ "<para>To learn more about terminals use the help in the terminal application.</para>"));
openTerminal->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal")));
actionCollection()->setDefaultShortcut(openTerminal, Qt::SHIFT | Qt::Key_F4);
connect(openTerminal, &QAction::triggered, this, &DolphinMainWindow::openTerminal);
- QAction* openTerminalHere = actionCollection()->addAction(QStringLiteral("open_terminal_here"));
+ QAction *openTerminalHere = actionCollection()->addAction(QStringLiteral("open_terminal_here"));
// i18n: "Here" refers to the location(s) of the currently selected item(s) or the currently viewed location if nothing is selected.
openTerminalHere->setText(i18nc("@action:inmenu Tools", "Open Terminal Here"));
openTerminalHere->setWhatsThis(xi18nc("@info:whatsthis",
- "<para>This opens <emphasis>terminal</emphasis> applications for the selected items' locations.</para>"
- "<para>To learn more about terminals use the help in the terminal application.</para>"));
+ "<para>This opens <emphasis>terminal</emphasis> applications for the selected items' locations.</para>"
+ "<para>To learn more about terminals use the help in the terminal application.</para>"));
openTerminalHere->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal")));
actionCollection()->setDefaultShortcut(openTerminalHere, Qt::SHIFT | Qt::ALT | Qt::Key_F4);
connect(openTerminalHere, &QAction::triggered, this, &DolphinMainWindow::openTerminalHere);
#if HAVE_TERMINAL
- QAction* focusTerminalPanel = actionCollection()->addAction(QStringLiteral("focus_terminal_panel"));
+ QAction *focusTerminalPanel = actionCollection()->addAction(QStringLiteral("focus_terminal_panel"));
focusTerminalPanel->setText(i18nc("@action:inmenu Tools", "Focus Terminal Panel"));
focusTerminalPanel->setIcon(QIcon::fromTheme(QStringLiteral("swap-panels")));
actionCollection()->setDefaultShortcut(focusTerminalPanel, Qt::CTRL | Qt::SHIFT | Qt::Key_F4);
actionCollection()->addAction(QStringLiteral("bookmarks"), bookmarkMenu);
// setup 'Settings' menu
- KToggleAction* showMenuBar = KStandardAction::showMenubar(nullptr, nullptr, actionCollection());
+ KToggleAction *showMenuBar = KStandardAction::showMenubar(nullptr, nullptr, actionCollection());
showMenuBar->setWhatsThis(xi18nc("@info:whatsthis",
- "<para>This switches between having a <emphasis>Menubar</emphasis> "
- "and having a <interface>%1</interface> button. Both "
- "contain mostly the same actions and configuration options.</para>"
- "<para>The Menubar takes up more space but allows for fast and organised access to all "
- "actions an application has to offer.</para><para>The <interface>%1</interface> button "
- "is simpler and small which makes triggering advanced actions more time consuming.</para>", hamburgerMenuAction->text().replace('&', "")));
- connect(showMenuBar, &KToggleAction::triggered, // Fixes #286822
- this, &DolphinMainWindow::toggleShowMenuBar, Qt::QueuedConnection);
-
- KToggleAction* showStatusBar = KStandardAction::showStatusbar(nullptr, nullptr, actionCollection());
+ "<para>This switches between having a <emphasis>Menubar</emphasis> "
+ "and having a <interface>%1</interface> button. Both "
+ "contain mostly the same actions and configuration options.</para>"
+ "<para>The Menubar takes up more space but allows for fast and organised access to all "
+ "actions an application has to offer.</para><para>The <interface>%1</interface> button "
+ "is simpler and small which makes triggering advanced actions more time consuming.</para>",
+ hamburgerMenuAction->text().replace('&', "")));
+ connect(showMenuBar,
+ &KToggleAction::triggered, // Fixes #286822
+ this,
+ &DolphinMainWindow::toggleShowMenuBar,
+ Qt::QueuedConnection);
+
+ KToggleAction *showStatusBar = KStandardAction::showStatusbar(nullptr, nullptr, actionCollection());
showStatusBar->setChecked(GeneralSettings::showStatusBar());
connect(GeneralSettings::self(), &GeneralSettings::showStatusBarChanged, showStatusBar, &KToggleAction::setChecked);
connect(showStatusBar, &KToggleAction::triggered, this, [this](bool checked) {
prevTabKeys.append(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_Tab));
for (int i = 0; i < MaxActivateTabShortcuts; ++i) {
- QAction* activateTab = actionCollection()->addAction(QStringLiteral("activate_tab_%1").arg(i));
+ QAction *activateTab = actionCollection()->addAction(QStringLiteral("activate_tab_%1").arg(i));
activateTab->setText(i18nc("@action:inmenu", "Activate Tab %1", i + 1));
activateTab->setEnabled(false);
- connect(activateTab, &QAction::triggered, this, [this, i]() { m_tabWidget->activateTab(i); });
+ connect(activateTab, &QAction::triggered, this, [this, i]() {
+ m_tabWidget->activateTab(i);
+ });
// only add default shortcuts for the first 9 tabs regardless of MaxActivateTabShortcuts
if (i < 9) {
}
}
- QAction* activateLastTab = actionCollection()->addAction(QStringLiteral("activate_last_tab"));
+ QAction *activateLastTab = actionCollection()->addAction(QStringLiteral("activate_last_tab"));
activateLastTab->setText(i18nc("@action:inmenu", "Activate Last Tab"));
activateLastTab->setEnabled(false);
connect(activateLastTab, &QAction::triggered, m_tabWidget, &DolphinTabWidget::activateLastTab);
actionCollection()->setDefaultShortcut(activateLastTab, Qt::ALT | Qt::Key_0);
- QAction* activateNextTab = actionCollection()->addAction(QStringLiteral("activate_next_tab"));
+ QAction *activateNextTab = actionCollection()->addAction(QStringLiteral("activate_next_tab"));
activateNextTab->setIconText(i18nc("@action:inmenu", "Next Tab"));
activateNextTab->setText(i18nc("@action:inmenu", "Activate Next Tab"));
activateNextTab->setEnabled(false);
connect(activateNextTab, &QAction::triggered, m_tabWidget, &DolphinTabWidget::activateNextTab);
actionCollection()->setDefaultShortcuts(activateNextTab, nextTabKeys);
- QAction* activatePrevTab = actionCollection()->addAction(QStringLiteral("activate_prev_tab"));
+ QAction *activatePrevTab = actionCollection()->addAction(QStringLiteral("activate_prev_tab"));
activatePrevTab->setIconText(i18nc("@action:inmenu", "Previous Tab"));
activatePrevTab->setText(i18nc("@action:inmenu", "Activate Previous Tab"));
activatePrevTab->setEnabled(false);
actionCollection()->setDefaultShortcuts(activatePrevTab, prevTabKeys);
// for context menu
- QAction* showTarget = actionCollection()->addAction(QStringLiteral("show_target"));
+ QAction *showTarget = actionCollection()->addAction(QStringLiteral("show_target"));
showTarget->setText(i18nc("@action:inmenu", "Show Target"));
showTarget->setIcon(QIcon::fromTheme(QStringLiteral("document-open-folder")));
showTarget->setEnabled(false);
connect(showTarget, &QAction::triggered, this, &DolphinMainWindow::showTarget);
- QAction* openInNewTab = actionCollection()->addAction(QStringLiteral("open_in_new_tab"));
+ QAction *openInNewTab = actionCollection()->addAction(QStringLiteral("open_in_new_tab"));
openInNewTab->setText(i18nc("@action:inmenu", "Open in New Tab"));
openInNewTab->setIcon(QIcon::fromTheme(QStringLiteral("tab-new")));
connect(openInNewTab, &QAction::triggered, this, &DolphinMainWindow::openInNewTab);
- QAction* openInNewTabs = actionCollection()->addAction(QStringLiteral("open_in_new_tabs"));
+ QAction *openInNewTabs = actionCollection()->addAction(QStringLiteral("open_in_new_tabs"));
openInNewTabs->setText(i18nc("@action:inmenu", "Open in New Tabs"));
openInNewTabs->setIcon(QIcon::fromTheme(QStringLiteral("tab-new")));
connect(openInNewTabs, &QAction::triggered, this, &DolphinMainWindow::openInNewTab);
- QAction* openInNewWindow = actionCollection()->addAction(QStringLiteral("open_in_new_window"));
+ QAction *openInNewWindow = actionCollection()->addAction(QStringLiteral("open_in_new_window"));
openInNewWindow->setText(i18nc("@action:inmenu", "Open in New Window"));
openInNewWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new")));
connect(openInNewWindow, &QAction::triggered, this, &DolphinMainWindow::openInNewWindow);
DolphinPlacesModelSingleton::instance().placesModel()->setPanelsLocked(lock);
- KDualAction* lockLayoutAction = actionCollection()->add<KDualAction>(QStringLiteral("lock_panels"));
+ KDualAction *lockLayoutAction = actionCollection()->add<KDualAction>(QStringLiteral("lock_panels"));
lockLayoutAction->setActiveText(i18nc("@action:inmenu Panels", "Unlock Panels"));
lockLayoutAction->setActiveIcon(QIcon::fromTheme(QStringLiteral("object-unlocked")));
lockLayoutAction->setInactiveText(i18nc("@action:inmenu Panels", "Lock Panels"));
lockLayoutAction->setInactiveIcon(QIcon::fromTheme(QStringLiteral("object-locked")));
- lockLayoutAction->setWhatsThis(xi18nc("@info:whatsthis", "This "
- "switches between having panels <emphasis>locked</emphasis> or "
- "<emphasis>unlocked</emphasis>.<nl/>Unlocked panels can be "
- "dragged to the other side of the window and have a close "
- "button.<nl/>Locked panels are embedded more cleanly."));
+ lockLayoutAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "This "
+ "switches between having panels <emphasis>locked</emphasis> or "
+ "<emphasis>unlocked</emphasis>.<nl/>Unlocked panels can be "
+ "dragged to the other side of the window and have a close "
+ "button.<nl/>Locked panels are embedded more cleanly."));
lockLayoutAction->setActive(lock);
connect(lockLayoutAction, &KDualAction::triggered, this, &DolphinMainWindow::togglePanelLockState);
// Setup "Information"
- DolphinDockWidget* infoDock = new DolphinDockWidget(i18nc("@title:window", "Information"));
+ DolphinDockWidget *infoDock = new DolphinDockWidget(i18nc("@title:window", "Information"));
infoDock->setLocked(lock);
infoDock->setObjectName(QStringLiteral("infoDock"));
infoDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
#if HAVE_BALOO
- InformationPanel* infoPanel = new InformationPanel(infoDock);
+ InformationPanel *infoPanel = new InformationPanel(infoDock);
infoPanel->setCustomContextMenuActions({lockLayoutAction});
connect(infoPanel, &InformationPanel::urlActivated, this, &DolphinMainWindow::handleUrl);
infoDock->setWidget(infoPanel);
- QAction* infoAction = infoDock->toggleViewAction();
+ QAction *infoAction = infoDock->toggleViewAction();
createPanelAction(QIcon::fromTheme(QStringLiteral("dialog-information")), Qt::Key_F11, infoAction, QStringLiteral("show_information_panel"));
addDockWidget(Qt::RightDockWidgetArea, infoDock);
- connect(this, &DolphinMainWindow::urlChanged,
- infoPanel, &InformationPanel::setUrl);
- connect(this, &DolphinMainWindow::selectionChanged,
- infoPanel, &InformationPanel::setSelection);
- connect(this, &DolphinMainWindow::requestItemInfo,
- infoPanel, &InformationPanel::requestDelayedItemInfo);
- connect(this, &DolphinMainWindow::fileItemsChanged,
- infoPanel, &InformationPanel::slotFilesItemChanged);
+ connect(this, &DolphinMainWindow::urlChanged, infoPanel, &InformationPanel::setUrl);
+ connect(this, &DolphinMainWindow::selectionChanged, infoPanel, &InformationPanel::setSelection);
+ connect(this, &DolphinMainWindow::requestItemInfo, infoPanel, &InformationPanel::requestDelayedItemInfo);
+ connect(this, &DolphinMainWindow::fileItemsChanged, infoPanel, &InformationPanel::slotFilesItemChanged);
#endif
// i18n: This is the last paragraph for the "What's This"-texts of all four panels.
- const QString panelWhatsThis = xi18nc("@info:whatsthis", "<para>To show or "
- "hide panels like this go to <interface>Menu|Panels</interface> "
- "or <interface>View|Panels</interface>.</para>");
+ const QString panelWhatsThis = xi18nc("@info:whatsthis",
+ "<para>To show or "
+ "hide panels like this go to <interface>Menu|Panels</interface> "
+ "or <interface>View|Panels</interface>.</para>");
#if HAVE_BALOO
- actionCollection()->action(QStringLiteral("show_information_panel"))
- ->setWhatsThis(xi18nc("@info:whatsthis", "<para> This toggles the "
- "<emphasis>information</emphasis> panel at the right side of the "
- "window.</para><para>The panel provides in-depth information "
- "about the items your mouse is hovering over or about the selected "
- "items. Otherwise it informs you about the currently viewed folder.<nl/>"
- "For single items a preview of their contents is provided.</para>"));
+ actionCollection()
+ ->action(QStringLiteral("show_information_panel"))
+ ->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para> This toggles the "
+ "<emphasis>information</emphasis> panel at the right side of the "
+ "window.</para><para>The panel provides in-depth information "
+ "about the items your mouse is hovering over or about the selected "
+ "items. Otherwise it informs you about the currently viewed folder.<nl/>"
+ "For single items a preview of their contents is provided.</para>"));
#endif
- infoDock->setWhatsThis(xi18nc("@info:whatsthis", "<para>This panel "
- "provides in-depth information about the items your mouse is "
- "hovering over or about the selected items. Otherwise it informs "
- "you about the currently viewed folder.<nl/>For single items a "
- "preview of their contents is provided.</para><para>You can configure "
- "which and how details are given here by right-clicking.</para>") + panelWhatsThis);
+ infoDock->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>This panel "
+ "provides in-depth information about the items your mouse is "
+ "hovering over or about the selected items. Otherwise it informs "
+ "you about the currently viewed folder.<nl/>For single items a "
+ "preview of their contents is provided.</para><para>You can configure "
+ "which and how details are given here by right-clicking.</para>")
+ + panelWhatsThis);
// Setup "Folders"
- DolphinDockWidget* foldersDock = new DolphinDockWidget(i18nc("@title:window", "Folders"));
+ DolphinDockWidget *foldersDock = new DolphinDockWidget(i18nc("@title:window", "Folders"));
foldersDock->setLocked(lock);
foldersDock->setObjectName(QStringLiteral("foldersDock"));
foldersDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
- FoldersPanel* foldersPanel = new FoldersPanel(foldersDock);
+ FoldersPanel *foldersPanel = new FoldersPanel(foldersDock);
foldersPanel->setCustomContextMenuActions({lockLayoutAction});
foldersDock->setWidget(foldersPanel);
- QAction* foldersAction = foldersDock->toggleViewAction();
+ QAction *foldersAction = foldersDock->toggleViewAction();
createPanelAction(QIcon::fromTheme(QStringLiteral("folder")), Qt::Key_F7, foldersAction, QStringLiteral("show_folders_panel"));
addDockWidget(Qt::LeftDockWidgetArea, foldersDock);
- connect(this, &DolphinMainWindow::urlChanged,
- foldersPanel, &FoldersPanel::setUrl);
- connect(foldersPanel, &FoldersPanel::folderActivated,
- this, &DolphinMainWindow::changeUrl);
- connect(foldersPanel, &FoldersPanel::folderInNewTab,
- this, &DolphinMainWindow::openNewTab);
- connect(foldersPanel, &FoldersPanel::folderInNewActiveTab,
- this, &DolphinMainWindow::openNewTabAndActivate);
- connect(foldersPanel, &FoldersPanel::errorMessage,
- this, &DolphinMainWindow::showErrorMessage);
-
- actionCollection()->action(QStringLiteral("show_folders_panel"))
- ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the "
- "<emphasis>folders</emphasis> panel at the left side of the window."
- "<nl/><nl/>It shows the folders of the <emphasis>file system"
- "</emphasis> in a <emphasis>tree view</emphasis>."));
- foldersDock->setWhatsThis(xi18nc("@info:whatsthis", "<para>This panel "
- "shows the folders of the <emphasis>file system</emphasis> in a "
- "<emphasis>tree view</emphasis>.</para><para>Click a folder to go "
- "there. Click the arrow to the left of a folder to see its subfolders. "
- "This allows quick switching between any folders.</para>") + panelWhatsThis);
+ connect(this, &DolphinMainWindow::urlChanged, foldersPanel, &FoldersPanel::setUrl);
+ connect(foldersPanel, &FoldersPanel::folderActivated, this, &DolphinMainWindow::changeUrl);
+ connect(foldersPanel, &FoldersPanel::folderInNewTab, this, &DolphinMainWindow::openNewTab);
+ connect(foldersPanel, &FoldersPanel::folderInNewActiveTab, this, &DolphinMainWindow::openNewTabAndActivate);
+ connect(foldersPanel, &FoldersPanel::errorMessage, this, &DolphinMainWindow::showErrorMessage);
+
+ actionCollection()
+ ->action(QStringLiteral("show_folders_panel"))
+ ->setWhatsThis(xi18nc("@info:whatsthis",
+ "This toggles the "
+ "<emphasis>folders</emphasis> panel at the left side of the window."
+ "<nl/><nl/>It shows the folders of the <emphasis>file system"
+ "</emphasis> in a <emphasis>tree view</emphasis>."));
+ foldersDock->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>This panel "
+ "shows the folders of the <emphasis>file system</emphasis> in a "
+ "<emphasis>tree view</emphasis>.</para><para>Click a folder to go "
+ "there. Click the arrow to the left of a folder to see its subfolders. "
+ "This allows quick switching between any folders.</para>")
+ + panelWhatsThis);
// Setup "Terminal"
#if HAVE_TERMINAL
if (KAuthorized::authorize(QStringLiteral("shell_access"))) {
- DolphinDockWidget* terminalDock = new DolphinDockWidget(i18nc("@title:window Shell terminal", "Terminal"));
+ DolphinDockWidget *terminalDock = new DolphinDockWidget(i18nc("@title:window Shell terminal", "Terminal"));
terminalDock->setLocked(lock);
terminalDock->setObjectName(QStringLiteral("terminalDock"));
m_terminalPanel = new TerminalPanel(terminalDock);
connect(m_terminalPanel, &TerminalPanel::hideTerminalPanel, terminalDock, &DolphinDockWidget::hide);
connect(m_terminalPanel, &TerminalPanel::changeUrl, this, &DolphinMainWindow::slotTerminalDirectoryChanged);
- connect(terminalDock, &DolphinDockWidget::visibilityChanged,
- m_terminalPanel, &TerminalPanel::dockVisibilityChanged);
- connect(terminalDock, &DolphinDockWidget::visibilityChanged,
- this, &DolphinMainWindow::slotTerminalPanelVisibilityChanged);
+ connect(terminalDock, &DolphinDockWidget::visibilityChanged, m_terminalPanel, &TerminalPanel::dockVisibilityChanged);
+ connect(terminalDock, &DolphinDockWidget::visibilityChanged, this, &DolphinMainWindow::slotTerminalPanelVisibilityChanged);
- QAction* terminalAction = terminalDock->toggleViewAction();
+ QAction *terminalAction = terminalDock->toggleViewAction();
createPanelAction(QIcon::fromTheme(QStringLiteral("dialog-scripts")), Qt::Key_F4, terminalAction, QStringLiteral("show_terminal_panel"));
addDockWidget(Qt::BottomDockWidgetArea, terminalDock);
- connect(this, &DolphinMainWindow::urlChanged,
- m_terminalPanel, &TerminalPanel::setUrl);
+ connect(this, &DolphinMainWindow::urlChanged, m_terminalPanel, &TerminalPanel::setUrl);
if (GeneralSettings::version() < 200) {
terminalDock->hide();
}
- actionCollection()->action(QStringLiteral("show_terminal_panel"))
- ->setWhatsThis(xi18nc("@info:whatsthis", "<para>This toggles the "
- "<emphasis>terminal</emphasis> panel at the bottom of the window."
- "<nl/>The location in the terminal will always match the folder "
- "view so you can navigate using either.</para><para>The terminal "
- "panel is not needed for basic computer usage but can be useful "
- "for advanced tasks. To learn more about terminals use the help "
- "in a standalone terminal application like Konsole.</para>"));
- terminalDock->setWhatsThis(xi18nc("@info:whatsthis", "<para>This is "
- "the <emphasis>terminal</emphasis> panel. It behaves like a "
- "normal terminal but will match the location of the folder view "
- "so you can navigate using either.</para><para>The terminal panel "
- "is not needed for basic computer usage but can be useful for "
- "advanced tasks. To learn more about terminals use the help in a "
- "standalone terminal application like Konsole.</para>") + panelWhatsThis);
+ actionCollection()
+ ->action(QStringLiteral("show_terminal_panel"))
+ ->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>This toggles the "
+ "<emphasis>terminal</emphasis> panel at the bottom of the window."
+ "<nl/>The location in the terminal will always match the folder "
+ "view so you can navigate using either.</para><para>The terminal "
+ "panel is not needed for basic computer usage but can be useful "
+ "for advanced tasks. To learn more about terminals use the help "
+ "in a standalone terminal application like Konsole.</para>"));
+ terminalDock->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>This is "
+ "the <emphasis>terminal</emphasis> panel. It behaves like a "
+ "normal terminal but will match the location of the folder view "
+ "so you can navigate using either.</para><para>The terminal panel "
+ "is not needed for basic computer usage but can be useful for "
+ "advanced tasks. To learn more about terminals use the help in a "
+ "standalone terminal application like Konsole.</para>")
+ + panelWhatsThis);
}
#endif
}
// Setup "Places"
- DolphinDockWidget* placesDock = new DolphinDockWidget(i18nc("@title:window", "Places"));
+ DolphinDockWidget *placesDock = new DolphinDockWidget(i18nc("@title:window", "Places"));
placesDock->setLocked(lock);
placesDock->setObjectName(QStringLiteral("placesDock"));
placesDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
createPanelAction(QIcon::fromTheme(QStringLiteral("compass")), Qt::Key_F9, placesAction, QStringLiteral("show_places_panel"));
addDockWidget(Qt::LeftDockWidgetArea, placesDock);
- connect(m_placesPanel, &PlacesPanel::placeActivated,
- this, &DolphinMainWindow::slotPlaceActivated);
- connect(m_placesPanel, &PlacesPanel::tabRequested,
- this, &DolphinMainWindow::openNewTab);
- connect(m_placesPanel, &PlacesPanel::activeTabRequested,
- this, &DolphinMainWindow::openNewTabAndActivate);
+ connect(m_placesPanel, &PlacesPanel::placeActivated, this, &DolphinMainWindow::slotPlaceActivated);
+ connect(m_placesPanel, &PlacesPanel::tabRequested, this, &DolphinMainWindow::openNewTab);
+ connect(m_placesPanel, &PlacesPanel::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate);
connect(m_placesPanel, &PlacesPanel::newWindowRequested, this, [this](const QUrl &url) {
Dolphin::openNewWindow({url}, this);
});
- connect(m_placesPanel, &PlacesPanel::errorMessage,
- this, &DolphinMainWindow::showErrorMessage);
- connect(this, &DolphinMainWindow::urlChanged,
- m_placesPanel, &PlacesPanel::setUrl);
- connect(placesDock, &DolphinDockWidget::visibilityChanged,
- &DolphinUrlNavigatorsController::slotPlacesPanelVisibilityChanged);
- connect(this, &DolphinMainWindow::settingsChanged,
- m_placesPanel, &PlacesPanel::readSettings);
- connect(m_placesPanel, &PlacesPanel::storageTearDownRequested,
- this, &DolphinMainWindow::slotStorageTearDownFromPlacesRequested);
- connect(m_placesPanel, &PlacesPanel::storageTearDownExternallyRequested,
- this, &DolphinMainWindow::slotStorageTearDownExternallyRequested);
+ connect(m_placesPanel, &PlacesPanel::errorMessage, this, &DolphinMainWindow::showErrorMessage);
+ connect(this, &DolphinMainWindow::urlChanged, m_placesPanel, &PlacesPanel::setUrl);
+ connect(placesDock, &DolphinDockWidget::visibilityChanged, &DolphinUrlNavigatorsController::slotPlacesPanelVisibilityChanged);
+ connect(this, &DolphinMainWindow::settingsChanged, m_placesPanel, &PlacesPanel::readSettings);
+ connect(m_placesPanel, &PlacesPanel::storageTearDownRequested, this, &DolphinMainWindow::slotStorageTearDownFromPlacesRequested);
+ connect(m_placesPanel, &PlacesPanel::storageTearDownExternallyRequested, this, &DolphinMainWindow::slotStorageTearDownExternallyRequested);
DolphinUrlNavigatorsController::slotPlacesPanelVisibilityChanged(m_placesPanel->isVisible());
auto actionShowAllPlaces = new QAction(QIcon::fromTheme(QStringLiteral("view-hidden")), i18nc("@item:inmenu", "Show Hidden Places"), this);
actionShowAllPlaces->setCheckable(true);
actionShowAllPlaces->setDisabled(true);
- actionShowAllPlaces->setWhatsThis(i18nc("@info:whatsthis", "This displays "
- "all places in the places panel that have been hidden. They will "
- "appear semi-transparent unless you uncheck their hide property."));
+ actionShowAllPlaces->setWhatsThis(i18nc("@info:whatsthis",
+ "This displays "
+ "all places in the places panel that have been hidden. They will "
+ "appear semi-transparent unless you uncheck their hide property."));
- connect(actionShowAllPlaces, &QAction::triggered, this, [actionShowAllPlaces, this](bool checked){
+ connect(actionShowAllPlaces, &QAction::triggered, this, [actionShowAllPlaces, this](bool checked) {
m_placesPanel->setShowAll(checked);
});
connect(m_placesPanel, &PlacesPanel::allPlacesShownChanged, actionShowAllPlaces, &QAction::setChecked);
- actionCollection()->action(QStringLiteral("show_places_panel"))
- ->setWhatsThis(xi18nc("@info:whatsthis", "<para>This toggles the "
- "<emphasis>places</emphasis> panel at the left side of the window."
- "</para><para>It allows you to go to locations you have "
- "bookmarked and to access disk or media attached to the computer "
- "or to the network. It also contains sections to find recently "
- "saved files or files of a certain type.</para>"));
- placesDock->setWhatsThis(xi18nc("@info:whatsthis", "<para>This is the "
- "<emphasis>Places</emphasis> panel. It allows you to go to locations "
- "you have bookmarked and to access disk or media attached to the "
- "computer or to the network. It also contains sections to find "
- "recently saved files or files of a certain type.</para><para>"
- "Click on an entry to go there. Click with the right mouse button "
- "instead to open any entry in a new tab or new window.</para>"
- "<para>New entries can be added by dragging folders onto this panel. "
- "Right-click any section or entry to hide it. Right-click an empty "
- "space on this panel and select <interface>Show Hidden Places"
- "</interface> to display it again.</para>") + panelWhatsThis);
+ actionCollection()
+ ->action(QStringLiteral("show_places_panel"))
+ ->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>This toggles the "
+ "<emphasis>places</emphasis> panel at the left side of the window."
+ "</para><para>It allows you to go to locations you have "
+ "bookmarked and to access disk or media attached to the computer "
+ "or to the network. It also contains sections to find recently "
+ "saved files or files of a certain type.</para>"));
+ placesDock->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>This is the "
+ "<emphasis>Places</emphasis> panel. It allows you to go to locations "
+ "you have bookmarked and to access disk or media attached to the "
+ "computer or to the network. It also contains sections to find "
+ "recently saved files or files of a certain type.</para><para>"
+ "Click on an entry to go there. Click with the right mouse button "
+ "instead to open any entry in a new tab or new window.</para>"
+ "<para>New entries can be added by dragging folders onto this panel. "
+ "Right-click any section or entry to hide it. Right-click an empty "
+ "space on this panel and select <interface>Show Hidden Places"
+ "</interface> to display it again.</para>")
+ + panelWhatsThis);
// Add actions into the "Panels" menu
- KActionMenu* panelsMenu = new KActionMenu(i18nc("@action:inmenu View", "Show Panels"), this);
+ KActionMenu *panelsMenu = new KActionMenu(i18nc("@action:inmenu View", "Show Panels"), this);
actionCollection()->addAction(QStringLiteral("panels"), panelsMenu);
panelsMenu->setIcon(QIcon::fromTheme(QStringLiteral("view-sidetree")));
panelsMenu->setPopupMode(QToolButton::InstantPopup);
- const KActionCollection* ac = actionCollection();
+ const KActionCollection *ac = actionCollection();
panelsMenu->addAction(ac->action(QStringLiteral("show_places_panel")));
#if HAVE_BALOO
panelsMenu->addAction(ac->action(QStringLiteral("show_information_panel")));
panelsMenu->addAction(actionShowAllPlaces);
panelsMenu->addAction(lockLayoutAction);
- connect(panelsMenu->menu(), &QMenu::aboutToShow, this, [actionShowAllPlaces, this]{
+ connect(panelsMenu->menu(), &QMenu::aboutToShow, this, [actionShowAllPlaces, this] {
actionShowAllPlaces->setEnabled(DolphinPlacesModelSingleton::instance().placesModel()->hiddenCount());
});
}
-
void DolphinMainWindow::updateFileAndEditActions()
{
const KFileItemList list = m_activeViewContainer->view()->selectedItems();
- const KActionCollection* col = actionCollection();
+ const KActionCollection *col = actionCollection();
KFileItemListProperties capabilitiesSource(list);
- QAction* renameAction = col->action(KStandardAction::name(KStandardAction::RenameFile));
- QAction* moveToTrashAction = col->action(KStandardAction::name(KStandardAction::MoveToTrash));
- QAction* deleteAction = col->action(KStandardAction::name(KStandardAction::DeleteFile));
- QAction* cutAction = col->action(KStandardAction::name(KStandardAction::Cut));
- QAction* duplicateAction = col->action(QStringLiteral("duplicate")); // see DolphinViewActionHandler
- QAction* addToPlacesAction = col->action(QStringLiteral("add_to_places"));
- QAction* copyToOtherViewAction = col->action(QStringLiteral("copy_to_inactive_split_view"));
- QAction* moveToOtherViewAction = col->action(QStringLiteral("move_to_inactive_split_view"));
- QAction* copyLocation = col->action(QString("copy_location"));
+ QAction *renameAction = col->action(KStandardAction::name(KStandardAction::RenameFile));
+ QAction *moveToTrashAction = col->action(KStandardAction::name(KStandardAction::MoveToTrash));
+ QAction *deleteAction = col->action(KStandardAction::name(KStandardAction::DeleteFile));
+ QAction *cutAction = col->action(KStandardAction::name(KStandardAction::Cut));
+ QAction *duplicateAction = col->action(QStringLiteral("duplicate")); // see DolphinViewActionHandler
+ QAction *addToPlacesAction = col->action(QStringLiteral("add_to_places"));
+ QAction *copyToOtherViewAction = col->action(QStringLiteral("copy_to_inactive_split_view"));
+ QAction *moveToOtherViewAction = col->action(QStringLiteral("move_to_inactive_split_view"));
+ QAction *copyLocation = col->action(QString("copy_location"));
if (list.isEmpty()) {
stateChanged(QStringLiteral("has_no_selection"));
m_actionTextHelper->textsWhenNothingIsSelectedEnabled(false);
stateChanged(QStringLiteral("has_selection"));
- QAction* deleteWithTrashShortcut = col->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler
- QAction* showTarget = col->action(QStringLiteral("show_target"));
+ QAction *deleteWithTrashShortcut = col->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler
+ QAction *showTarget = col->action(QStringLiteral("show_target"));
if (list.length() == 1 && list.first().isDir()) {
addToPlacesAction->setEnabled(true);
}
if (m_tabWidget->currentTabPage()->splitViewEnabled()) {
- DolphinTabPage* tabPage = m_tabWidget->currentTabPage();
+ DolphinTabPage *tabPage = m_tabWidget->currentTabPage();
KFileItem capabilitiesDestination;
if (tabPage->primaryViewActive()) {
{
m_actionHandler->updateViewActions();
- QAction* toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
+ QAction *toggleFilterBarAction = actionCollection()->action(QStringLiteral("toggle_filter"));
toggleFilterBarAction->setChecked(m_activeViewContainer->isFilterBarVisible());
updateSplitAction();
void DolphinMainWindow::updateGoActions()
{
- QAction* goUpAction = actionCollection()->action(KStandardAction::name(KStandardAction::Up));
+ QAction *goUpAction = actionCollection()->action(KStandardAction::name(KStandardAction::Up));
const QUrl currentUrl = m_activeViewContainer->url();
// I think this is one of the best places to firstly be confronted
// with a file system and its hierarchy. Talking about the root
// directory might seem too much here but it is the question that
// naturally arises in this context.
- goUpAction->setWhatsThis(xi18nc("@info:whatsthis", "<para>Go to "
- "the folder that contains the currently viewed one.</para>"
- "<para>All files and folders are organized in a hierarchical "
- "<emphasis>file system</emphasis>. At the top of this hierarchy is "
- "a directory that contains all data connected to this computer"
- "—the <emphasis>root directory</emphasis>.</para>"));
+ goUpAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>Go to "
+ "the folder that contains the currently viewed one.</para>"
+ "<para>All files and folders are organized in a hierarchical "
+ "<emphasis>file system</emphasis>. At the top of this hierarchy is "
+ "a directory that contains all data connected to this computer"
+ "—the <emphasis>root directory</emphasis>.</para>"));
goUpAction->setEnabled(KIO::upUrl(currentUrl) != currentUrl);
}
m_activeViewContainer->statusBar()->resetToDefaultText();
}
-void DolphinMainWindow::connectViewSignals(DolphinViewContainer* container)
+void DolphinMainWindow::connectViewSignals(DolphinViewContainer *container)
{
- connect(container, &DolphinViewContainer::showFilterBarChanged,
- this, &DolphinMainWindow::updateFilterBarAction);
- connect(container, &DolphinViewContainer::writeStateChanged,
- this, &DolphinMainWindow::slotWriteStateChanged);
- connect(container, &DolphinViewContainer::searchModeEnabledChanged,
- this, &DolphinMainWindow::updateSearchAction);
- connect(container, &DolphinViewContainer::captionChanged,
- this, &DolphinMainWindow::updateWindowTitle);
- connect(container, &DolphinViewContainer::tabRequested,
- this, &DolphinMainWindow::openNewTab);
- connect(container, &DolphinViewContainer::activeTabRequested,
- this, &DolphinMainWindow::openNewTabAndActivate);
+ connect(container, &DolphinViewContainer::showFilterBarChanged, this, &DolphinMainWindow::updateFilterBarAction);
+ connect(container, &DolphinViewContainer::writeStateChanged, this, &DolphinMainWindow::slotWriteStateChanged);
+ connect(container, &DolphinViewContainer::searchModeEnabledChanged, this, &DolphinMainWindow::updateSearchAction);
+ connect(container, &DolphinViewContainer::captionChanged, this, &DolphinMainWindow::updateWindowTitle);
+ connect(container, &DolphinViewContainer::tabRequested, this, &DolphinMainWindow::openNewTab);
+ connect(container, &DolphinViewContainer::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate);
- const QAction* toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search"));
+ const QAction *toggleSearchAction = actionCollection()->action(QStringLiteral("toggle_search"));
connect(toggleSearchAction, &QAction::triggered, container, &DolphinViewContainer::setSearchModeEnabled);
// Make the toggled state of the selection mode actions visually follow the selection mode state of the view.
auto toggleSelectionModeAction = actionCollection()->action(QStringLiteral("toggle_selection_mode"));
toggleSelectionModeAction->setChecked(m_activeViewContainer->isSelectionModeEnabled());
- connect(m_activeViewContainer, &DolphinViewContainer::selectionModeChanged,
- toggleSelectionModeAction, &QAction::setChecked);
-
- const DolphinView* view = container->view();
- connect(view, &DolphinView::selectionChanged,
- this, &DolphinMainWindow::slotSelectionChanged);
- connect(view, &DolphinView::requestItemInfo,
- this, &DolphinMainWindow::requestItemInfo);
- connect(view, &DolphinView::fileItemsChanged,
- this, &DolphinMainWindow::fileItemsChanged);
- connect(view, &DolphinView::tabRequested,
- this, &DolphinMainWindow::openNewTab);
- connect(view, &DolphinView::activeTabRequested,
- this, &DolphinMainWindow::openNewTabAndActivate);
- connect(view, &DolphinView::windowRequested,
- this, &DolphinMainWindow::openNewWindow);
- connect(view, &DolphinView::requestContextMenu,
- this, &DolphinMainWindow::openContextMenu);
- connect(view, &DolphinView::directoryLoadingStarted,
- this, &DolphinMainWindow::enableStopAction);
- connect(view, &DolphinView::directoryLoadingCompleted,
- this, &DolphinMainWindow::disableStopAction);
- connect(view, &DolphinView::directoryLoadingCompleted,
- this, &DolphinMainWindow::slotDirectoryLoadingCompleted);
- connect(view, &DolphinView::goBackRequested,
- this, &DolphinMainWindow::goBack);
- connect(view, &DolphinView::goForwardRequested,
- this, &DolphinMainWindow::goForward);
- connect(view, &DolphinView::urlActivated,
- this, &DolphinMainWindow::handleUrl);
- connect(view, &DolphinView::goUpRequested,
- this, &DolphinMainWindow::goUp);
-
- connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::urlChanged,
- this, &DolphinMainWindow::changeUrl);
- connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::historyChanged,
- this, &DolphinMainWindow::updateHistory);
-
- auto navigators = static_cast<DolphinNavigatorsWidgetAction *>
- (actionCollection()->action(QStringLiteral("url_navigators")));
- const KUrlNavigator *navigator = m_tabWidget->currentTabPage()->primaryViewActive() ?
- navigators->primaryUrlNavigator() :
- navigators->secondaryUrlNavigator();
+ connect(m_activeViewContainer, &DolphinViewContainer::selectionModeChanged, toggleSelectionModeAction, &QAction::setChecked);
+
+ const DolphinView *view = container->view();
+ connect(view, &DolphinView::selectionChanged, this, &DolphinMainWindow::slotSelectionChanged);
+ connect(view, &DolphinView::requestItemInfo, this, &DolphinMainWindow::requestItemInfo);
+ connect(view, &DolphinView::fileItemsChanged, this, &DolphinMainWindow::fileItemsChanged);
+ connect(view, &DolphinView::tabRequested, this, &DolphinMainWindow::openNewTab);
+ connect(view, &DolphinView::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate);
+ connect(view, &DolphinView::windowRequested, this, &DolphinMainWindow::openNewWindow);
+ connect(view, &DolphinView::requestContextMenu, this, &DolphinMainWindow::openContextMenu);
+ connect(view, &DolphinView::directoryLoadingStarted, this, &DolphinMainWindow::enableStopAction);
+ connect(view, &DolphinView::directoryLoadingCompleted, this, &DolphinMainWindow::disableStopAction);
+ connect(view, &DolphinView::directoryLoadingCompleted, this, &DolphinMainWindow::slotDirectoryLoadingCompleted);
+ connect(view, &DolphinView::goBackRequested, this, &DolphinMainWindow::goBack);
+ connect(view, &DolphinView::goForwardRequested, this, &DolphinMainWindow::goForward);
+ connect(view, &DolphinView::urlActivated, this, &DolphinMainWindow::handleUrl);
+ connect(view, &DolphinView::goUpRequested, this, &DolphinMainWindow::goUp);
+
+ connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::urlChanged, this, &DolphinMainWindow::changeUrl);
+ connect(container->urlNavigatorInternalWithHistory(), &KUrlNavigator::historyChanged, this, &DolphinMainWindow::updateHistory);
+
+ auto navigators = static_cast<DolphinNavigatorsWidgetAction *>(actionCollection()->action(QStringLiteral("url_navigators")));
+ const KUrlNavigator *navigator =
+ m_tabWidget->currentTabPage()->primaryViewActive() ? navigators->primaryUrlNavigator() : navigators->secondaryUrlNavigator();
QAction *editableLocactionAction = actionCollection()->action(QStringLiteral("editable_location"));
editableLocactionAction->setChecked(navigator->isUrlEditable());
- connect(navigator, &KUrlNavigator::editableStateChanged,
- this, &DolphinMainWindow::slotEditableStateChanged);
- connect(navigator, &KUrlNavigator::tabRequested,
- this, &DolphinMainWindow::openNewTab);
- connect(navigator, &KUrlNavigator::activeTabRequested,
- this, &DolphinMainWindow::openNewTabAndActivate);
- connect(navigator, &KUrlNavigator::newWindowRequested,
- this, &DolphinMainWindow::openNewWindow);
-
+ connect(navigator, &KUrlNavigator::editableStateChanged, this, &DolphinMainWindow::slotEditableStateChanged);
+ connect(navigator, &KUrlNavigator::tabRequested, this, &DolphinMainWindow::openNewTab);
+ connect(navigator, &KUrlNavigator::activeTabRequested, this, &DolphinMainWindow::openNewTabAndActivate);
+ connect(navigator, &KUrlNavigator::newWindowRequested, this, &DolphinMainWindow::openNewWindow);
}
void DolphinMainWindow::updateSplitAction()
{
- QAction* splitAction = actionCollection()->action(QStringLiteral("split_view"));
- const DolphinTabPage* tabPage = m_tabWidget->currentTabPage();
+ QAction *splitAction = actionCollection()->action(QStringLiteral("split_view"));
+ const DolphinTabPage *tabPage = m_tabWidget->currentTabPage();
if (tabPage->splitViewEnabled()) {
if (GeneralSettings::closeActiveSplitView() ? tabPage->primaryViewActive() : !tabPage->primaryViewActive()) {
splitAction->setText(i18nc("@action:intoolbar Close left view", "Close"));
void DolphinMainWindow::updateAllowedToolbarAreas()
{
- auto navigators = static_cast<DolphinNavigatorsWidgetAction *>
- (actionCollection()->action(QStringLiteral("url_navigators")));
+ auto navigators = static_cast<DolphinNavigatorsWidgetAction *>(actionCollection()->action(QStringLiteral("url_navigators")));
if (toolBar()->actions().contains(navigators)) {
toolBar()->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
- if (toolBarArea(toolBar()) == Qt::LeftToolBarArea ||
- toolBarArea(toolBar()) == Qt::RightToolBarArea) {
+ if (toolBarArea(toolBar()) == Qt::LeftToolBarArea || toolBarArea(toolBar()) == Qt::RightToolBarArea) {
addToolBar(Qt::TopToolBarArea, toolBar());
}
} else {
return installed;
}
-void DolphinMainWindow::createPanelAction(const QIcon& icon,
- const QKeySequence& shortcut,
- QAction* dockAction,
- const QString& actionName)
+void DolphinMainWindow::createPanelAction(const QIcon &icon, const QKeySequence &shortcut, QAction *dockAction, const QString &actionName)
{
- QAction* panelAction = actionCollection()->addAction(actionName);
+ QAction *panelAction = actionCollection()->addAction(actionName);
panelAction->setCheckable(true);
panelAction->setChecked(dockAction->isChecked());
panelAction->setText(dockAction->text());
connect(panelAction, &QAction::triggered, dockAction, &QAction::trigger);
connect(dockAction, &QAction::toggled, panelAction, &QAction::setChecked);
}
-
+// clang-format off
void DolphinMainWindow::setupWhatsThis()
{
// main widgets
"<nl/>If you like using this application but don't know "
"about KDE or want to see a cute dragon have a look!"));
}
+// clang-format on
bool DolphinMainWindow::addHamburgerMenuToToolbar()
{
KXmlGuiWindow::saveNewToolbarConfig(); // Applies the new config. This has to be called first
// because the rest of this method decides things
// based on the new config.
- auto navigators = static_cast<DolphinNavigatorsWidgetAction *>
- (actionCollection()->action(QStringLiteral("url_navigators")));
+ auto navigators = static_cast<DolphinNavigatorsWidgetAction *>(actionCollection()->action(QStringLiteral("url_navigators")));
if (!toolBar()->actions().contains(navigators)) {
m_tabWidget->currentTabPage()->insertNavigatorsWidget(navigators);
}
updateAllowedToolbarAreas();
- (static_cast<KHamburgerMenu *>(actionCollection()->action(KStandardAction::name(
- KStandardAction::HamburgerMenu))))->hideActionsOf(toolBar());
+ (static_cast<KHamburgerMenu *>(actionCollection()->action(KStandardAction::name(KStandardAction::HamburgerMenu))))->hideActionsOf(toolBar());
}
void DolphinMainWindow::focusTerminalPanel()
}
}
-DolphinMainWindow::UndoUiInterface::UndoUiInterface() :
- KIO::FileUndoManager::UiInterface()
+DolphinMainWindow::UndoUiInterface::UndoUiInterface()
+ : KIO::FileUndoManager::UiInterface()
{
}
{
}
-void DolphinMainWindow::UndoUiInterface::jobError(KIO::Job* job)
+void DolphinMainWindow::UndoUiInterface::jobError(KIO::Job *job)
{
- DolphinMainWindow* mainWin= qobject_cast<DolphinMainWindow *>(parentWidget());
+ DolphinMainWindow *mainWin = qobject_cast<DolphinMainWindow *>(parentWidget());
if (mainWin) {
- DolphinViewContainer* container = mainWin->activeViewContainer();
+ DolphinViewContainer *container = mainWin->activeViewContainer();
container->showMessage(job->errorString(), DolphinViewContainer::Error);
} else {
KIO::FileUndoManager::UiInterface::jobError(job);
#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>
class PlacesPanel;
class TerminalPanel;
-namespace KIO {
- class OpenUrlJob;
+namespace KIO
+{
+class OpenUrlJob;
}
-namespace SelectionMode {
- class ActionTextHelper;
+namespace SelectionMode
+{
+class ActionTextHelper;
}
/**
*
* 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")
* 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,
* 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
* 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;
*/
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,
* 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();
/**
* 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.
* 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,
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;
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
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();
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();
* 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
* 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
* 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.
* 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
* 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);
* 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
* 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.
* 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.
* 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
* 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:
* 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();
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;
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
-
#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")));
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()
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
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;
}
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;
updateText();
}
-void DolphinNavigatorsWidgetAction::followViewContainersGeometry(QWidget *primaryViewContainer,
- QWidget *secondaryViewContainer)
+void DolphinNavigatorsWidgetAction::followViewContainersGeometry(QWidget *primaryViewContainer, QWidget *secondaryViewContainer)
{
m_viewGeometriesHelper.setViewContainers(primaryViewContainer, secondaryViewContainer);
adjustSpacing();
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) {
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) {
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"));
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"));
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);
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) {
m_secondaryViewContainer = secondaryViewContainer;
}
-DolphinNavigatorsWidgetAction::ViewGeometriesHelper::Geometries
- DolphinNavigatorsWidgetAction::ViewGeometriesHelper::viewGeometries()
+DolphinNavigatorsWidgetAction::ViewGeometriesHelper::Geometries DolphinNavigatorsWidgetAction::ViewGeometriesHelper::viewGeometries()
{
Q_ASSERT(m_primaryViewContainer);
Geometries 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;
}
* 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;
/**
* 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.
*/
*/
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.
/**
* 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;
#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);
}
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());
KNewFileMenu::slotResult(job);
}
}
-
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
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);
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);
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.
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 {
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);
// 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
#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"));
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();
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()) {
}
}
-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.
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);
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) {
// 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)
}
}
-
void DolphinPart::slotEditMimeType()
{
const KFileItemList items = m_view->selectedItems();
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);
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();
}
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.
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 {
m_newFileMenu->createDirectory();
}
-void DolphinPart::setFilesToSelect(const QList<QUrl>& files)
+void DolphinPart::setFilesToSelect(const QList<QUrl> &files)
{
if (files.isEmpty()) {
return;
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);
}
// 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
* 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.
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:
/**
*/
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.
*/
* 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
/**
* Connected to all "Go" menu actions provided by DolphinPart
*/
- void slotGoTriggered(QAction* action);
+ void slotGoTriggered(QAction *action);
/**
* Connected to the "editMimeType" action
*/
void updateStatusBar();
- /**
- * Notify container of folder loading progress.
- */
+ /**
+ * Notify container of folder loading progress.
+ */
void updateProgress(int percent);
void createDirectory();
* 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)
};
#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)
m_part->view()->paste();
}
-void DolphinPartBrowserExtension::pasteTo(const QUrl&)
+void DolphinPartBrowserExtension::pasteTo(const QUrl &)
{
m_part->view()->pasteIntoFolder();
}
m_part->view()->readSettings();
}
-
-DolphinPartFileInfoExtension::DolphinPartFileInfoExtension(DolphinPart* part)
- :KParts::FileInfoExtension(part)
- ,m_part(part)
+DolphinPartFileInfoExtension::DolphinPartFileInfoExtension(DolphinPart *part)
+ : KParts::FileInfoExtension(part)
+ , m_part(part)
{
}
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)
{
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
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:
////
-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);
}
-
{
Q_OBJECT
public:
- explicit DolphinPartBrowserExtension( DolphinPart* part );
+ explicit DolphinPartBrowserExtension(DolphinPart *part);
void restoreState(QDataStream &stream) override;
void saveState(QDataStream &stream) override;
void reparseConfiguration();
private:
- DolphinPart* m_part;
+ DolphinPart *m_part;
};
class DolphinPartFileInfoExtension : public KParts::FileInfoExtension
Q_OBJECT
public:
- explicit DolphinPartFileInfoExtension(DolphinPart* part);
+ explicit DolphinPartFileInfoExtension(DolphinPart *part);
QueryModes supportedQueryModes() const override;
bool hasSelection() const override;
KFileItemList queryFor(QueryMode mode) const override;
private:
- DolphinPart* m_part;
+ DolphinPart *m_part;
};
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
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
QStringList DolphinPlacesModel::mimeTypes() const
{
QStringList types = KFilePlacesModel::mimeTypes();
- types << DragAndDropHelper::arkDndServiceMimeType()
- << DragAndDropHelper::arkDndPathMimeType();
+ types << DragAndDropHelper::arkDndServiceMimeType() << DragAndDropHelper::arkDndPathMimeType();
return types;
}
DolphinPlacesModelSingleton::DolphinPlacesModelSingleton()
: m_placesModel(new DolphinPlacesModel(KAboutData::applicationData().componentName() + applicationNameSuffix()))
{
-
}
DolphinPlacesModelSingleton &DolphinPlacesModelSingleton::instance()
#ifndef DOLPHINPLACESMODELSINGLETON_H
#define DOLPHINPLACESMODELSINGLETON_H
-#include <QString>
#include <QScopedPointer>
+#include <QString>
#include <KFilePlacesModel>
*/
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();
#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);
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);
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));
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
#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);
*/
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.
#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);
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()) {
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()) {
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()) {
QTabBar::dropEvent(event);
}
-void DolphinTabBar::mousePressEvent(QMouseEvent* event)
+void DolphinTabBar::mousePressEvent(QMouseEvent *event)
{
const int index = tabAt(event->pos());
{
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;
QTabBar::mouseReleaseEvent(event);
}
-void DolphinTabBar::mouseDoubleClickEvent(QMouseEvent* event)
+void DolphinTabBar::mouseDoubleClickEvent(QMouseEvent *event)
{
const int index = tabAt(event->pos());
QTabBar::mouseDoubleClickEvent(event);
}
-void DolphinTabBar::contextMenuEvent(QContextMenuEvent* event)
+void DolphinTabBar::contextMenuEvent(QContextMenuEvent *event)
{
const int index = tabAt(event->pos());
// 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) {
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();
void updateAutoActivationTimer(const int index);
private:
- QTimer* m_autoActivationTimer;
+ QTimer *m_autoActivationTimer;
int m_autoActivationIndex;
int m_tabToBeClosedOnMiddleMouseButtonRelease;
};
#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);
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();
// 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();
{
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) {
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();
}
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);
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.
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.
}
}
-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
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()
}
}
-void DolphinTabPage::insertNavigatorsWidget(DolphinNavigatorsWidgetAction* navigatorsWidget)
+void DolphinTabPage::insertNavigatorsWidget(DolphinNavigatorsWidgetAction *navigatorsWidget)
{
QGridLayout *gridLayout = static_cast<QGridLayout *>(layout());
if (navigatorsWidget->isInToolbar()) {
}
}
-void DolphinTabPage::markUrlsAsSelected(const QList<QUrl>& urls)
+void DolphinTabPage::markUrlsAsSelected(const QList<QUrl> &urls)
{
m_primaryViewContainer->view()->markUrlsAsSelected(urls);
if (m_splitViewEnabled) {
}
}
-void DolphinTabPage::markUrlAsCurrent(const QUrl& url)
+void DolphinTabPage::markUrlAsCurrent(const QUrl &url)
{
m_primaryViewContainer->view()->markUrlAsCurrent(url);
if (m_splitViewEnabled) {
return state;
}
-void DolphinTabPage::restoreState(const QByteArray& state)
+void DolphinTabPage::restoreState(const QByteArray &state)
{
if (state.isEmpty()) {
return;
{
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();
}
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);
// 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;
}
}
-
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
}
}
- 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)
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;
}
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.
DolphinTabPageSplitterHandle::DolphinTabPageSplitterHandle(Qt::Orientation orientation, QSplitter *parent)
: QSplitterHandle(orientation, parent)
, m_mouseReleaseWasReceived(false)
-{}
+{
+}
bool DolphinTabPageSplitterHandle::event(QEvent *event)
{
DolphinTabPageSplitter::DolphinTabPageSplitter(Qt::Orientation orientation, QWidget *parent)
: QSplitter(orientation, parent)
-{}
+{
+}
-QSplitterHandle* DolphinTabPageSplitter::createHandle()
+QSplitterHandle *DolphinTabPageSplitter::createHandle()
{
return new DolphinTabPageSplitterHandle(orientation(), this);
}
#include "global.h"
#include <QPointer>
+#include <QSplitter>
#include <QUrl>
#include <QWidget>
-#include <QSplitter>
class DolphinNavigatorsWidgetAction;
class DolphinViewContainer;
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.
/**
* @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
* 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
* 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
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:
*
* 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();
/**
* 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.
explicit DolphinTabPageSplitter(Qt::Orientation orientation, QWidget *parent);
protected:
- QSplitterHandle* createHandle() override;
+ QSplitterHandle *createHandle() override;
};
#endif // DOLPHIN_TAB_PAGE_H
#include "dolphintabbar.h"
#include "dolphinviewcontainer.h"
+#include <KAcceleratorManager>
#include <KConfigGroup>
-#include <KShell>
-#include <kio/global.h>
#include <KIO/CommandLauncherJob>
-#include <KAcceleratorManager>
#include <KLocalizedString>
+#include <KShell>
+#include <kio/global.h>
#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);
-
- 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);
+ 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);
tabBar->hide();
setTabBar(tabBar);
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) {
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
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()) {
}
}
-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);
}
}
-void DolphinTabWidget::openDirectories(const QList<QUrl>& dirs, bool splitView)
+void DolphinTabWidget::openDirectories(const QList<QUrl> &dirs, bool splitView)
{
Q_ASSERT(dirs.size() > 0);
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,
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 {
}
}
-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;
// 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) {
return;
}
- DolphinTabPage* tabPage = tabPageAt(index);
+ DolphinTabPage *tabPage = tabPageAt(index);
Q_EMIT rememberClosedTab(tabPage->activeViewContainer()->url(), tabPage->saveState());
removeTab(index);
setCurrentIndex(index >= 0 ? index : (count() - 1));
}
-void DolphinTabWidget::restoreClosedTab(const QByteArray& state)
+void DolphinTabWidget::restoreClosedTab(const QByteArray &state)
{
openNewActivatedTab();
currentTabPage()->restoreState(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;
}
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;
}
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();
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();
}
}
-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));
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);
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()) {
} 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()
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) {
}
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.
}
i = (i + 1) % count();
- }
- while (i != currentIndex());
+ } while (i != currentIndex());
return std::nullopt;
}
Q_OBJECT
public:
-
/**
* @param navigatorsWidget The navigatorsWidget which is always going to be connected
* to the active tabPage.
/**
* @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
* @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:
/**
* 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
/**
* 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:
/**
* 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
* 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.
* 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();
* 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);
* @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;
* @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.
* @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;
#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(QWidget *parent)
+ : DolphinUrlNavigator(QUrl(), parent)
+{
+}
-DolphinUrlNavigator::DolphinUrlNavigator(const QUrl &url, QWidget *parent) :
- KUrlNavigator(DolphinPlacesModelSingleton::instance().placesModel(), url, parent)
+DolphinUrlNavigator::DolphinUrlNavigator(const QUrl &url, QWidget *parent)
+ : KUrlNavigator(DolphinPlacesModelSingleton::instance().placesModel(), url, parent)
{
- const GeneralSettings* settings = GeneralSettings::self();
+ 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()
return visualState;
}
-void DolphinUrlNavigator::setVisualState(const VisualState& visualState)
+void DolphinUrlNavigator::setVisualState(const VisualState &visualState)
{
setUrlEditable(visualState.isUrlEditable);
if (!visualState.isUrlEditable) {
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)
#include "dolphinviewcontainer.h"
+#include "dolphin_detailsmodesettings.h"
#include "dolphin_generalsettings.h"
#include "dolphindebug.h"
#include "dolphinplacesmodelsingleton.h"
#include "search/dolphinsearchbox.h"
#include "selectionmode/topbar.h"
#include "statusbar/dolphinstatusbar.h"
-#include "dolphin_detailsmodesettings.h"
#include <KActionCollection>
#if HAVE_KACTIVITIES
#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
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);
#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);
}
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);
});
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
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;
}
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;
}
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;
}
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;
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;
}
}
}
-
-void DolphinViewContainer::showMessage(const QString& msg, MessageType type)
+void DolphinViewContainer::showMessage(const QString &msg, MessageType type)
{
if (msg.isEmpty()) {
return;
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;
m_searchBox->setVisible(enabled);
if (enabled) {
- const QUrl& locationUrl = m_urlNavigator->locationUrl();
+ const QUrl &locationUrl = m_urlNavigator->locationUrl();
m_searchBox->fromSearchUrl(locationUrl);
}
QString DolphinViewContainer::caption() const
{
if (isSearchModeEnabled()) {
- if (currentSearchText().isEmpty()){
+ if (currentSearchText().isEmpty()) {
return i18n("Search");
} else {
return i18n("Search for %1", currentSearchText());
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;
return fileName;
}
-void DolphinViewContainer::setUrl(const QUrl& newUrl)
+void DolphinViewContainer::setUrl(const QUrl &newUrl)
{
if (newUrl != m_urlNavigator->locationUrl()) {
m_urlNavigator->setLocationUrl(newUrl);
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 {
// 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
job->start();
}
-void DolphinViewContainer::slotItemsActivated(const KFileItemList& items)
+void DolphinViewContainer::slotItemsActivated(const KFileItemList &items)
{
Q_ASSERT(items.count() >= 2);
fileItemActions.runPreferredApplications(items);
}
-void DolphinViewContainer::showItemInfo(const KFileItem& item)
+void DolphinViewContainer::showItemInfo(const KFileItem &item)
{
if (item.isNull()) {
m_statusBar->resetToDefaultText();
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);
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();
"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);
}
}
-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
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();
m_view->setZoomLevel(zoomLevel);
}
-void DolphinViewContainer::showErrorMessage(const QString& msg)
+void DolphinViewContainer::showErrorMessage(const QString &msg)
{
showMessage(msg, Error);
}
}
}
-bool DolphinViewContainer::isSearchUrl(const QUrl& url) const
+bool DolphinViewContainer::isSearchUrl(const QUrl &url) const
{
return url.scheme().contains(QLatin1String("search"));
}
}
}
-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{};
}
#include <QWidget>
#if HAVE_KACTIVITIES
-namespace KActivities {
- class ResourceInstance;
+namespace KActivities
+{
+class ResourceInstance;
}
#endif
class QUrl;
class DolphinSearchBox;
class DolphinStatusBar;
-namespace SelectionMode {
- class TopBar;
+namespace SelectionMode
+{
+class TopBar;
}
/**
Q_OBJECT
public:
- enum MessageType
- {
- Information,
- Warning,
- Error
- };
-
- DolphinViewContainer(const QUrl& url, QWidget* parent);
+ enum MessageType { Information, Warning, Error };
+
+ DolphinViewContainer(const QUrl &url, QWidget *parent);
~DolphinViewContainer() override;
/**
QString currentSearchText() const;
- const DolphinStatusBar* statusBar() const;
- DolphinStatusBar* statusBar();
+ const DolphinStatusBar *statusBar() const;
+ DolphinStatusBar *statusBar();
/**
* @return An UrlNavigator that is controlling this view
*/
DolphinUrlNavigator *urlNavigatorInternalWithHistory();
- const DolphinView* view() const;
- DolphinView* view();
+ const DolphinView *view() const;
+ DolphinView *view();
/**
* @param urlNavigator The UrlNavigator that is supposed to control
* @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;
* 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.
/** Returns true, if the filter bar is visible. */
bool isFilterBarVisible() const;
-
/** Returns true if the search mode is enabled. */
bool isSearchModeEnabled() const;
* 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.
* 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
* 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();
* 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
* 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();
/**
* Slot that calls showMessage(msg, Error).
*/
- void showErrorMessage(const QString& msg);
+ void showErrorMessage(const QString &msg);
/**
* Is invoked when a KFilePlacesModel has been changed
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,
/**
* @return Path of nearest existing ancestor directory.
*/
- QString getNearestExistingAncestorOfPath(const QString& path) const;
+ QString getNearestExistingAncestorOfPath(const QString &path) const;
private:
QGridLayout *m_topLayout;
*/
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
#if HAVE_KACTIVITIES
private:
- KActivities::ResourceInstance * m_activityResourceInstance;
+ KActivities::ResourceInstance *m_activityResourceInstance;
#endif
};
#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);
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
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);
}
}
-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);
break;
}
}
-
Q_OBJECT
public:
- explicit FilterBar(QWidget* parent = nullptr);
+ explicit FilterBar(QWidget *parent = nullptr);
~FilterBar() override;
/** Called by view container to hide this **/
* 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.
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
#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);
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;
}
int activeWindowIndex = -1;
- for (const auto& interface: qAsConst(dolphinInterfaces)) {
+ for (const auto &interface : qAsConst(dolphinInterfaces)) {
++activeWindowIndex;
auto isActiveWindowReply = interface.first->isActiveWindow();
// 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();
}
i = (i + 1) % dolphinInterfaces.size();
- }
- while (i != activeWindowIndex);
+ } while (i != activeWindowIndex);
if (!urlFound) {
if (GeneralSettings::openExternallyCalledFolderInNewTab()) {
}
}
- 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);
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()));
}
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()));
}
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));
}
}
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
{
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();
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) {
}
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());
}
}
class QFontMetrics;
class QString;
-enum ItemsState {
- None,
- Selected
-};
+enum ItemsState { None, Selected };
/**
* @brief Generates a textual representation of the given list of KFileItems.
#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);
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);
return m_scanDirectories;
}
-QPixmap KFileItemListView::createDragPixmap(const KItemSet& indexes) const
+QPixmap KFileItemListView::createDragPixmap(const KItemSet &indexes) const
{
if (!model()) {
return QPixmap();
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();
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());
triggerVisibleIndexRangeUpdate();
}
-void KFileItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
+void KFileItemListView::onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
triggerVisibleIndexRangeUpdate();
}
-void KFileItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
+void KFileItemListView::onVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous)
{
KStandardItemListView::onVisibleRolesChanged(current, previous);
applyRolesToModel();
}
-void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
+void KFileItemListView::onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous)
{
KStandardItemListView::onStyleOptionChanged(current, previous);
triggerIconSizeUpdate();
// Only unpause the model-roles-updater if no timer is active. If one
// timer is still active the model-roles-updater will be unpaused later as
// soon as the timer has been exceeded.
- const bool timerActive = m_updateVisibleIndexRangeTimer->isActive() ||
- m_updateIconSizeTimer->isActive();
+ const bool timerActive = m_updateVisibleIndexRangeTimer->isActive() || m_updateIconSizeTimer->isActive();
if (!timerActive) {
m_modelRolesUpdater->setPaused(false);
}
}
-void KFileItemListView::resizeEvent(QGraphicsSceneResizeEvent* event)
+void KFileItemListView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
KStandardItemListView::resizeEvent(event);
triggerVisibleIndexRangeUpdate();
}
-void KFileItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
+void KFileItemListView::slotItemsRemoved(const KItemRangeList &itemRanges)
{
KStandardItemListView::slotItemsRemoved(itemRanges);
}
-void KFileItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
+void KFileItemListView::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous)
{
const QByteArray sortRole = model()->sortRole();
if (!visibleRoles().contains(sortRole)) {
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:
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;
return QSize(iconSize, iconSize);
}
-
Q_OBJECT
public:
- explicit KFileItemListView(QGraphicsWidget* parent = nullptr);
+ explicit KFileItemListView(QGraphicsWidget *parent = nullptr);
~KFileItemListView() override;
void setPreviewsShown(bool show);
*
* @see enabledPlugins
*/
- void setEnabledPlugins(const QStringList& list);
+ void setEnabledPlugins(const QStringList &list);
/**
* Returns the list of enabled thumbnail plugins.
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.
* this method will be called repeatedly with increasing values
* for this parameter.
*/
- void setHoverSequenceState(const QUrl& itemUrl, int seqIdx);
+ void setHoverSequenceState(const QUrl &itemUrl, int seqIdx);
protected:
- KItemListWidgetCreatorBase* defaultWidgetCreator() const override;
- void initializeItemListWidget(KItemListWidget* item) override;
+ KItemListWidgetCreatorBase *defaultWidgetCreator() const override;
+ void initializeItemListWidget(KItemListWidget *item) override;
virtual void onPreviewsShownChanged(bool shown);
void onItemLayoutChanged(ItemLayout current, ItemLayout previous) override;
- void onModelChanged(KItemModelBase* current, KItemModelBase* previous) override;
+ void onModelChanged(KItemModelBase *current, KItemModelBase *previous) override;
void onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous) override;
- void onItemSizeChanged(const QSizeF& current, const QSizeF& previous) override;
+ void onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous) override;
void onScrollOffsetChanged(qreal current, qreal previous) override;
- void onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous) override;
- void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous) override;
+ void onVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous) override;
+ void onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous) override;
void onSupportsItemExpandingChanged(bool supportsExpanding) override;
void onTransactionBegin() override;
void onTransactionEnd() override;
- void resizeEvent(QGraphicsSceneResizeEvent* event) override;
+ void resizeEvent(QGraphicsSceneResizeEvent *event) override;
protected Q_SLOTS:
- void slotItemsRemoved(const KItemRangeList& itemRanges) override;
- void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous) override;
+ void slotItemsRemoved(const KItemRangeList &itemRanges) override;
+ void slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous) override;
private Q_SLOTS:
void triggerVisibleIndexRangeUpdate();
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
-
-
#include <QGraphicsView>
#include <QMimeDatabase>
-KFileItemListWidgetInformant::KFileItemListWidgetInformant() :
- KStandardItemListWidgetInformant()
+KFileItemListWidgetInformant::KFileItemListWidgetInformant()
+ : KStandardItemListWidgetInformant()
{
}
{
}
-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);
// 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 {
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()) {
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);
return font;
}
-KFileItemListWidget::KFileItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) :
- KStandardItemListWidget(informant, parent)
+KFileItemListWidget::KFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent)
+ : KStandardItemListWidget(informant, parent)
{
}
{
}
-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";
}
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);
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;
}
void KFileItemListWidget::hoverSequenceStarted()
{
- KFileItemListView* view = listView();
+ KFileItemListView *view = listView();
if (!view) {
return;
void KFileItemListWidget::hoverSequenceIndexChanged(int sequenceIndex)
{
- KFileItemListView* view = listView();
+ KFileItemListView *view = listView();
if (!view) {
return;
void KFileItemListWidget::hoverSequenceEnded()
{
- KFileItemListView* view = listView();
+ KFileItemListView *view = listView();
if (!view) {
return;
view->setHoverSequenceState(QUrl(), 0);
}
-KFileItemListView* KFileItemListWidget::listView()
+KFileItemListView *KFileItemListWidget::listView()
{
- return dynamic_cast<KFileItemListView*>(parentItem());
+ return dynamic_cast<KFileItemListView *>(parentItem());
}
-
class KFileItemListView;
-
class DOLPHIN_EXPORT KFileItemListWidgetInformant : public KStandardItemListWidgetInformant
{
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
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
-
-
#include "kfileitemmodel.h"
-#include "dolphin_generalsettings.h"
#include "dolphin_detailsmodesettings.h"
+#include "dolphin_generalsettings.h"
#include "dolphindebug.h"
#include "private/kfileitemmodelsortalgorithm.h"
#include <KDirLister>
#include <KIO/Job>
-#include <kio_version.h>
#include <KLocalizedString>
#include <KUrlMimeData>
+#include <kio_version.h>
#include <QElapsedTimer>
+#include <QIcon>
#include <QMimeData>
#include <QMimeDatabase>
+#include <QRecursiveMutex>
#include <QTimer>
#include <QWidget>
-#include <QRecursiveMutex>
-#include <QIcon>
#include <algorithm>
#include <klazylocalizedstring.h>
// #define KFILEITEMMODEL_DEBUG
-KFileItemModel::KFileItemModel(QObject* parent) :
- KItemModelBase("text", parent),
- m_dirLister(nullptr),
- m_sortDirsFirst(true),
- m_sortHiddenLast(false),
- m_sortRole(NameRole),
- m_sortingProgressPercent(-1),
- m_roles(),
- m_itemData(),
- m_items(),
- m_filter(),
- m_filteredItems(),
- m_requestRole(),
- m_maximumUpdateIntervalTimer(nullptr),
- m_resortAllItemsTimer(nullptr),
- m_pendingItemsToInsert(),
- m_groups(),
- m_expandedDirs(),
- m_urlsToExpand()
+KFileItemModel::KFileItemModel(QObject *parent)
+ : KItemModelBase("text", parent)
+ , m_dirLister(nullptr)
+ , m_sortDirsFirst(true)
+ , m_sortHiddenLast(false)
+ , m_sortRole(NameRole)
+ , m_sortingProgressPercent(-1)
+ , m_roles()
+ , m_itemData()
+ , m_items()
+ , m_filter()
+ , m_filteredItems()
+ , m_requestRole()
+ , m_maximumUpdateIntervalTimer(nullptr)
+ , m_resortAllItemsTimer(nullptr)
+ , m_pendingItemsToInsert()
+ , m_groups()
+ , m_expandedDirs()
+ , m_urlsToExpand()
{
m_collator.setNumericMode(true);
m_dirLister->setAutoErrorHandlingEnabled(false);
m_dirLister->setDelayedMimeTypes(true);
- const QWidget* parentWidget = qobject_cast<QWidget*>(parent);
+ const QWidget *parentWidget = qobject_cast<QWidget *>(parent);
if (parentWidget) {
m_dirLister->setMainWindow(parentWidget->window());
}
QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
{
if (index >= 0 && index < count()) {
- ItemData* data = m_itemData.at(index);
+ ItemData *data = m_itemData.at(index);
if (data->values.isEmpty()) {
data->values = retrieveData(data->item, data->parent);
} else if (data->values.count() <= 2 && data->values.value("isExpanded").toBool()) {
return QHash<QByteArray, QVariant>();
}
-bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant>& values)
+bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant> &values)
{
if (index < 0 || index >= count()) {
return false;
return m_dirLister->dirOnlyMode();
}
-QMimeData* KFileItemModel::createMimeData(const KItemSet& indexes) const
+QMimeData *KFileItemModel::createMimeData(const KItemSet &indexes) const
{
- QMimeData* data = new QMimeData();
+ QMimeData *data = new QMimeData();
// The following code has been taken from KDirModel::mimeData()
// (kdelibs/kio/kio/kdirmodel.cpp)
// SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
QList<QUrl> urls;
QList<QUrl> mostLocalUrls;
- const ItemData* lastAddedItem = nullptr;
+ const ItemData *lastAddedItem = nullptr;
for (int index : indexes) {
- const ItemData* itemData = m_itemData.at(index);
- const ItemData* parent = itemData->parent;
+ const ItemData *itemData = m_itemData.at(index);
+ const ItemData *parent = itemData->parent;
while (parent && parent != lastAddedItem) {
parent = parent->parent;
}
lastAddedItem = itemData;
- const KFileItem& item = itemData->item;
+ const KFileItem &item = itemData->item;
if (!item.isNull()) {
urls << item.url();
return data;
}
-int KFileItemModel::indexForKeyboardSearch(const QString& text, int startFromIndex) const
+int KFileItemModel::indexForKeyboardSearch(const QString &text, int startFromIndex) const
{
startFromIndex = qMax(0, startFromIndex);
for (int i = startFromIndex; i < count(); ++i) {
return !item.isNull() && (item.isDir() || item.isDesktopFile());
}
-QString KFileItemModel::roleDescription(const QByteArray& role) const
+QString KFileItemModel::roleDescription(const QByteArray &role) const
{
static QHash<QByteArray, QString> description;
if (description.isEmpty()) {
int count = 0;
- const RoleInfoMap* map = rolesInfoMap(count);
+ const RoleInfoMap *map = rolesInfoMap(count);
for (int i = 0; i < count; ++i) {
if (map[i].roleTranslation.isEmpty()) {
continue;
return description.value(role);
}
-QList<QPair<int, QVariant> > KFileItemModel::groups() const
+QList<QPair<int, QVariant>> KFileItemModel::groups() const
{
if (!m_itemData.isEmpty() && m_groups.isEmpty()) {
#ifdef KFILEITEMMODEL_DEBUG
timer.start();
#endif
switch (typeForRole(sortRole())) {
- case NameRole: m_groups = nameRoleGroups(); break;
- case SizeRole: m_groups = sizeRoleGroups(); break;
+ case NameRole:
+ m_groups = nameRoleGroups();
+ break;
+ case SizeRole:
+ m_groups = sizeRoleGroups();
+ break;
case ModificationTimeRole:
m_groups = timeRoleGroups([](const ItemData *item) {
return item->item.time(KFileItem::ModificationTime);
return item->values.value("deletiontime").toDateTime();
});
break;
- case PermissionsRole: m_groups = permissionRoleGroups(); break;
- case RatingRole: m_groups = ratingRoleGroups(); break;
- default: m_groups = genericStringRoleGroups(sortRole()); break;
+ case PermissionsRole:
+ m_groups = permissionRoleGroups();
+ break;
+ case RatingRole:
+ m_groups = ratingRoleGroups();
+ break;
+ default:
+ m_groups = genericStringRoleGroups(sortRole());
+ break;
}
#ifdef KFILEITEMMODEL_DEBUG
return KFileItem();
}
-int KFileItemModel::index(const KFileItem& item) const
+int KFileItemModel::index(const KFileItem &item) const
{
return index(item.url());
}
-int KFileItemModel::index(const QUrl& url) const
+int KFileItemModel::index(const QUrl &url) const
{
const QUrl urlToFind = url.adjusted(QUrl::StripTrailingSlash);
}
const auto uniqueKeys = indexesForUrl.uniqueKeys();
- for (const QUrl& url : uniqueKeys) {
+ for (const QUrl &url : uniqueKeys) {
if (indexesForUrl.count(url) > 1) {
qCWarning(DolphinDebug) << "Multiple items found with the URL" << url;
auto it = indexesForUrl.find(url);
while (it != indexesForUrl.end() && it.key() == url) {
- const ItemData* data = m_itemData.at(it.value());
+ const ItemData *data = m_itemData.at(it.value());
qCWarning(DolphinDebug) << "index" << it.value() << ":" << data->item;
if (data->parent) {
qCWarning(DolphinDebug) << "parent" << data->parent->item;
slotClear();
}
-void KFileItemModel::setRoles(const QSet<QByteArray>& roles)
+void KFileItemModel::setRoles(const QSet<QByteArray> &roles)
{
if (m_roles == roles) {
return;
QSetIterator<QByteArray> it(roles);
while (it.hasNext()) {
- const QByteArray& role = it.next();
+ const QByteArray &role = it.next();
m_requestRole[typeForRole(role)] = true;
}
// Clear the 'values' of all filtered items. They will be re-populated with the
// correct roles the next time 'values' will be accessed via data(int).
- QHash<KFileItem, ItemData*>::iterator filteredIt = m_filteredItems.begin();
- const QHash<KFileItem, ItemData*>::iterator filteredEnd = m_filteredItems.end();
+ QHash<KFileItem, ItemData *>::iterator filteredIt = m_filteredItems.begin();
+ const QHash<KFileItem, ItemData *>::iterator filteredEnd = m_filteredItems.end();
while (filteredIt != filteredEnd) {
(*filteredIt)->values.clear();
++filteredIt;
m_dirLister->openUrl(url, KDirLister::Keep);
const QVariantList previouslyExpandedChildren = m_itemData.at(index)->values.value("previouslyExpandedChildren").value<QVariantList>();
- for (const QVariant& var : previouslyExpandedChildren) {
+ for (const QVariant &var : previouslyExpandedChildren) {
m_urlsToExpand.insert(var.toUrl());
}
} else {
int childIndex = firstChildIndex;
while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
- ItemData* itemData = m_itemData.at(childIndex);
+ ItemData *itemData = m_itemData.at(childIndex);
if (itemData->values.value("isExpanded").toBool()) {
const QUrl targetUrl = itemData->item.targetUrl();
const QUrl url = itemData->item.url();
m_expandedDirs.remove(targetUrl);
- m_dirLister->stop(url); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
+ m_dirLister->stop(url); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
#if KIO_VERSION >= QT_VERSION_CHECK(5, 92, 0)
m_dirLister->forgetDirs(url);
#endif
void KFileItemModel::expandParentDirectories(const QUrl &url)
{
-
// Assure that each sub-path of the URL that should be
// expanded is added to m_urlsToExpand. KDirLister
// does not care whether the parent-URL has already been
}
}
-void KFileItemModel::setNameFilter(const QString& nameFilter)
+void KFileItemModel::setNameFilter(const QString &nameFilter)
{
if (m_filter.pattern() != nameFilter) {
dispatchPendingItemsToInsert();
return m_filter.pattern();
}
-void KFileItemModel::setMimeTypeFilters(const QStringList& filters)
+void KFileItemModel::setMimeTypeFilters(const QStringList &filters)
{
if (m_filter.mimeTypes() != filters) {
dispatchPendingItemsToInsert();
for (int index = m_itemData.count() - 1; index >= 0; --index) {
ItemData *itemData = m_itemData.at(index);
- if (m_filter.matches(itemData->item)
- || (itemShownBelow && itemShownBelow->parent == itemData)) {
+ if (m_filter.matches(itemData->item) || (itemShownBelow && itemShownBelow->parent == itemData)) {
// We could've entered here for two reasons:
// 1. This item passes the filter itself
// 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
insertItems(newVisibleItems);
}
-void KFileItemModel::removeFilteredChildren(const KItemRangeList& itemRanges)
+void KFileItemModel::removeFilteredChildren(const KItemRangeList &itemRanges)
{
if (m_filteredItems.isEmpty() || !m_requestRole[ExpandedParentsCountRole]) {
// There are either no filtered items, or it is not possible to expand
return;
}
- QSet<ItemData*> parents;
- for (const KItemRange& range : itemRanges) {
+ QSet<ItemData *> parents;
+ for (const KItemRange &range : itemRanges) {
for (int index = range.index; index < range.index + range.count; ++index) {
parents.insert(m_itemData.at(index));
}
}
- QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
+ QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
while (it != m_filteredItems.end()) {
if (parents.contains(it.value()->parent)) {
delete it.value();
static QList<RoleInfo> rolesInfo;
if (rolesInfo.isEmpty()) {
int count = 0;
- const RoleInfoMap* map = rolesInfoMap(count);
+ const RoleInfoMap *map = rolesInfoMap(count);
for (int i = 0; i < count; ++i) {
if (map[i].roleType != NoRole) {
RoleInfo info;
m_groups.clear();
}
-void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems)
+void KFileItemModel::onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems)
{
Q_UNUSED(previous)
m_sortRole = typeForRole(current);
// been moved because of the resorting.
QList<QUrl> oldUrls;
oldUrls.reserve(itemCount);
- for (const ItemData* itemData : qAsConst(m_itemData)) {
+ for (const ItemData *itemData : qAsConst(m_itemData)) {
oldUrls.append(itemData->item.url());
}
// Determine the first index that has been moved.
int firstMovedIndex = 0;
- while (firstMovedIndex < itemCount
- && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) {
+ while (firstMovedIndex < itemCount && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) {
++firstMovedIndex;
}
m_groups.clear();
int lastMovedIndex = itemCount - 1;
- while (lastMovedIndex > firstMovedIndex
- && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) {
+ while (lastMovedIndex > firstMovedIndex && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) {
--lastMovedIndex;
}
Q_EMIT itemsMoved(KItemRange(firstMovedIndex, movedItemsCount), movedToIndexes);
} else if (groupedSorting()) {
// The groups might have changed even if the order of the items has not.
- const QList<QPair<int, QVariant> > oldGroups = m_groups;
+ const QList<QPair<int, QVariant>> oldGroups = m_groups;
m_groups.clear();
if (groups() != oldGroups) {
Q_EMIT groupsChanged();
// -> we expand the first visible URL we find in m_restoredExpandedUrls.
// Iterate over a const copy because items are deleted and inserted within the loop
const auto urlsToExpand = m_urlsToExpand;
- for(const QUrl &url : urlsToExpand) {
+ for (const QUrl &url : urlsToExpand) {
const int indexForUrl = index(url);
if (indexForUrl >= 0) {
m_urlsToExpand.remove(url);
Q_EMIT directoryLoadingCanceled();
}
-void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList& items)
+void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList &items)
{
Q_ASSERT(!items.isEmpty());
}
}
- const QList<ItemData*> itemDataList = createItemDataList(parentUrl, items);
+ const QList<ItemData *> itemDataList = createItemDataList(parentUrl, items);
if (!m_filter.hasSetFilters()) {
m_pendingItemsToInsert.append(itemDataList);
// The name or type filter is active. Hide filtered items
// before inserting them into the model and remember
// the filtered items in m_filteredItems.
- for (ItemData* itemData : itemDataList) {
+ for (ItemData *itemData : itemDataList) {
if (m_filter.matches(itemData->item)) {
m_pendingItemsToInsert.append(itemData);
if (itemData->parent) {
return filteredParentsCount;
}
-void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
+void KFileItemModel::slotItemsDeleted(const KFileItemList &items)
{
dispatchPendingItemsToInsert();
const auto currentDir = directory();
- for (const KFileItem& item : items) {
+ for (const KFileItem &item : items) {
if (item.url() == currentDir) {
Q_EMIT currentDirectoryRemoved();
return;
indexesToRemove.append(indexForItem);
} else {
// Probably the item has been filtered.
- QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(item);
+ QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(item);
if (it != m_filteredItems.end()) {
delete it.value();
m_filteredItems.erase(it);
Q_EMIT fileItemsChanged(dirsChanged);
}
-void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
+void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem>> &items)
{
Q_ASSERT(!items.isEmpty());
#ifdef KFILEITEMMODEL_DEBUG
// Contains currently hidden items that should
// get visible and hence removed from m_filteredItems
- QList<ItemData*> newVisibleItems;
+ QList<ItemData *> newVisibleItems;
- QListIterator<QPair<KFileItem, KFileItem> > it(items);
+ QListIterator<QPair<KFileItem, KFileItem>> it(items);
while (it.hasNext()) {
- const QPair<KFileItem, KFileItem>& itemPair = it.next();
- const KFileItem& oldItem = itemPair.first;
- const KFileItem& newItem = itemPair.second;
+ const QPair<KFileItem, KFileItem> &itemPair = it.next();
+ const KFileItem &oldItem = itemPair.first;
+ const KFileItem &newItem = itemPair.second;
const int indexForItem = index(oldItem);
const bool newItemMatchesFilter = m_filter.matches(newItem);
if (indexForItem >= 0) {
// Keep old values as long as possible if they could not retrieved synchronously yet.
// The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
- ItemData * const itemData = m_itemData.at(indexForItem);
+ ItemData *const itemData = m_itemData.at(indexForItem);
QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, itemData->parent));
while (it.hasNext()) {
it.next();
- const QByteArray& role = it.key();
+ const QByteArray &role = it.key();
if (itemData->values.value(role) != it.value()) {
itemData->values.insert(role, it.value());
changedRoles.insert(role);
}
} else {
// Check if 'oldItem' is one of the filtered items.
- QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(oldItem);
+ QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(oldItem);
if (it != m_filteredItems.end()) {
ItemData *const itemData = it.value();
itemData->item = newItem;
}
}
-void KFileItemModel::insertItems(QList<ItemData*>& newItems)
+void KFileItemModel::insertItems(QList<ItemData *> &newItems)
{
if (newItems.isEmpty()) {
return;
if (m_sortRole == NameRole) {
parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount());
} else if (isRoleValueNatural(m_sortRole)) {
- auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b)
- {
+ auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
const QByteArray role = roleForType(m_sortRole);
return a->values.value(role).toString() < b->values.value(role).toString();
};
int rangeCount = 0;
while (sourceIndexNewItems >= 0) {
- ItemData* newItem = newItems.at(sourceIndexNewItems);
+ ItemData *newItem = newItems.at(sourceIndexNewItems);
if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) {
// Move an existing item to its new position. If any new items
// are behind it, push the item range to itemRanges.
#endif
}
-void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior)
+void KFileItemModel::removeItems(const KItemRangeList &itemRanges, RemoveItemsBehavior behavior)
{
if (itemRanges.isEmpty()) {
return;
// Step 1: Remove the items from m_itemData, and free the ItemData.
int removedItemsCount = 0;
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
removedItemsCount += range.count;
for (int index = range.index; index < range.index + range.count; ++index) {
Q_EMIT itemsRemoved(itemRanges);
}
-QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const
+QList<KFileItemModel::ItemData *> KFileItemModel::createItemDataList(const QUrl &parentUrl, const KFileItemList &items) const
{
if (m_sortRole == TypeRole) {
// Try to resolve the MIME-types synchronously to prevent a reordering of
const int parentIndex = index(parentUrl);
ItemData *parentItem = parentIndex < 0 ? m_filteredItems.value(KFileItem(parentUrl), nullptr) : m_itemData.at(parentIndex);
- QList<ItemData*> itemDataList;
+ QList<ItemData *> itemDataList;
itemDataList.reserve(items.count());
- for (const KFileItem& item : items) {
- ItemData* itemData = new ItemData();
+ for (const KFileItem &item : items) {
+ ItemData *itemData = new ItemData();
itemData->item = item;
itemData->parent = parentItem;
itemDataList.append(itemData);
return itemDataList;
}
-void KFileItemModel::prepareItemsForSorting(QList<ItemData*>& itemDataList)
+void KFileItemModel::prepareItemsForSorting(QList<ItemData *> &itemDataList)
{
switch (m_sortRole) {
case ExtensionRole:
case DeletionTimeRole:
// These roles can be determined with retrieveData, and they have to be stored
// in the QHash "values" for the sorting.
- for (ItemData* itemData : qAsConst(itemDataList)) {
+ for (ItemData *itemData : qAsConst(itemDataList)) {
if (itemData->values.isEmpty()) {
itemData->values = retrieveData(itemData->item, itemData->parent);
}
case TypeRole:
// At least store the data including the file type for items with known MIME type.
- for (ItemData* itemData : qAsConst(itemDataList)) {
+ for (ItemData *itemData : qAsConst(itemDataList)) {
if (itemData->values.isEmpty()) {
const KFileItem item = itemData->item;
if (item.isDir() || item.isMimeTypeKnown()) {
}
}
-int KFileItemModel::expandedParentsCount(const ItemData* data)
+int KFileItemModel::expandedParentsCount(const ItemData *data)
{
// The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
// if the corresponding item is expanded, and it is not a top-level item.
- const ItemData* parent = data->parent;
+ const ItemData *parent = data->parent;
if (parent) {
if (parent->parent) {
Q_ASSERT(parent->values.contains("expandedParentsCount"));
const int maxIndex = m_itemData.count() - 1;
for (int i = 0; i <= maxIndex; ++i) {
- const ItemData* itemData = m_itemData.at(i);
+ const ItemData *itemData = m_itemData.at(i);
if (itemData->parent) {
indexesToRemove.append(i);
}
m_expandedDirs.clear();
// Also remove all filtered items which have a parent.
- QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
- const QHash<KFileItem, ItemData*>::iterator end = m_filteredItems.end();
+ QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
+ const QHash<KFileItem, ItemData *>::iterator end = m_filteredItems.end();
while (it != end) {
if (it.value()->parent) {
}
}
-void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles)
+void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet<QByteArray> &changedRoles)
{
Q_EMIT itemsChanged(itemRanges, changedRoles);
// Trigger a resorting if necessary. Note that this can happen even if the sort
// role has not changed at all because the file name can be used as a fallback.
if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))) {
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
bool needsResorting = false;
const int first = range.index;
// (a) The first item in the range is "lessThan" its predecessor,
// (b) the successor of the last item is "lessThan" the last item, or
// (c) the internal order of the items in the range is incorrect.
- if (first > 0
- && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
+ if (first > 0 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
needsResorting = true;
- } else if (last < count() - 1
- && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
+ } else if (last < count() - 1 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
needsResorting = true;
} else {
for (int index = first; index < last; ++index) {
}
}
-KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const
+KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray &role) const
{
static QHash<QByteArray, RoleType> roles;
if (roles.isEmpty()) {
// Insert user visible roles that can be accessed with
// KFileItemModel::roleInformation()
int count = 0;
- const RoleInfoMap* map = rolesInfoMap(count);
+ const RoleInfoMap *map = rolesInfoMap(count);
for (int i = 0; i < count; ++i) {
roles.insert(map[i].role, map[i].roleType);
}
// Insert user visible roles that can be accessed with
// KFileItemModel::roleInformation()
int count = 0;
- const RoleInfoMap* map = rolesInfoMap(count);
+ const RoleInfoMap *map = rolesInfoMap(count);
for (int i = 0; i < count; ++i) {
roles.insert(map[i].roleType, map[i].role);
}
return roles.value(roleType);
}
-QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item, const ItemData* parent) const
+QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem &item, const ItemData *parent) const
{
// It is important to insert only roles that are fast to retrieve. E.g.
// KFileItem::iconName() can be very expensive if the MIME-type is unknown
return data;
}
-bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const
+bool KFileItemModel::lessThan(const ItemData *a, const ItemData *b, const QCollator &collator) const
{
int result = 0;
return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
}
-void KFileItemModel::sort(const QList<KFileItemModel::ItemData*>::iterator &begin,
- const QList<KFileItemModel::ItemData*>::iterator &end) const
+void KFileItemModel::sort(const QList<KFileItemModel::ItemData *>::iterator &begin, const QList<KFileItemModel::ItemData *>::iterator &end) const
{
- auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b)
- {
+ auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
return lessThan(a, b, m_collator);
};
}
}
-int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const
+int KFileItemModel::sortRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const
{
// This function must never return 0, because that would break stable
// sorting, which leads to all kinds of bugs.
// See: https://bugs.kde.org/show_bug.cgi?id=433247
// If two items have equal sort values, let the fallbacks at the bottom of
// the function handle it.
- const KFileItem& itemA = a->item;
- const KFileItem& itemB = b->item;
+ const KFileItem &itemA = a->item;
+ const KFileItem &itemB = b->item;
int result = 0;
break;
}
- case DimensionsRole: {
+ case DimensionsRole: {
const QByteArray role = roleForType(m_sortRole);
const QSize dimensionsA = a->values.value(role).toSize();
const QSize dimensionsB = b->values.value(role).toSize();
}
break;
}
-
}
if (result != 0) {
return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
}
-int KFileItemModel::stringCompare(const QString& a, const QString& b, const QCollator& collator) const
+int KFileItemModel::stringCompare(const QString &a, const QString &b, const QCollator &collator) const
{
QMutexLocker collatorLock(s_collatorMutex());
return QString::compare(a, b, Qt::CaseSensitive);
}
-QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
+QList<QPair<int, QVariant>> KFileItemModel::nameRoleGroups() const
{
Q_ASSERT(!m_itemData.isEmpty());
const int maxIndex = count() - 1;
- QList<QPair<int, QVariant> > groups;
+ QList<QPair<int, QVariant>> groups;
QString groupValue;
QChar firstChar;
if (firstChar != newFirstChar) {
QString newGroupValue;
if (newFirstChar.isLetter()) {
-
if (m_collator.compare(newFirstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(newFirstChar, QChar(QLatin1Char('Z'))) <= 0) {
// WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
return groups;
}
-QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
+QList<QPair<int, QVariant>> KFileItemModel::sizeRoleGroups() const
{
Q_ASSERT(!m_itemData.isEmpty());
const int maxIndex = count() - 1;
- QList<QPair<int, QVariant> > groups;
+ QList<QPair<int, QVariant>> groups;
QString groupValue;
for (int i = 0; i <= maxIndex; ++i) {
continue;
}
- const KFileItem& item = m_itemData.at(i)->item;
+ const KFileItem &item = m_itemData.at(i)->item;
KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
QString newGroupValue;
if (!item.isNull() && item.isDir()) {
return groups;
}
-QList<QPair<int, QVariant> > KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
+QList<QPair<int, QVariant>> KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
{
Q_ASSERT(!m_itemData.isEmpty());
const int maxIndex = count() - 1;
- QList<QPair<int, QVariant> > groups;
+ QList<QPair<int, QVariant>> groups;
const QDate currentDate = QDate::currentDate();
const int daysDistance = fileDate.daysTo(currentDate);
QString newGroupValue;
- if (currentDate.year() == fileDate.year() &&
- currentDate.month() == fileDate.month()) {
-
+ if (currentDate.year() == fileDate.year() && currentDate.month() == fileDate.month()) {
switch (daysDistance / 7) {
case 0:
switch (daysDistance) {
- case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
- case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
+ case 0:
+ newGroupValue = i18nc("@title:group Date", "Today");
+ break;
+ case 1:
+ newGroupValue = i18nc("@title:group Date", "Yesterday");
+ break;
default:
- newGroupValue = fileTime.toString(
- i18nc("@title:group Date: The week day name: dddd", "dddd"));
- newGroupValue = i18nc("Can be used to script translation of \"dddd\""
- "with context @title:group Date", "%1", newGroupValue);
+ newGroupValue = fileTime.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
+ newGroupValue = i18nc(
+ "Can be used to script translation of \"dddd\""
+ "with context @title:group Date",
+ "%1",
+ newGroupValue);
}
break;
case 1:
}
} else {
const QDate lastMonthDate = currentDate.addMonths(-1);
- if (lastMonthDate.year() == fileDate.year() &&
- lastMonthDate.month() == fileDate.month()) {
-
+ if (lastMonthDate.year() == fileDate.year() && lastMonthDate.month() == fileDate.month()) {
if (daysDistance == 1) {
- const KLocalizedString format = ki18nc("@title:group Date: "
- "MMMM is full month name in current locale, and yyyy is "
- "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Yesterday' (MMMM, yyyy)");
+ const KLocalizedString format = ki18nc(
+ "@title:group Date: "
+ "MMMM is full month name in current locale, and yyyy is "
+ "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
+ "part of the text that should not be formatted as a date",
+ "'Yesterday' (MMMM, yyyy)");
const QString translatedFormat = format.toString();
if (translatedFormat.count(QLatin1Char('\'')) == 2) {
newGroupValue = fileTime.toString(translatedFormat);
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
} else {
- qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
- const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
+ qCWarning(DolphinDebug).nospace()
+ << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
+ const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
newGroupValue = fileTime.toString(untranslatedFormat);
}
} else if (daysDistance <= 7) {
- newGroupValue = fileTime.toString(i18nc("@title:group Date: "
- "The week day name: dddd, MMMM is full month name "
- "in current locale, and yyyy is full year number.",
- "dddd (MMMM, yyyy)"));
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue =
+ fileTime.toString(i18nc("@title:group Date: "
+ "The week day name: dddd, MMMM is full month name "
+ "in current locale, and yyyy is full year number.",
+ "dddd (MMMM, yyyy)"));
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"dddd (MMMM, yyyy)\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
} else if (daysDistance <= 7 * 2) {
- const KLocalizedString format = ki18nc("@title:group Date: "
- "MMMM is full month name in current locale, and yyyy is "
- "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'One Week Ago' (MMMM, yyyy)");
+ const KLocalizedString format = ki18nc(
+ "@title:group Date: "
+ "MMMM is full month name in current locale, and yyyy is "
+ "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
+ "part of the text that should not be formatted as a date",
+ "'One Week Ago' (MMMM, yyyy)");
const QString translatedFormat = format.toString();
if (translatedFormat.count(QLatin1Char('\'')) == 2) {
newGroupValue = fileTime.toString(translatedFormat);
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
} else {
- qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
- const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
+ qCWarning(DolphinDebug).nospace()
+ << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
+ const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
newGroupValue = fileTime.toString(untranslatedFormat);
}
} else if (daysDistance <= 7 * 3) {
- const KLocalizedString format = ki18nc("@title:group Date: "
- "MMMM is full month name in current locale, and yyyy is "
- "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Two Weeks Ago' (MMMM, yyyy)");
+ const KLocalizedString format = ki18nc(
+ "@title:group Date: "
+ "MMMM is full month name in current locale, and yyyy is "
+ "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
+ "part of the text that should not be formatted as a date",
+ "'Two Weeks Ago' (MMMM, yyyy)");
const QString translatedFormat = format.toString();
if (translatedFormat.count(QLatin1Char('\'')) == 2) {
newGroupValue = fileTime.toString(translatedFormat);
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
} else {
- qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
- const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
+ qCWarning(DolphinDebug).nospace()
+ << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
+ const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
newGroupValue = fileTime.toString(untranslatedFormat);
}
} else if (daysDistance <= 7 * 4) {
- const KLocalizedString format = ki18nc("@title:group Date: "
- "MMMM is full month name in current locale, and yyyy is "
- "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Three Weeks Ago' (MMMM, yyyy)");
+ const KLocalizedString format = ki18nc(
+ "@title:group Date: "
+ "MMMM is full month name in current locale, and yyyy is "
+ "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
+ "part of the text that should not be formatted as a date",
+ "'Three Weeks Ago' (MMMM, yyyy)");
const QString translatedFormat = format.toString();
if (translatedFormat.count(QLatin1Char('\'')) == 2) {
newGroupValue = fileTime.toString(translatedFormat);
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
} else {
- qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
- const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
+ qCWarning(DolphinDebug).nospace()
+ << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
+ const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
newGroupValue = fileTime.toString(untranslatedFormat);
}
} else {
- const KLocalizedString format = ki18nc("@title:group Date: "
- "MMMM is full month name in current locale, and yyyy is "
- "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a part of the text that should not be formatted as a date", "'Earlier on' MMMM, yyyy");
+ const KLocalizedString format = ki18nc(
+ "@title:group Date: "
+ "MMMM is full month name in current locale, and yyyy is "
+ "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
+ "part of the text that should not be formatted as a date",
+ "'Earlier on' MMMM, yyyy");
const QString translatedFormat = format.toString();
if (translatedFormat.count(QLatin1Char('\'')) == 2) {
newGroupValue = fileTime.toString(translatedFormat);
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
} else {
- qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
- const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
+ qCWarning(DolphinDebug).nospace()
+ << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
+ const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
newGroupValue = fileTime.toString(untranslatedFormat);
}
}
} else {
- newGroupValue = fileTime.toString(i18nc("@title:group "
- "The month and year: MMMM is full month name in current locale, "
- "and yyyy is full year number", "MMMM, yyyy"));
- newGroupValue = i18nc("Can be used to script translation of "
+ newGroupValue =
+ fileTime.toString(i18nc("@title:group "
+ "The month and year: MMMM is full month name in current locale, "
+ "and yyyy is full year number",
+ "MMMM, yyyy"));
+ newGroupValue = i18nc(
+ "Can be used to script translation of "
"\"MMMM, yyyy\" with context @title:group Date",
- "%1", newGroupValue);
+ "%1",
+ newGroupValue);
}
}
return groups;
}
-QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
+QList<QPair<int, QVariant>> KFileItemModel::permissionRoleGroups() const
{
Q_ASSERT(!m_itemData.isEmpty());
const int maxIndex = count() - 1;
- QList<QPair<int, QVariant> > groups;
+ QList<QPair<int, QVariant>> groups;
QString permissionsString;
QString groupValue;
continue;
}
- const ItemData* itemData = m_itemData.at(i);
+ const ItemData *itemData = m_itemData.at(i);
const QString newPermissionsString = itemData->values.value("permissions").toString();
if (newPermissionsString == permissionsString) {
continue;
return groups;
}
-QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
+QList<QPair<int, QVariant>> KFileItemModel::ratingRoleGroups() const
{
Q_ASSERT(!m_itemData.isEmpty());
const int maxIndex = count() - 1;
- QList<QPair<int, QVariant> > groups;
+ QList<QPair<int, QVariant>> groups;
int groupValue = -1;
for (int i = 0; i <= maxIndex; ++i) {
return groups;
}
-QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
+QList<QPair<int, QVariant>> KFileItemModel::genericStringRoleGroups(const QByteArray &role) const
{
Q_ASSERT(!m_itemData.isEmpty());
const int maxIndex = count() - 1;
- QList<QPair<int, QVariant> > groups;
+ QList<QPair<int, QVariant>> groups;
bool isFirstGroupValue = true;
QString groupValue;
}
}
-const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count)
+const KFileItemModel::RoleInfoMap *KFileItemModel::rolesInfoMap(int &count)
{
static const RoleInfoMap rolesInfoMap[] = {
// | role | roleType | role translation | group translation | requires Baloo | requires indexer
return rolesInfoMap;
}
-void KFileItemModel::determineMimeTypes(const KFileItemList& items, int timeout)
+void KFileItemModel::determineMimeTypes(const KFileItemList &items, int timeout)
{
QElapsedTimer timer;
timer.start();
- for (const KFileItem& item : items) {
+ for (const KFileItem &item : items) {
// Only determine mime types for files here. For directories,
// KFileItem::determineMimeType() reads the .directory file inside to
// load the icon, but this is not necessary at all if we just need the
}
}
-QByteArray KFileItemModel::sharedValue(const QByteArray& value)
+QByteArray KFileItemModel::sharedValue(const QByteArray &value)
{
static QSet<QByteArray> pool;
const QSet<QByteArray>::const_iterator it = pool.constFind(value);
// Check if the items are sorted correctly.
if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) {
- qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:"
- << fileItem(i - 1) << fileItem(i);
+ qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:" << fileItem(i - 1) << fileItem(i);
return false;
}
// Check if all parent-child relationships are consistent.
- const ItemData* data = m_itemData.at(i);
- const ItemData* parent = data->parent;
+ const ItemData *data = m_itemData.at(i);
+ const ItemData *parent = data->parent;
if (parent) {
if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) {
qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item;
const int parentIndex = index(parent->item);
if (parentIndex >= i) {
- qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child" << data->item;
+ qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child"
+ << data->item;
return false;
}
}
class QTimer;
-namespace KIO {
- class Job;
+namespace KIO
+{
+class Job;
}
/**
Q_OBJECT
public:
- explicit KFileItemModel(QObject* parent = nullptr);
+ explicit KFileItemModel(QObject *parent = nullptr);
~KFileItemModel() override;
/**
* 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
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
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
* 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
/**
* 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;
* 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;
* 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
protected:
void onGroupedSortingChanged(bool current) override;
- void onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems = true) override;
+ void onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems = true) override;
void onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous) override;
private Q_SLOTS:
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);
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
* 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();
* 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.
* @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.
*/
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.
* @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
* 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
* 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;
/**
* @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.
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
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;
// 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();
}
}
#endif
-
-
// #define KFILEITEMMODELROLESUPDATER_DEBUG
-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;
-
- // Not only the visible area, but up to ReadAheadPages before and after
- // this area will be resolved.
- const int ReadAheadPages = 5;
+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;
+
+// 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);
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.
#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) {
killPreviewJob();
}
-void KFileItemModelRolesUpdater::setIconSize(const QSize& size)
+void KFileItemModelRolesUpdater::setIconSize(const QSize &size)
{
if (size != m_iconSize) {
m_iconSize = size;
return m_enlargeSmallPreviews;
}
-void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList& list)
+void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList &list)
{
if (m_enabledPlugins != list) {
m_enabledPlugins = list;
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();
}
}
-void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
+void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray> &roles)
{
if (m_roles != roles) {
m_roles = 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;
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;
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);
loadNextHoverSequencePreview();
}
-void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRanges)
+void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList &itemRanges)
{
QElapsedTimer timer;
timer.start();
// 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) {
startUpdating();
}
-void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRanges)
+void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList &itemRanges)
{
Q_UNUSED(itemRanges)
} 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);
}
}
// 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);
startUpdating();
}
-void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRanges,
- const QSet<QByteArray>& roles)
+void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles)
{
Q_UNUSED(roles)
// 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);
}
}
-void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current,
- const QByteArray& previous)
+void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
}
-void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPixmap& pixmap)
+void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem &item, const QPixmap &pixmap)
{
if (m_state != PreviewJobRunning) {
return;
// 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
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;
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);
}
}
-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) {
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();
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) {
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)
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();
}
}
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;
}
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));
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
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)
#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");
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);
}
}
}
// 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
} 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);
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;
}
// 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);
// 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);
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;
}
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;
}
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) {
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()
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;
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));
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();
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.
}
}
}
-
#include <list>
-#include <KFileItem>
#include "config-dolphin.h"
+#include <KFileItem>
#include <QObject>
#include <QSet>
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
/**
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;
/**
/**
* Sets the roles that should be resolved asynchronously.
*/
- void setRoles(const QSet<QByteArray>& roles);
+ void setRoles(const QSet<QByteArray> &roles);
QSet<QByteArray> roles() const;
/**
*
* @see enabledPlugins
*/
- void setEnabledPlugins(const QStringList& list);
+ void setEnabledPlugins(const QStringList &list);
/**
* Returns the list of enabled thumbnail plugins.
* 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 ¤t, const QByteArray &previous);
/**
* Is invoked after a preview has been received successfully.
*
* @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.
*
* @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
/**
* 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
/**
* 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
*/
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:
/**
* @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.
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
void trimHoverSequenceLoadedItems();
private:
- enum State {
- Idle,
- Paused,
- ResolvingSortRole,
- ResolvingAllRoles,
- PreviewJobRunning
- };
+ enum State { Idle, Paused, ResolvingSortRole, ResolvingAllRoles, PreviewJobRunning };
State m_state;
// 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;
// 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;
// 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
};
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);
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);
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()
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());
// 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);
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:
// 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();
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);
}
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);
}
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);
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);
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;
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);
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) {
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();
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);
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 {
* (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();
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
-
-
#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);
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();
}
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();
Q_EMIT viewChanged(m_view, oldView);
}
-KItemListView* KItemListController::view() const
+KItemListView *KItemListController::view() const
{
return m_view;
}
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();
return m_selectionMode;
}
-bool KItemListController::keyPressEvent(QKeyEvent* event)
+bool KItemListController::keyPressEvent(QKeyEvent *event)
{
int index = m_selectionManager->currentItem();
int key = event->key();
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();
// 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;
}
}
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();
}
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
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;
}
}
-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;
return true;
}
-bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
+bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform)
{
if (!m_view) {
return false;
}
}
} else {
- KItemListRubberBand* rubberBand = m_view->rubberBand();
+ KItemListRubberBand *rubberBand = m_view->rubberBand();
if (rubberBand->isActive()) {
QPointF endPos = transform.map(event->pos());
return false;
}
-bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
+bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent *event, const QTransform &transform)
{
m_mousePress = false;
m_isTouchEvent = false;
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;
}
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);
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)
return false;
}
-bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
+bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform)
{
Q_UNUSED(event)
Q_UNUSED(transform)
m_view->setAutoScroll(false);
m_view->hideDropIndicator();
- KItemListWidget* widget = hoveredWidget();
+ KItemListWidget *widget = hoveredWidget();
if (widget) {
widget->setHovered(false);
Q_EMIT itemUnhovered(widget->index());
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();
return false;
}
-bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
+bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent *event, const QTransform &transform)
{
if (!m_view) {
return false;
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) {
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) {
// 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
return false;
}
-bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
+bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent *event, const QTransform &transform)
{
Q_UNUSED(event)
Q_UNUSED(transform)
}
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());
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;
//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);
}
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)) {
return accepted;
}
-bool KItemListController::touchBeginEvent(QTouchEvent* event, const QTransform& transform)
+bool KItemListController::touchBeginEvent(QTouchEvent *event, const QTransform &transform)
{
Q_UNUSED(event)
Q_UNUSED(transform)
return false;
}
-void KItemListController::tapTriggered(QTapGesture* tap, const QTransform& transform)
+void KItemListController::tapTriggered(QTapGesture *tap, const QTransform &transform)
{
static bool scrollerWasActive = false;
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);
}
}
}
-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) {
}
}
-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;
}
}
-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;
}
}
-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;
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;
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;
}
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
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();
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();
}
// 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);
// 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;
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);
// 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);
}
}
// 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);
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;
}
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;
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;
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;
}
}
-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);
// - 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)) {
}
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);
}
// 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);
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) {
}
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);
}
m_oldSelection = m_selectionManager->selectedItems();
- KItemListRubberBand* rubberBand = m_view->rubberBand();
+ KItemListRubberBand *rubberBand = m_view->rubberBand();
rubberBand->setStartPosition(startPos);
rubberBand->setEndPosition(startPos);
rubberBand->setActive(true);
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;
void setSelectionModeEnabled(bool enabled);
bool selectionMode() const;
- bool processEvent(QEvent* event, const QTransform& transform);
+ bool processEvent(QEvent *event, const QTransform &transform);
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.
* 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.
*/
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);
*/
void slotRubberBandChanged();
- void slotChangeCurrentItem(const QString& text, bool searchFromNextItem);
+ void slotChangeCurrentItem(const QString &text, bool searchFromNextItem);
void slotAutoActivationTimeout();
* @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
* 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
*/
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:
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;
};
#endif
-
-
#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()
{
}
{
}
-void KItemListGroupHeader::setRole(const QByteArray& role)
+void KItemListGroupHeader::setRole(const QByteArray &role)
{
if (m_role != role) {
const QByteArray previous = m_role;
return m_role;
}
-void KItemListGroupHeader::setData(const QVariant& data)
+void KItemListGroupHeader::setData(const QVariant &data)
{
if (m_data != data) {
const QVariant previous = m_data;
return m_data;
}
-void KItemListGroupHeader::setStyleOption(const KItemListStyleOption& option)
+void KItemListGroupHeader::setStyleOption(const KItemListStyleOption &option)
{
if (m_styleOption == option) {
return;
styleOptionChanged(option, previous);
}
-const KItemListStyleOption& KItemListGroupHeader::styleOption() const
+const KItemListStyleOption &KItemListGroupHeader::styleOption() const
{
return m_styleOption;
}
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)
paintRole(painter, m_roleBounds, m_roleColor);
}
-void KItemListGroupHeader::roleChanged(const QByteArray& current, const QByteArray& previous)
+void KItemListGroupHeader::roleChanged(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
-void KItemListGroupHeader::dataChanged(const QVariant& current, const QVariant& previous)
+void KItemListGroupHeader::dataChanged(const QVariant ¤t, const QVariant &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
-void KItemListGroupHeader::styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
+void KItemListGroupHeader::styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
Q_UNUSED(previous)
}
-void KItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent* event)
+void KItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent *event)
{
QGraphicsWidget::resizeEvent(event);
if (event->oldSize().height() != event->newSize().height()) {
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
const QPalette::ColorGroup group = isActiveWindow() ? QPalette::Active : QPalette::Inactive;
return styleOption().palette.color(group, normalBaseColorRole());
}
-
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.
void setItemIndex(int index);
int itemIndex() const;
- void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
protected:
- virtual void paintRole(QPainter* painter, const QRectF& roleBounds, const QColor& color) = 0;
- virtual void paintSeparator(QPainter* painter, const QColor& color) = 0;
+ virtual void paintRole(QPainter *painter, const QRectF &roleBounds, const QColor &color) = 0;
+ virtual void paintSeparator(QPainter *painter, const QColor &color) = 0;
/**
* Is called after the role has been changed and allows the derived class
* to react on this change.
*/
- virtual void roleChanged(const QByteArray& current, const QByteArray& previous);
+ virtual void roleChanged(const QByteArray ¤t, const QByteArray &previous);
/**
* Is called after the role has been changed and allows the derived class
* to react on this change.
*/
- virtual void dataChanged(const QVariant& current, const QVariant& previous);
+ virtual void dataChanged(const QVariant ¤t, const QVariant &previous);
/**
* Is called after the style option has been changed and allows the derived class
* to react on this change.
*/
- virtual void styleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous);
+ virtual void styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous);
/**
* Is called after the scroll orientation has been changed and allows the derived class
*/
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;
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;
QRectF m_roleBounds;
};
#endif
-
-
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);
}
}
-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);
}
}
}
-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()) {
}
}
-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);
}
-
* 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
* 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.
* 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
-
-
#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)
{
}
return m_currentItem;
}
-void KItemListSelectionManager::setSelectedItems(const KItemSet& items)
+void KItemListSelectionManager::setSelectedItems(const KItemSet &items)
{
if (m_selectedItems != items) {
const KItemSet previous = m_selectedItems;
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) {
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) {
}
}
-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();
} 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;
}
m_anchorItem = 0;
} else {
int inc = 0;
- for (const KItemRange& itemRange : itemRanges) {
+ for (const KItemRange &itemRange : itemRanges) {
if (m_anchorItem < itemRange.index) {
break;
}
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;
}
}
}
-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();
for (int oldIndex : previous) {
const int index = indexAfterRangesRemoving(oldIndex, itemRanges, DiscardRemovedIndex);
- if (index >= 0) {
+ if (index >= 0) {
m_selectedItems.insert(index);
}
}
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();
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);
}
}
}
}
-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;
}
}
return qBound(-1, index - dec, m_model->count() - 1);
}
-
{
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;
void endAnchoredSelection();
bool isAnchoredSelectionActive() const;
- KItemModelBase* model() const;
+ KItemModelBase *model() const;
Q_SIGNALS:
void currentChanged(int current, int previous);
- void selectionChanged(const KItemSet& current, const KItemSet& previous);
+ void selectionChanged(const KItemSet ¤t, const KItemSet &previous);
private:
- void setModel(KItemModelBase* model);
- void itemsInserted(const KItemRangeList& itemRanges);
- void itemsRemoved(const KItemRangeList& itemRanges);
- void itemsMoved(const KItemRange& itemRange, const QList<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;
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;
};
#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)
{
}
{
}
-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);
}
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
-
-
#include <QTimer>
#include <QVariantAnimation>
+namespace
+{
+// Time in ms until reaching the autoscroll margin triggers
+// an initial autoscrolling
+const int InitialAutoScrollDelay = 700;
-namespace {
- // Time in ms until reaching the autoscroll margin triggers
- // an initial autoscrolling
- const int InitialAutoScrollDelay = 700;
-
- // Delay in ms for triggering the next autoscroll
- const int RepeatingAutoScrollDelay = 1000 / 60;
+// Delay in ms for triggering the next autoscroll
+const int RepeatingAutoScrollDelay = 1000 / 60;
- // Copied from the Kirigami.Units.shortDuration
- const int RubberFadeSpeed = 150;
+// Copied from the Kirigami.Units.shortDuration
+const int RubberFadeSpeed = 150;
- const char* RubberPropertyName = "_kitemviews_rubberBandPosition";
+const char *RubberPropertyName = "_kitemviews_rubberBandPosition";
}
#ifndef QT_NO_ACCESSIBILITY
-QAccessibleInterface* accessibleInterfaceFactory(const QString& key, QObject* object)
+QAccessibleInterface *accessibleInterfaceFactory(const QString &key, QObject *object)
{
Q_UNUSED(key)
- if (KItemListContainer* container = qobject_cast<KItemListContainer*>(object)) {
+ if (KItemListContainer *container = qobject_cast<KItemListContainer *>(object)) {
return new KItemListContainerAccessible(container);
- } else if (KItemListView* view = qobject_cast<KItemListView*>(object)) {
+ } else if (KItemListView *view = qobject_cast<KItemListView *>(object)) {
return new KItemListViewAccessible(view);
}
}
#endif
-KItemListView::KItemListView(QGraphicsWidget* parent) :
- QGraphicsWidget(parent),
- m_enabledSelectionToggles(false),
- m_grouped(false),
- m_highlightEntireRow(false),
- m_alternateBackgrounds(false),
- m_supportsItemExpanding(false),
- m_editingRole(false),
- m_activeTransactions(0),
- m_endTransactionAnimationHint(Animation),
- m_itemSize(),
- m_controller(nullptr),
- m_model(nullptr),
- m_visibleRoles(),
- m_widgetCreator(nullptr),
- m_groupHeaderCreator(nullptr),
- m_styleOption(),
- m_visibleItems(),
- m_visibleGroups(),
- m_visibleCells(),
- m_scrollBarExtent(0),
- m_layouter(nullptr),
- m_animation(nullptr),
- m_oldScrollOffset(0),
- m_oldMaximumScrollOffset(0),
- m_oldItemOffset(0),
- m_oldMaximumItemOffset(0),
- m_skipAutoScrollForRubberBand(false),
- m_rubberBand(nullptr),
- m_tapAndHoldIndicator(nullptr),
- m_mousePos(),
- m_autoScrollIncrement(0),
- m_autoScrollTimer(nullptr),
- m_header(nullptr),
- m_headerWidget(nullptr),
- m_indicatorAnimation(nullptr),
- m_dropIndicator(),
- m_sizeHintResolver(nullptr)
+KItemListView::KItemListView(QGraphicsWidget *parent)
+ : QGraphicsWidget(parent)
+ , m_enabledSelectionToggles(false)
+ , m_grouped(false)
+ , m_highlightEntireRow(false)
+ , m_alternateBackgrounds(false)
+ , m_supportsItemExpanding(false)
+ , m_editingRole(false)
+ , m_activeTransactions(0)
+ , m_endTransactionAnimationHint(Animation)
+ , m_itemSize()
+ , m_controller(nullptr)
+ , m_model(nullptr)
+ , m_visibleRoles()
+ , m_widgetCreator(nullptr)
+ , m_groupHeaderCreator(nullptr)
+ , m_styleOption()
+ , m_visibleItems()
+ , m_visibleGroups()
+ , m_visibleCells()
+ , m_scrollBarExtent(0)
+ , m_layouter(nullptr)
+ , m_animation(nullptr)
+ , m_oldScrollOffset(0)
+ , m_oldMaximumScrollOffset(0)
+ , m_oldItemOffset(0)
+ , m_oldMaximumItemOffset(0)
+ , m_skipAutoScrollForRubberBand(false)
+ , m_rubberBand(nullptr)
+ , m_tapAndHoldIndicator(nullptr)
+ , m_mousePos()
+ , m_autoScrollIncrement(0)
+ , m_autoScrollTimer(nullptr)
+ , m_header(nullptr)
+ , m_headerWidget(nullptr)
+ , m_indicatorAnimation(nullptr)
+ , m_dropIndicator()
+ , m_sizeHintResolver(nullptr)
{
setAcceptHoverEvents(true);
setAcceptTouchEvents(true);
m_layouter = new KItemListViewLayouter(m_sizeHintResolver, this);
m_animation = new KItemListViewAnimation(this);
- connect(m_animation, &KItemListViewAnimation::finished,
- this, &KItemListView::slotAnimationFinished);
+ connect(m_animation, &KItemListViewAnimation::finished, this, &KItemListView::slotAnimationFinished);
m_rubberBand = new KItemListRubberBand(this);
connect(m_rubberBand, &KItemListRubberBand::activationChanged, this, &KItemListView::slotRubberBandActivationChanged);
#ifndef QT_NO_ACCESSIBILITY
QAccessible::installFactory(accessibleInterfaceFactory);
#endif
-
}
KItemListView::~KItemListView()
return m_layouter->maximumVisibleItems();
}
-void KItemListView::setVisibleRoles(const QList<QByteArray>& roles)
+void KItemListView::setVisibleRoles(const QList<QByteArray> &roles)
{
const QList<QByteArray> previousRoles = m_visibleRoles;
m_visibleRoles = roles;
if (!m_headerWidget->automaticColumnResizing()) {
// The column-width of new roles are still 0. Apply the preferred
// column-width as default with.
- for (const QByteArray& role : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &role : qAsConst(m_visibleRoles)) {
if (m_headerWidget->columnWidth(role) == 0) {
const qreal width = m_headerWidget->preferredColumnWidth(role);
m_headerWidget->setColumnWidth(role, width);
}
}
- const bool alternateBackgroundsChanged = m_itemSize.isEmpty() &&
- ((roles.count() > 1 && previousRoles.count() <= 1) ||
- (roles.count() <= 1 && previousRoles.count() > 1));
+ const bool alternateBackgroundsChanged =
+ m_itemSize.isEmpty() && ((roles.count() > 1 && previousRoles.count() <= 1) || (roles.count() <= 1 && previousRoles.count() > 1));
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
- KItemListWidget* widget = it.value();
+ KItemListWidget *widget = it.value();
widget->setVisibleRoles(roles);
if (alternateBackgroundsChanged) {
updateAlternateBackgroundForWidget(widget);
if (m_enabledSelectionToggles != enabled) {
m_enabledSelectionToggles = enabled;
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
it.value()->setEnabledSelectionToggle(enabled);
return m_enabledSelectionToggles;
}
-KItemListController* KItemListView::controller() const
+KItemListController *KItemListView::controller() const
{
return m_controller;
}
-KItemModelBase* KItemListView::model() const
+KItemModelBase *KItemListView::model() const
{
return m_model;
}
-void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator)
+void KItemListView::setWidgetCreator(KItemListWidgetCreatorBase *widgetCreator)
{
delete m_widgetCreator;
m_widgetCreator = widgetCreator;
}
-KItemListWidgetCreatorBase* KItemListView::widgetCreator() const
+KItemListWidgetCreatorBase *KItemListView::widgetCreator() const
{
if (!m_widgetCreator) {
m_widgetCreator = defaultWidgetCreator();
return m_widgetCreator;
}
-void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator)
+void KItemListView::setGroupHeaderCreator(KItemListGroupHeaderCreatorBase *groupHeaderCreator)
{
delete m_groupHeaderCreator;
m_groupHeaderCreator = groupHeaderCreator;
}
-KItemListGroupHeaderCreatorBase* KItemListView::groupHeaderCreator() const
+KItemListGroupHeaderCreatorBase *KItemListView::groupHeaderCreator() const
{
if (!m_groupHeaderCreator) {
m_groupHeaderCreator = defaultGroupHeaderCreator();
return m_itemSize;
}
-const KItemListStyleOption& KItemListView::styleOption() const
+const KItemListStyleOption &KItemListView::styleOption() const
{
return m_styleOption;
}
-void KItemListView::setGeometry(const QRectF& rect)
+void KItemListView::setGeometry(const QRectF &rect)
{
QGraphicsWidget::setGeometry(rect);
applyAutomaticColumnWidths();
} else {
const qreal requiredWidth = columnWidthsSum();
- const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth),
- m_itemSize.height());
+ const QSizeF dynamicItemSize(qMax(newSize.width(), requiredWidth), m_itemSize.height());
m_layouter->setItemSize(dynamicItemSize);
}
}
return size().height() - headerHeight;
}
-std::optional<int> KItemListView::itemAt(const QPointF& pos) const
+std::optional<int> KItemListView::itemAt(const QPointF &pos) const
{
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
- const KItemListWidget* widget = it.value();
+ const KItemListWidget *widget = it.value();
const QPointF mappedPos = widget->mapFromItem(this, pos);
if (widget->contains(mappedPos) || widget->selectionRect().contains(mappedPos)) {
return it.key();
return std::nullopt;
}
-bool KItemListView::isAboveSelectionToggle(int index, const QPointF& pos) const
+bool KItemListView::isAboveSelectionToggle(int index, const QPointF &pos) const
{
if (!m_enabledSelectionToggles) {
return false;
}
- const KItemListWidget* widget = m_visibleItems.value(index);
+ const KItemListWidget *widget = m_visibleItems.value(index);
if (widget) {
const QRectF selectionToggleRect = widget->selectionToggleRect();
if (!selectionToggleRect.isEmpty()) {
return false;
}
-bool KItemListView::isAboveExpansionToggle(int index, const QPointF& pos) const
+bool KItemListView::isAboveExpansionToggle(int index, const QPointF &pos) const
{
- const KItemListWidget* widget = m_visibleItems.value(index);
+ const KItemListWidget *widget = m_visibleItems.value(index);
if (widget) {
const QRectF expansionToggleRect = widget->expansionToggleRect();
if (!expansionToggleRect.isEmpty()) {
bool KItemListView::isAboveText(int index, const QPointF &pos) const
{
- const KItemListWidget* widget = m_visibleItems.value(index);
+ const KItemListWidget *widget = m_visibleItems.value(index);
if (widget) {
const QRectF &textRect = widget->textRect();
if (!textRect.isEmpty()) {
return m_layouter->lastVisibleIndex();
}
-void KItemListView::calculateItemSizeHints(QVector<std::pair<qreal, bool>>& logicalHeightHints, qreal& logicalWidthHint) const
+void KItemListView::calculateItemSizeHints(QVector<std::pair<qreal, bool>> &logicalHeightHints, qreal &logicalWidthHint) const
{
widgetCreator()->calculateItemSizeHints(logicalHeightHints, logicalWidthHint, this);
}
{
QRectF contextRect;
- const KItemListWidget* widget = m_visibleItems.value(index);
+ const KItemListWidget *widget = m_visibleItems.value(index);
if (widget) {
contextRect = widget->iconRect() | widget->textRect();
contextRect.translate(itemRect(index).topLeft());
QRectF currentRect = itemRect(index);
// Fix for Bug 311099 - View the underscore when using Ctrl + PagDown
- currentRect.adjust(-m_styleOption.horizontalMargin, -m_styleOption.verticalMargin,
- m_styleOption.horizontalMargin, m_styleOption.verticalMargin);
+ currentRect.adjust(-m_styleOption.horizontalMargin, -m_styleOption.verticalMargin, m_styleOption.horizontalMargin, m_styleOption.verticalMargin);
if (!viewGeometry.contains(currentRect)) {
qreal newOffset = scrollOffset();
{
if (visible && !m_headerWidget->isVisible()) {
QStyleOptionHeader option;
- const QSize headerSize = style()->sizeFromContents(QStyle::CT_HeaderSection,
- &option, QSize());
+ const QSize headerSize = style()->sizeFromContents(QStyle::CT_HeaderSection, &option, QSize());
m_headerWidget->setPos(0, 0);
m_headerWidget->resize(size().width(), headerSize.height());
m_headerWidget->setColumns(m_visibleRoles);
m_headerWidget->setZValue(1);
- connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged,
- this, &KItemListView::slotHeaderColumnWidthChanged);
- connect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged,
- this, &KItemListView::slotSidePaddingChanged);
- connect(m_headerWidget, &KItemListHeaderWidget::columnMoved,
- this, &KItemListView::slotHeaderColumnMoved);
- connect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged,
- this, &KItemListView::sortOrderChanged);
- connect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged,
- this, &KItemListView::sortRoleChanged);
+ connect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, this, &KItemListView::slotHeaderColumnWidthChanged);
+ connect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, this, &KItemListView::slotSidePaddingChanged);
+ connect(m_headerWidget, &KItemListHeaderWidget::columnMoved, this, &KItemListView::slotHeaderColumnMoved);
+ connect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged, this, &KItemListView::sortOrderChanged);
+ connect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged, this, &KItemListView::sortRoleChanged);
m_layouter->setHeaderHeight(headerSize.height());
m_headerWidget->setVisible(true);
} else if (!visible && m_headerWidget->isVisible()) {
- disconnect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged,
- this, &KItemListView::slotHeaderColumnWidthChanged);
- disconnect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged,
- this, &KItemListView::slotSidePaddingChanged);
- disconnect(m_headerWidget, &KItemListHeaderWidget::columnMoved,
- this, &KItemListView::slotHeaderColumnMoved);
- disconnect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged,
- this, &KItemListView::sortOrderChanged);
- disconnect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged,
- this, &KItemListView::sortRoleChanged);
+ disconnect(m_headerWidget, &KItemListHeaderWidget::columnWidthChanged, this, &KItemListView::slotHeaderColumnWidthChanged);
+ disconnect(m_headerWidget, &KItemListHeaderWidget::sidePaddingChanged, this, &KItemListView::slotSidePaddingChanged);
+ disconnect(m_headerWidget, &KItemListHeaderWidget::columnMoved, this, &KItemListView::slotHeaderColumnMoved);
+ disconnect(m_headerWidget, &KItemListHeaderWidget::sortOrderChanged, this, &KItemListView::sortOrderChanged);
+ disconnect(m_headerWidget, &KItemListHeaderWidget::sortRoleChanged, this, &KItemListView::sortRoleChanged);
m_layouter->setHeaderHeight(0);
m_headerWidget->setVisible(false);
return m_headerWidget->isVisible();
}
-KItemListHeader* KItemListView::header() const
+KItemListHeader *KItemListView::header() const
{
return m_header;
}
-QPixmap KItemListView::createDragPixmap(const KItemSet& indexes) const
+QPixmap KItemListView::createDragPixmap(const KItemSet &indexes) const
{
QPixmap pixmap;
if (indexes.count() == 1) {
- KItemListWidget* item = m_visibleItems.value(indexes.first());
- QGraphicsView* graphicsView = scene()->views()[0];
+ KItemListWidget *item = m_visibleItems.value(indexes.first());
+ QGraphicsView *graphicsView = scene()->views()[0];
if (item && graphicsView) {
pixmap = item->createDragPixmap(nullptr, graphicsView);
}
return pixmap;
}
-void KItemListView::editRole(int index, const QByteArray& role)
+void KItemListView::editRole(int index, const QByteArray &role)
{
- KStandardItemListWidget* widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
+ KStandardItemListWidget *widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
if (!widget || m_editingRole) {
return;
}
m_editingRole = true;
widget->setEditedRole(role);
- connect(widget, &KItemListWidget::roleEditingCanceled,
- this, &KItemListView::slotRoleEditingCanceled);
- connect(widget, &KItemListWidget::roleEditingFinished,
- this, &KItemListView::slotRoleEditingFinished);
+ connect(widget, &KItemListWidget::roleEditingCanceled, this, &KItemListView::slotRoleEditingCanceled);
+ connect(widget, &KItemListWidget::roleEditingFinished, this, &KItemListView::slotRoleEditingFinished);
- connect(this, &KItemListView::scrollOffsetChanged,
- widget, &KStandardItemListWidget::finishRoleEditing);
+ connect(this, &KItemListView::scrollOffsetChanged, widget, &KStandardItemListWidget::finishRoleEditing);
}
-void KItemListView::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
+void KItemListView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QGraphicsWidget::paint(painter, option, widget);
}
if (m_rubberBand->isActive()) {
- QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
- m_rubberBand->endPosition()).normalized();
+ QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), m_rubberBand->endPosition()).normalized();
const QPointF topLeft = rubberBandRect.topLeft();
if (scrollOrientation() == Qt::Vertical) {
if (m_tapAndHoldIndicator->isActive()) {
const QPointF indicatorSize = m_tapAndHoldIndicator->endPosition();
- const QRectF rubberBandRect = QRectF(m_tapAndHoldIndicator->startPosition() - indicatorSize,
- (m_tapAndHoldIndicator->startPosition()) + indicatorSize).normalized();
+ const QRectF rubberBandRect =
+ QRectF(m_tapAndHoldIndicator->startPosition() - indicatorSize, (m_tapAndHoldIndicator->startPosition()) + indicatorSize).normalized();
QStyleOptionRubberBand opt;
initStyleOption(&opt);
opt.shape = QRubberBand::Rectangle;
return QGraphicsItem::itemChange(change, value);
}
-void KItemListView::setItemSize(const QSizeF& size)
+void KItemListView::setItemSize(const QSizeF &size)
{
const QSizeF previousSize = m_itemSize;
if (size == previousSize) {
// Skip animations when the number of rows or columns
// are changed in the grid layout. Although the animation
// engine can handle this usecase, it looks obtrusive.
- const bool animate = !changesItemGridLayout(m_layouter->size(),
- size,
- m_layouter->itemMargin());
+ const bool animate = !changesItemGridLayout(m_layouter->size(), size, m_layouter->itemMargin());
- const bool alternateBackgroundsChanged = m_alternateBackgrounds &&
- (( m_itemSize.isEmpty() && !size.isEmpty()) ||
- (!m_itemSize.isEmpty() && size.isEmpty()));
+ const bool alternateBackgroundsChanged = m_alternateBackgrounds && ((m_itemSize.isEmpty() && !size.isEmpty()) || (!m_itemSize.isEmpty() && size.isEmpty()));
m_itemSize = size;
onItemSizeChanged(size, previousSize);
}
-void KItemListView::setStyleOption(const KItemListStyleOption& option)
+void KItemListView::setStyleOption(const KItemListStyleOption &option)
{
if (m_styleOption == option) {
return;
// Skip animations when the number of rows or columns
// are changed in the grid layout. Although the animation
// engine can handle this usecase, it looks obtrusive.
- animate = !changesItemGridLayout(m_layouter->size(),
- m_layouter->itemSize(),
- margin);
+ animate = !changesItemGridLayout(m_layouter->size(), m_layouter->itemSize(), margin);
m_layouter->setItemMargin(margin);
}
updateGroupHeaderHeight();
}
- if (animate &&
- (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) {
+ if (animate && (previousOption.maxTextLines != option.maxTextLines || previousOption.maxTextWidth != option.maxTextWidth)) {
// Animating a change of the maximum text size just results in expensive
// temporary eliding and clipping operations and does not look good visually.
animate = false;
}
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
it.value()->setStyleOption(option);
m_sizeHintResolver->clearCache();
if (m_grouped) {
- QMutableHashIterator<KItemListWidget*, KItemListGroupHeader*> it (m_visibleGroups);
+ QMutableHashIterator<KItemListWidget *, KItemListGroupHeader *> it(m_visibleGroups);
while (it.hasNext()) {
it.next();
it.value()->setScrollOrientation(orientation);
}
updateGroupHeaderHeight();
-
}
doLayout(NoAnimation);
return m_layouter->scrollOrientation();
}
-KItemListWidgetCreatorBase* KItemListView::defaultWidgetCreator() const
+KItemListWidgetCreatorBase *KItemListView::defaultWidgetCreator() const
{
return nullptr;
}
-KItemListGroupHeaderCreatorBase* KItemListView::defaultGroupHeaderCreator() const
+KItemListGroupHeaderCreatorBase *KItemListView::defaultGroupHeaderCreator() const
{
return nullptr;
}
-void KItemListView::initializeItemListWidget(KItemListWidget* item)
+void KItemListView::initializeItemListWidget(KItemListWidget *item)
{
Q_UNUSED(item)
}
-bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const
+bool KItemListView::itemSizeHintUpdateRequired(const QSet<QByteArray> &changedRoles) const
{
Q_UNUSED(changedRoles)
return true;
}
-void KItemListView::onControllerChanged(KItemListController* current, KItemListController* previous)
+void KItemListView::onControllerChanged(KItemListController *current, KItemListController *previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
-void KItemListView::onModelChanged(KItemModelBase* current, KItemModelBase* previous)
+void KItemListView::onModelChanged(KItemModelBase *current, KItemModelBase *previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
Q_UNUSED(previous)
}
-void KItemListView::onItemSizeChanged(const QSizeF& current, const QSizeF& previous)
+void KItemListView::onItemSizeChanged(const QSizeF ¤t, const QSizeF &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
Q_UNUSED(previous)
}
-void KItemListView::onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous)
+void KItemListView::onVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
-void KItemListView::onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous)
+void KItemListView::onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
{
}
-bool KItemListView::event(QEvent* event)
+bool KItemListView::event(QEvent *event)
{
switch (event->type()) {
case QEvent::PaletteChange:
return QGraphicsWidget::event(event);
}
-void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent* event)
+void KItemListView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
m_mousePos = transform().map(event->pos());
event->accept();
}
-void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
+void KItemListView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsWidget::mouseMoveEvent(event);
}
}
-void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent* event)
+void KItemListView::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
event->setAccepted(true);
setAutoScroll(true);
}
-void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent* event)
+void KItemListView::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
QGraphicsWidget::dragMoveEvent(event);
}
}
-void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent* event)
+void KItemListView::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
QGraphicsWidget::dragLeaveEvent(event);
setAutoScroll(false);
}
-void KItemListView::dropEvent(QGraphicsSceneDragDropEvent* event)
+void KItemListView::dropEvent(QGraphicsSceneDragDropEvent *event)
{
QGraphicsWidget::dropEvent(event);
setAutoScroll(false);
}
-QList<KItemListWidget*> KItemListView::visibleItemListWidgets() const
+QList<KItemListWidget *> KItemListView::visibleItemListWidgets() const
{
return m_visibleItems.values();
}
}
}
-void KItemListView::slotItemsInserted(const KItemRangeList& itemRanges)
+void KItemListView::slotItemsInserted(const KItemRangeList &itemRanges)
{
if (m_itemSize.isEmpty()) {
updatePreferredColumnWidths(itemRanges);
m_sizeHintResolver->itemsInserted(itemRanges);
int previouslyInsertedCount = 0;
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
// range.index is related to the model before anything has been inserted.
// As in each loop the current item-range gets inserted the index must
// be increased by the already previously inserted items.
// Determine which visible items must be moved
QList<int> itemsToMove;
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
const int visibleItemIndex = it.key();
// from the highest index to the lowest index to prevent overlaps when setting the new index.
std::sort(itemsToMove.begin(), itemsToMove.end());
for (int i = itemsToMove.count() - 1; i >= 0; --i) {
- KItemListWidget* widget = m_visibleItems.value(itemsToMove[i]);
+ KItemListWidget *widget = m_visibleItems.value(itemsToMove[i]);
Q_ASSERT(widget);
const int newIndex = widget->index() + count;
if (hasMultipleRanges) {
// the size of the layouter will be decreased before calling doLayout(): This prevents
// an unnecessary temporary animation due to the geometry change of the inserted scrollbar.
const bool verticalScrollOrientation = (scrollOrientation() == Qt::Vertical);
- const bool decreaseLayouterSize = ( verticalScrollOrientation && maximumScrollOffset() > size().height()) ||
- (!verticalScrollOrientation && maximumScrollOffset() > size().width());
+ const bool decreaseLayouterSize = (verticalScrollOrientation && maximumScrollOffset() > size().height())
+ || (!verticalScrollOrientation && maximumScrollOffset() > size().width());
if (decreaseLayouterSize) {
const int scrollBarExtent = style()->pixelMetric(QStyle::PM_ScrollBarExtent);
}
}
-void KItemListView::slotItemsRemoved(const KItemRangeList& itemRanges)
+void KItemListView::slotItemsRemoved(const KItemRangeList &itemRanges)
{
if (m_itemSize.isEmpty()) {
// Don't pass the item-range: The preferred column-widths of
m_sizeHintResolver->itemsRemoved(itemRanges);
for (int i = itemRanges.count() - 1; i >= 0; --i) {
- const KItemRange& range = itemRanges[i];
+ const KItemRange &range = itemRanges[i];
const int index = range.index;
const int count = range.count;
if (index < 0 || count <= 0) {
// Iterate over a const copy because the container is mutated within the loop
// directly and in `recycleWidget()` (https://bugs.kde.org/show_bug.cgi?id=428374)
const auto visibleItems = m_visibleItems;
- for (KItemListWidget* widget : visibleItems) {
+ for (KItemListWidget *widget : visibleItems) {
const int i = widget->index();
if (i < firstRemovedIndex) {
continue;
// order to prevent overlaps when setting the new index.
std::sort(itemsToMove.begin(), itemsToMove.end());
for (int i : qAsConst(itemsToMove)) {
- KItemListWidget* widget = m_visibleItems.value(i);
+ KItemListWidget *widget = m_visibleItems.value(i);
Q_ASSERT(widget);
const int newIndex = i - count;
if (hasMultipleRanges) {
}
}
-void KItemListView::slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes)
+void KItemListView::slotItemsMoved(const KItemRange &itemRange, const QList<int> &movedToIndexes)
{
m_sizeHintResolver->itemsMoved(itemRange, movedToIndexes);
m_layouter->markAsDirty();
const int lastVisibleMovedIndex = qMin(lastVisibleIndex(), itemRange.index + itemRange.count - 1);
for (int index = firstVisibleMovedIndex; index <= lastVisibleMovedIndex; ++index) {
- KItemListWidget* widget = m_visibleItems.value(index);
+ KItemListWidget *widget = m_visibleItems.value(index);
if (widget) {
updateWidgetProperties(widget, index);
initializeItemListWidget(widget);
updateSiblingsInformation();
}
-void KItemListView::slotItemsChanged(const KItemRangeList& itemRanges,
- const QSet<QByteArray>& roles)
+void KItemListView::slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles)
{
const bool updateSizeHints = itemSizeHintUpdateRequired(roles);
if (updateSizeHints && m_itemSize.isEmpty()) {
updatePreferredColumnWidths(itemRanges);
}
- for (const KItemRange& itemRange : itemRanges) {
+ for (const KItemRange &itemRange : itemRanges) {
const int index = itemRange.index;
const int count = itemRange.count;
// Apply the changed roles to the visible item-widgets
const int lastIndex = index + count - 1;
for (int i = index; i <= lastIndex; ++i) {
- KItemListWidget* widget = m_visibleItems.value(i);
+ KItemListWidget *widget = m_visibleItems.value(i);
if (widget) {
widget->setData(m_model->data(i), roles);
}
// Clear all visible headers. Note that the QHashIterator takes a copy of
// m_visibleGroups. Therefore, it remains valid even if items are removed
// from m_visibleGroups in recycleGroupHeaderForWidget().
- QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
+ QHashIterator<KItemListWidget *, KItemListGroupHeader *> it(m_visibleGroups);
while (it.hasNext()) {
it.next();
recycleGroupHeaderForWidget(it.key());
}
}
-void KItemListView::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
+void KItemListView::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
// In SingleSelection mode (e.g., in the Places Panel), the current item is
// always the selected item. It is not necessary to highlight the current item then.
if (m_controller->selectionBehavior() != KItemListController::SingleSelection) {
- KItemListWidget* previousWidget = m_visibleItems.value(previous, nullptr);
+ KItemListWidget *previousWidget = m_visibleItems.value(previous, nullptr);
if (previousWidget) {
previousWidget->setCurrent(false);
}
- KItemListWidget* currentWidget = m_visibleItems.value(current, nullptr);
+ KItemListWidget *currentWidget = m_visibleItems.value(current, nullptr);
if (currentWidget) {
currentWidget->setCurrent(true);
}
QAccessible::updateAccessibility(&ev);
}
-void KItemListView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
+void KItemListView::slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous)
{
Q_UNUSED(previous)
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
const int index = it.key();
- KItemListWidget* widget = it.value();
+ KItemListWidget *widget = it.value();
widget->setSelected(current.contains(index));
}
}
-void KItemListView::slotAnimationFinished(QGraphicsWidget* widget,
- KItemListViewAnimation::AnimationType type)
+void KItemListView::slotAnimationFinished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type)
{
- KItemListWidget* itemListWidget = qobject_cast<KItemListWidget*>(widget);
+ KItemListWidget *itemListWidget = qobject_cast<KItemListWidget *>(widget);
Q_ASSERT(itemListWidget);
if (type == KItemListViewAnimation::DeleteAnimation) {
widgetCreator()->recycle(itemListWidget);
} else {
const int index = itemListWidget->index();
- const bool invisible = (index < m_layouter->firstVisibleIndex()) ||
- (index > m_layouter->lastVisibleIndex());
+ const bool invisible = (index < m_layouter->firstVisibleIndex()) || (index > m_layouter->lastVisibleIndex());
if (invisible && !m_animation->isStarted(itemListWidget)) {
recycleWidget(itemListWidget);
}
connect(m_rubberBand, &KItemListRubberBand::endPositionChanged, this, &KItemListView::slotRubberBandPosChanged);
m_skipAutoScrollForRubberBand = true;
} else {
- QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(),
- m_rubberBand->endPosition()).normalized();
+ QRectF rubberBandRect = QRectF(m_rubberBand->startPosition(), m_rubberBand->endPosition()).normalized();
auto animation = new QVariantAnimation(this);
animation->setStartValue(1.0);
curve.addCubicBezierSegment(QPointF(0.4, 0.0), QPointF(1.0, 1.0), QPointF(1.0, 1.0));
animation->setEasingCurve(curve);
- connect(animation, &QVariantAnimation::valueChanged, this, [=](const QVariant&) {
+ connect(animation, &QVariantAnimation::valueChanged, this, [=](const QVariant &) {
update();
});
connect(animation, &QVariantAnimation::finished, this, [=]() {
update();
}
-void KItemListView::slotHeaderColumnWidthChanged(const QByteArray& role,
- qreal currentWidth,
- qreal previousWidth)
+void KItemListView::slotHeaderColumnWidthChanged(const QByteArray &role, qreal currentWidth, qreal previousWidth)
{
Q_UNUSED(role)
Q_UNUSED(currentWidth)
doLayout(NoAnimation);
}
-void KItemListView::slotHeaderColumnMoved(const QByteArray& role,
- int currentIndex,
- int previousIndex)
+void KItemListView::slotHeaderColumnMoved(const QByteArray &role, int currentIndex, int previousIndex)
{
Q_ASSERT(m_visibleRoles[previousIndex] == role);
// an autoscrolling.
const qreal minDiff = 4; // Ignore any autoscrolling if the rubberband is very small
- const qreal diff = (scrollOrientation() == Qt::Vertical)
- ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
- : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
+ const qreal diff = (scrollOrientation() == Qt::Vertical) ? m_rubberBand->endPosition().y() - m_rubberBand->startPosition().y()
+ : m_rubberBand->endPosition().x() - m_rubberBand->startPosition().x();
if (qAbs(diff) < minDiff || (m_autoScrollIncrement < 0 && diff > 0) || (m_autoScrollIncrement > 0 && diff < 0)) {
// The rubberband direction is different from the scroll direction (e.g. the rubberband has
// been moved up although the autoscroll direction might be down)
void KItemListView::slotGeometryOfGroupHeaderParentChanged()
{
- KItemListWidget* widget = qobject_cast<KItemListWidget*>(sender());
+ KItemListWidget *widget = qobject_cast<KItemListWidget *>(sender());
Q_ASSERT(widget);
- KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
+ KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget);
Q_ASSERT(groupHeader);
updateGroupHeaderLayout(widget);
}
-void KItemListView::slotRoleEditingCanceled(int index, const QByteArray& role, const QVariant& value)
+void KItemListView::slotRoleEditingCanceled(int index, const QByteArray &role, const QVariant &value)
{
disconnectRoleEditingSignals(index);
Q_EMIT roleEditingCanceled(index, role, value);
}
-void KItemListView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
+void KItemListView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value)
{
disconnectRoleEditingSignals(index);
Q_EMIT roleEditingFinished(index, role, value);
}
-void KItemListView::setController(KItemListController* controller)
+void KItemListView::setController(KItemListController *controller)
{
if (m_controller != controller) {
- KItemListController* previous = m_controller;
+ KItemListController *previous = m_controller;
if (previous) {
- KItemListSelectionManager* selectionManager = previous->selectionManager();
+ KItemListSelectionManager *selectionManager = previous->selectionManager();
disconnect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged);
disconnect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged);
}
m_controller = controller;
if (controller) {
- KItemListSelectionManager* selectionManager = controller->selectionManager();
+ KItemListSelectionManager *selectionManager = controller->selectionManager();
connect(selectionManager, &KItemListSelectionManager::currentChanged, this, &KItemListView::slotCurrentChanged);
connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &KItemListView::slotSelectionChanged);
}
}
}
-void KItemListView::setModel(KItemModelBase* model)
+void KItemListView::setModel(KItemModelBase *model)
{
if (m_model == model) {
return;
}
- KItemModelBase* previous = m_model;
+ KItemModelBase *previous = m_model;
if (m_model) {
- disconnect(m_model, &KItemModelBase::itemsChanged,
- this, &KItemListView::slotItemsChanged);
- disconnect(m_model, &KItemModelBase::itemsInserted,
- this, &KItemListView::slotItemsInserted);
- disconnect(m_model, &KItemModelBase::itemsRemoved,
- this, &KItemListView::slotItemsRemoved);
- disconnect(m_model, &KItemModelBase::itemsMoved,
- this, &KItemListView::slotItemsMoved);
- disconnect(m_model, &KItemModelBase::groupsChanged,
- this, &KItemListView::slotGroupsChanged);
- disconnect(m_model, &KItemModelBase::groupedSortingChanged,
- this, &KItemListView::slotGroupedSortingChanged);
- disconnect(m_model, &KItemModelBase::sortOrderChanged,
- this, &KItemListView::slotSortOrderChanged);
- disconnect(m_model, &KItemModelBase::sortRoleChanged,
- this, &KItemListView::slotSortRoleChanged);
+ disconnect(m_model, &KItemModelBase::itemsChanged, this, &KItemListView::slotItemsChanged);
+ disconnect(m_model, &KItemModelBase::itemsInserted, this, &KItemListView::slotItemsInserted);
+ disconnect(m_model, &KItemModelBase::itemsRemoved, this, &KItemListView::slotItemsRemoved);
+ disconnect(m_model, &KItemModelBase::itemsMoved, this, &KItemListView::slotItemsMoved);
+ disconnect(m_model, &KItemModelBase::groupsChanged, this, &KItemListView::slotGroupsChanged);
+ disconnect(m_model, &KItemModelBase::groupedSortingChanged, this, &KItemListView::slotGroupedSortingChanged);
+ disconnect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListView::slotSortOrderChanged);
+ disconnect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListView::slotSortRoleChanged);
m_sizeHintResolver->itemsRemoved(KItemRangeList() << KItemRange(0, m_model->count()));
}
m_grouped = model->groupedSorting();
if (m_model) {
- connect(m_model, &KItemModelBase::itemsChanged,
- this, &KItemListView::slotItemsChanged);
- connect(m_model, &KItemModelBase::itemsInserted,
- this, &KItemListView::slotItemsInserted);
- connect(m_model, &KItemModelBase::itemsRemoved,
- this, &KItemListView::slotItemsRemoved);
- connect(m_model, &KItemModelBase::itemsMoved,
- this, &KItemListView::slotItemsMoved);
- connect(m_model, &KItemModelBase::groupsChanged,
- this, &KItemListView::slotGroupsChanged);
- connect(m_model, &KItemModelBase::groupedSortingChanged,
- this, &KItemListView::slotGroupedSortingChanged);
- connect(m_model, &KItemModelBase::sortOrderChanged,
- this, &KItemListView::slotSortOrderChanged);
- connect(m_model, &KItemModelBase::sortRoleChanged,
- this, &KItemListView::slotSortRoleChanged);
+ connect(m_model, &KItemModelBase::itemsChanged, this, &KItemListView::slotItemsChanged);
+ connect(m_model, &KItemModelBase::itemsInserted, this, &KItemListView::slotItemsInserted);
+ connect(m_model, &KItemModelBase::itemsRemoved, this, &KItemListView::slotItemsRemoved);
+ connect(m_model, &KItemModelBase::itemsMoved, this, &KItemListView::slotItemsMoved);
+ connect(m_model, &KItemModelBase::groupsChanged, this, &KItemListView::slotGroupsChanged);
+ connect(m_model, &KItemModelBase::groupedSortingChanged, this, &KItemListView::slotGroupedSortingChanged);
+ connect(m_model, &KItemModelBase::sortOrderChanged, this, &KItemListView::slotSortOrderChanged);
+ connect(m_model, &KItemModelBase::sortRoleChanged, this, &KItemListView::slotSortRoleChanged);
const int itemCount = m_model->count();
if (itemCount > 0) {
onModelChanged(model, previous);
}
-KItemListRubberBand* KItemListView::rubberBand() const
+KItemListRubberBand *KItemListView::rubberBand() const
{
return m_rubberBand;
}
const QRectF itemBounds = m_layouter->itemRect(i);
const QPointF newPos = itemBounds.topLeft();
- KItemListWidget* widget = m_visibleItems.value(i);
+ KItemListWidget *widget = m_visibleItems.value(i);
if (!widget) {
if (!reusableItems.isEmpty()) {
// Reuse a KItemListWidget instance from an invisible item
const int previousIndex = i - changedCount;
const QRectF itemRect = m_layouter->itemRect(previousIndex);
if (itemRect.isEmpty()) {
- const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical)
- ? QPointF(0, size().height()) : QPointF(size().width(), 0);
+ const QPointF invisibleOldPos = (scrollOrientation() == Qt::Vertical) ? QPointF(0, size().height()) : QPointF(size().width(), 0);
widget->setPos(invisibleOldPos);
} else {
widget->setPos(itemRect.topLeft());
if (animate) {
if (m_animation->isStarted(widget, KItemListViewAnimation::MovingAnimation)) {
- m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
+ m_animation->start(widget, KItemListViewAnimation::MovingAnimation, newPos);
applyNewPos = false;
}
if (m_grouped) {
// Update the layout of all visible group headers
- QHashIterator<KItemListWidget*, KItemListGroupHeader*> it(m_visibleGroups);
+ QHashIterator<KItemListWidget *, KItemListGroupHeader *> it(m_visibleGroups);
while (it.hasNext()) {
it.next();
updateGroupHeaderLayout(it.key());
emitOffsetChanges();
}
-QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex,
- int lastVisibleIndex,
- LayoutAnimationHint hint)
+QList<int> KItemListView::recycleInvisibleItems(int firstVisibleIndex, int lastVisibleIndex, LayoutAnimationHint hint)
{
// Determine all items that are completely invisible and might be
// reused for items that just got (at least partly) visible. If the
QList<int> items;
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
- KItemListWidget* widget = it.value();
+ KItemListWidget *widget = it.value();
const int index = widget->index();
const bool invisible = (index < firstVisibleIndex) || (index > lastVisibleIndex);
return items;
}
-bool KItemListView::moveWidget(KItemListWidget* widget,const QPointF& newPos)
+bool KItemListView::moveWidget(KItemListWidget *widget, const QPointF &newPos)
{
if (widget->pos() == newPos) {
return false;
}
}
-KItemListWidget* KItemListView::createWidget(int index)
+KItemListWidget *KItemListView::createWidget(int index)
{
- KItemListWidget* widget = widgetCreator()->create(this);
+ KItemListWidget *widget = widgetCreator()->create(this);
widget->setFlag(QGraphicsItem::ItemStacksBehindParent);
m_visibleItems.insert(index, widget);
return widget;
}
-void KItemListView::recycleWidget(KItemListWidget* widget)
+void KItemListView::recycleWidget(KItemListWidget *widget)
{
if (m_grouped) {
recycleGroupHeaderForWidget(widget);
widgetCreator()->recycle(widget);
}
-void KItemListView::setWidgetIndex(KItemListWidget* widget, int index)
+void KItemListView::setWidgetIndex(KItemListWidget *widget, int index)
{
const int oldIndex = widget->index();
m_visibleItems.remove(oldIndex);
widget->setIndex(index);
}
-void KItemListView::moveWidgetToIndex(KItemListWidget* widget, int index)
+void KItemListView::moveWidgetToIndex(KItemListWidget *widget, int index)
{
const int oldIndex = widget->index();
const Cell oldCell = m_visibleCells.value(oldIndex);
const Cell newCell(m_layouter->itemColumn(index), m_layouter->itemRow(index));
const bool vertical = (scrollOrientation() == Qt::Vertical);
- const bool updateCell = (vertical && oldCell.row == newCell.row) ||
- (!vertical && oldCell.column == newCell.column);
+ const bool updateCell = (vertical && oldCell.row == newCell.row) || (!vertical && oldCell.column == newCell.column);
if (updateCell) {
m_visibleCells.insert(index, newCell);
}
}
-void KItemListView::setLayouterSize(const QSizeF& size, SizeType sizeType)
+void KItemListView::setLayouterSize(const QSizeF &size, SizeType sizeType)
{
switch (sizeType) {
- case LayouterSize: m_layouter->setSize(size); break;
- case ItemSize: m_layouter->setItemSize(size); break;
- default: break;
+ case LayouterSize:
+ m_layouter->setSize(size);
+ break;
+ case ItemSize:
+ m_layouter->setItemSize(size);
+ break;
+ default:
+ break;
}
}
-void KItemListView::updateWidgetProperties(KItemListWidget* widget, int index)
+void KItemListView::updateWidgetProperties(KItemListWidget *widget, int index)
{
widget->setVisibleRoles(m_visibleRoles);
updateWidgetColumnWidths(widget);
widget->setStyleOption(m_styleOption);
- const KItemListSelectionManager* selectionManager = m_controller->selectionManager();
+ const KItemListSelectionManager *selectionManager = m_controller->selectionManager();
// In SingleSelection mode (e.g., in the Places Panel), the current item is
// always the selected item. It is not necessary to highlight the current item then.
}
}
-void KItemListView::updateGroupHeaderForWidget(KItemListWidget* widget)
+void KItemListView::updateGroupHeaderForWidget(KItemListWidget *widget)
{
Q_ASSERT(m_grouped);
return;
}
- const QList<QPair<int, QVariant> > groups = model()->groups();
+ const QList<QPair<int, QVariant>> groups = model()->groups();
if (groups.isEmpty() || !groupHeaderCreator()) {
return;
}
- KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
+ KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget);
if (!groupHeader) {
groupHeader = groupHeaderCreator()->create(this);
groupHeader->setParentItem(widget);
groupHeader->show();
}
-void KItemListView::updateGroupHeaderLayout(KItemListWidget* widget)
+void KItemListView::updateGroupHeaderLayout(KItemListWidget *widget)
{
- KItemListGroupHeader* groupHeader = m_visibleGroups.value(widget);
+ KItemListGroupHeader *groupHeader = m_visibleGroups.value(widget);
Q_ASSERT(groupHeader);
const int index = widget->index();
}
}
-void KItemListView::recycleGroupHeaderForWidget(KItemListWidget* widget)
+void KItemListView::recycleGroupHeaderForWidget(KItemListWidget *widget)
{
- KItemListGroupHeader* header = m_visibleGroups.value(widget);
+ KItemListGroupHeader *header = m_visibleGroups.value(widget);
if (header) {
header->setParentItem(nullptr);
groupHeaderCreator()->recycle(header);
Q_ASSERT(m_grouped);
m_layouter->markAsDirty();
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
updateGroupHeaderForWidget(it.value());
{
Q_ASSERT(m_grouped);
- const QList<QPair<int, QVariant> > groups = model()->groups();
+ const QList<QPair<int, QVariant>> groups = model()->groups();
if (groups.isEmpty()) {
return -1;
}
void KItemListView::updateAlternateBackgrounds()
{
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
updateAlternateBackgroundForWidget(it.value());
}
}
-void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget* widget)
+void KItemListView::updateAlternateBackgroundForWidget(KItemListWidget *widget)
{
bool enabled = useAlternateBackgrounds();
if (enabled) {
if (m_grouped) {
const int groupIndex = groupIndexForItem(index);
if (groupIndex >= 0) {
- const QList<QPair<int, QVariant> > groups = model()->groups();
+ const QList<QPair<int, QVariant>> groups = model()->groups();
const int indexOfFirstGroupItem = groups[groupIndex].first;
const int relativeIndex = index - indexOfFirstGroupItem;
enabled = (relativeIndex & 0x1) > 0;
return m_alternateBackgrounds && m_itemSize.isEmpty();
}
-QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList& itemRanges) const
+QHash<QByteArray, qreal> KItemListView::preferredColumnWidths(const KItemRangeList &itemRanges) const
{
QElapsedTimer timer;
timer.start();
// Calculate the minimum width for each column that is required
// to show the headline unclipped.
const QFontMetricsF fontMetrics(m_headerWidget->font());
- const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
+ const int gripMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderGripMargin);
const int headerMargin = m_headerWidget->style()->pixelMetric(QStyle::PM_HeaderMargin);
- for (const QByteArray& visibleRole : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &visibleRole : qAsConst(m_visibleRoles)) {
const QString headerText = m_model->roleDescription(visibleRole);
const qreal headerWidth = fontMetrics.horizontalAdvance(headerText) + gripMargin + headerMargin * 2;
widths.insert(visibleRole, headerWidth);
// Calculate the preferred column widths for each item and ignore values
// smaller than the width for showing the headline unclipped.
- const KItemListWidgetCreatorBase* creator = widgetCreator();
+ const KItemListWidgetCreatorBase *creator = widgetCreator();
int calculatedItemCount = 0;
bool maxTimeExceeded = false;
- for (const KItemRange& itemRange : itemRanges) {
+ for (const KItemRange &itemRange : itemRanges) {
const int startIndex = itemRange.index;
const int endIndex = startIndex + itemRange.count - 1;
for (int i = startIndex; i <= endIndex; ++i) {
- for (const QByteArray& visibleRole : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &visibleRole : qAsConst(m_visibleRoles)) {
qreal maxWidth = widths.value(visibleRole, 0);
const qreal width = creator->preferredRoleColumnWidth(visibleRole, i, this);
maxWidth = qMax(width, maxWidth);
{
// Apply the new size to the layouter
const qreal requiredWidth = columnWidthsSum() + m_headerWidget->sidePadding();
- const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth),
- m_itemSize.height());
+ const QSizeF dynamicItemSize(qMax(size().width(), requiredWidth), m_itemSize.height());
m_layouter->setItemSize(dynamicItemSize);
// Update the role sizes for all visible widgets
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
updateWidgetColumnWidths(it.value());
}
}
-void KItemListView::updateWidgetColumnWidths(KItemListWidget* widget)
+void KItemListView::updateWidgetColumnWidths(KItemListWidget *widget)
{
- for (const QByteArray& role : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &role : qAsConst(m_visibleRoles)) {
widget->setColumnWidth(role, m_headerWidget->columnWidth(role));
}
widget->setSidePadding(m_headerWidget->sidePadding());
}
-void KItemListView::updatePreferredColumnWidths(const KItemRangeList& itemRanges)
+void KItemListView::updatePreferredColumnWidths(const KItemRangeList &itemRanges)
{
Q_ASSERT(m_itemSize.isEmpty());
const int itemCount = m_model->count();
int rangesItemCount = 0;
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
rangesItemCount += range.count;
}
if (itemCount == rangesItemCount) {
const QHash<QByteArray, qreal> preferredWidths = preferredColumnWidths(itemRanges);
- for (const QByteArray& role : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &role : qAsConst(m_visibleRoles)) {
m_headerWidget->setPreferredColumnWidth(role, preferredWidths.value(role));
}
} else {
QHashIterator<QByteArray, qreal> it(updatedWidths);
while (it.hasNext()) {
it.next();
- const QByteArray& role = it.key();
+ const QByteArray &role = it.key();
const qreal updatedWidth = it.value();
const qreal currentWidth = m_headerWidget->preferredColumnWidth(role);
if (updatedWidth > currentWidth) {
// size does not use the available view-size the size of the
// first role will get stretched.
- for (const QByteArray& role : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &role : qAsConst(m_visibleRoles)) {
const qreal preferredWidth = m_headerWidget->preferredColumnWidth(role);
m_headerWidget->setColumnWidth(role, preferredWidth);
}
qreal requiredWidth = columnWidthsSum() + m_headerWidget->sidePadding()
+ m_headerWidget->sidePadding(); // Adding the padding a second time so we have the same padding symmetrically on both sides of the view.
- // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files.
+ // This improves UX, looks better and increases the chances of users figuring out that the padding area can be used for deselecting and dropping files.
const qreal availableWidth = size().width();
if (requiredWidth < availableWidth) {
// Stretch the first column to use the whole remaining width
m_layouter->setItemSize(dynamicItemSize);
// Update the role sizes for all visible widgets
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
updateWidgetColumnWidths(it.value());
qreal KItemListView::columnWidthsSum() const
{
qreal widthsSum = 0;
- for (const QByteArray& role : qAsConst(m_visibleRoles)) {
+ for (const QByteArray &role : qAsConst(m_visibleRoles)) {
widthsSum += m_headerWidget->columnWidth(role);
}
return widthsSum;
return m_headerWidget->isVisible() ? m_headerWidget->geometry() : QRectF();
}
-bool KItemListView::changesItemGridLayout(const QSizeF& newGridSize,
- const QSizeF& newItemSize,
- const QSizeF& newItemMargin) const
+bool KItemListView::changesItemGridLayout(const QSizeF &newGridSize, const QSizeF &newItemSize, const QSizeF &newItemMargin) const
{
if (newItemSize.isEmpty() || newGridSize.isEmpty()) {
return false;
if (m_layouter->scrollOrientation() == Qt::Vertical) {
const qreal itemWidth = m_layouter->itemSize().width();
if (itemWidth > 0) {
- const int newColumnCount = itemsPerSize(newGridSize.width(),
- newItemSize.width(),
- newItemMargin.width());
+ const int newColumnCount = itemsPerSize(newGridSize.width(), newItemSize.width(), newItemMargin.width());
if (m_model->count() > newColumnCount) {
- const int oldColumnCount = itemsPerSize(m_layouter->size().width(),
- itemWidth,
- m_layouter->itemMargin().width());
+ const int oldColumnCount = itemsPerSize(m_layouter->size().width(), itemWidth, m_layouter->itemMargin().width());
return oldColumnCount != newColumnCount;
}
}
} else {
const qreal itemHeight = m_layouter->itemSize().height();
if (itemHeight > 0) {
- const int newRowCount = itemsPerSize(newGridSize.height(),
- newItemSize.height(),
- newItemMargin.height());
+ const int newRowCount = itemsPerSize(newGridSize.height(), newItemSize.height(), newItemMargin.height());
if (m_model->count() > newRowCount) {
- const int oldRowCount = itemsPerSize(m_layouter->size().height(),
- itemHeight,
- m_layouter->itemMargin().height());
+ const int oldRowCount = itemsPerSize(m_layouter->size().height(), itemHeight, m_layouter->itemMargin().height());
return oldRowCount != newRowCount;
}
}
return false;
}
- const int maximum = (scrollOrientation() == Qt::Vertical)
- ? m_layouter->size().width() / m_layouter->itemSize().width()
- : m_layouter->size().height() / m_layouter->itemSize().height();
+ const int maximum = (scrollOrientation() == Qt::Vertical) ? m_layouter->size().width() / m_layouter->itemSize().width()
+ : m_layouter->size().height() / m_layouter->itemSize().height();
// Only animate if up to 2/3 of a row or column are inserted or removed
return changedItemCount <= maximum * 2 / 3;
}
-
-bool KItemListView::scrollBarRequired(const QSizeF& size) const
+bool KItemListView::scrollBarRequired(const QSizeF &size) const
{
const QSizeF oldSize = m_layouter->size();
const qreal maxOffset = m_layouter->maximumScrollOffset();
m_layouter->setSize(oldSize);
- return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height()
- : maxOffset > size.width();
+ return m_layouter->scrollOrientation() == Qt::Vertical ? maxOffset > size.height() : maxOffset > size.width();
}
-int KItemListView::showDropIndicator(const QPointF& pos)
+int KItemListView::showDropIndicator(const QPointF &pos)
{
- QHashIterator<int, KItemListWidget*> it(m_visibleItems);
+ QHashIterator<int, KItemListWidget *> it(m_visibleItems);
while (it.hasNext()) {
it.next();
- const KItemListWidget* widget = it.value();
+ const KItemListWidget *widget = it.value();
const QPointF mappedPos = widget->mapFromItem(this, pos);
const QRectF rect = itemRect(widget->index());
}
}
- const bool isAboveItem = (mappedPos.y () < rect.height() / 2);
+ const bool isAboveItem = (mappedPos.y() < rect.height() / 2);
const qreal y = isAboveItem ? rect.top() : rect.bottom();
const QRectF draggingInsertIndicator(rect.left(), y, rect.width(), 1);
// from m_styleOption.
groupHeaderHeight += 2 * m_styleOption.horizontalMargin;
groupHeaderMargin = m_styleOption.horizontalMargin;
- } else if (m_itemSize.isEmpty()){
+ } else if (m_itemSize.isEmpty()) {
groupHeaderHeight += 4 * m_styleOption.padding;
groupHeaderMargin = m_styleOption.iconSize / 2;
} else {
if (firstIndex < 0 || lastIndex < 0) {
firstIndex = m_layouter->firstVisibleIndex();
- lastIndex = m_layouter->lastVisibleIndex();
+ lastIndex = m_layouter->lastVisibleIndex();
} else {
- const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() &&
- lastIndex >= m_layouter->firstVisibleIndex());
+ const bool isRangeVisible = (firstIndex <= m_layouter->lastVisibleIndex() && lastIndex >= m_layouter->firstVisibleIndex());
if (!isRangeVisible) {
return;
}
// contain a siblings information which can be used as base.
int rootIndex = firstIndex;
- KItemListWidget* widget = m_visibleItems.value(firstIndex - 1);
+ KItemListWidget *widget = m_visibleItems.value(firstIndex - 1);
if (!widget) {
// There is no visible widget before the range, check whether there
// is one after the range:
if (i >= firstIndex) {
// The index represents a visible item. Apply the parent-siblings
// and update the sibling of the current item.
- KItemListWidget* widget = m_visibleItems.value(i);
+ KItemListWidget *widget = m_visibleItems.value(i);
if (!widget) {
continue;
}
void KItemListView::disconnectRoleEditingSignals(int index)
{
- KStandardItemListWidget* widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
+ KStandardItemListWidget *widget = qobject_cast<KStandardItemListWidget *>(m_visibleItems.value(index));
if (!widget) {
return;
}
return count;
}
-
-
KItemListCreatorBase::~KItemListCreatorBase()
{
qDeleteAll(m_recycleableWidgets);
qDeleteAll(m_createdWidgets);
}
-void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget* widget)
+void KItemListCreatorBase::addCreatedWidget(QGraphicsWidget *widget)
{
m_createdWidgets.insert(widget);
}
-void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget* widget)
+void KItemListCreatorBase::pushRecycleableWidget(QGraphicsWidget *widget)
{
Q_ASSERT(m_createdWidgets.contains(widget));
m_createdWidgets.remove(widget);
}
}
-QGraphicsWidget* KItemListCreatorBase::popRecycleableWidget()
+QGraphicsWidget *KItemListCreatorBase::popRecycleableWidget()
{
if (m_recycleableWidgets.isEmpty()) {
return nullptr;
}
- QGraphicsWidget* widget = m_recycleableWidgets.takeLast();
+ QGraphicsWidget *widget = m_recycleableWidgets.takeLast();
m_createdWidgets.insert(widget);
return widget;
}
{
}
-void KItemListWidgetCreatorBase::recycle(KItemListWidget* widget)
+void KItemListWidgetCreatorBase::recycle(KItemListWidget *widget)
{
widget->setParentItem(nullptr);
widget->setOpacity(1.0);
{
}
-void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader* header)
+void KItemListGroupHeaderCreatorBase::recycle(KItemListGroupHeader *header)
{
header->setOpacity(1.0);
pushRecycleableWidget(header);
}
-
Q_PROPERTY(qreal itemOffset READ itemOffset WRITE setItemOffset)
public:
- explicit KItemListView(QGraphicsWidget* parent = nullptr);
+ explicit KItemListView(QGraphicsWidget *parent = nullptr);
~KItemListView() override;
/**
int maximumVisibleItems() const;
- void setVisibleRoles(const QList<QByteArray>& roles);
+ void setVisibleRoles(const QList<QByteArray> &roles);
QList<QByteArray> visibleRoles() const;
/**
* 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
* 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
* 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
*/
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.
* 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.
* @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
* @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);
* the current sort role. Note that no signal will be emitted if the
* sort role of the model has been changed without user interaction.
*/
- void sortRoleChanged(const QByteArray& current, const QByteArray& previous);
+ void sortRoleChanged(const QByteArray ¤t, const QByteArray &previous);
/**
* Is emitted if the user has changed the visible roles by moving a header
* 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> ¤t, 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
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
* @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
* @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
* 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 ¤t, 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> ¤t, const QList<QByteArray> &previous);
+ virtual void onStyleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous);
virtual void onHighlightEntireRowChanged(bool highlightEntireRow);
virtual void onSupportsItemExpandingChanged(bool supportsExpanding);
virtual void onTransactionBegin();
virtual void onTransactionEnd();
- bool event(QEvent* event) override;
- void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override;
- void dragEnterEvent(QGraphicsSceneDragDropEvent* event) override;
- void dragMoveEvent(QGraphicsSceneDragDropEvent* event) override;
- void dragLeaveEvent(QGraphicsSceneDragDropEvent* event) override;
- void dropEvent(QGraphicsSceneDragDropEvent* event) override;
+ bool event(QEvent *event) override;
+ void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
+ void dragEnterEvent(QGraphicsSceneDragDropEvent *event) override;
+ void dragMoveEvent(QGraphicsSceneDragDropEvent *event) override;
+ void dragLeaveEvent(QGraphicsSceneDragDropEvent *event) override;
+ void dropEvent(QGraphicsSceneDragDropEvent *event) override;
- QList<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 ¤t, const QByteArray &previous);
virtual void slotCurrentChanged(int current, int previous);
- virtual void slotSelectionChanged(const KItemSet& current, const KItemSet& previous);
+ virtual void slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous);
private Q_SLOTS:
- void slotAnimationFinished(QGraphicsWidget* widget,
- KItemListViewAnimation::AnimationType type);
+ void slotAnimationFinished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type);
void slotRubberBandPosChanged();
void slotRubberBandActivationChanged(bool active);
* 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);
* 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
*/
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);
* 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
* 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
* 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()
* 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.
* 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
/**
* 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
* 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.
* 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
* @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();
/**
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;
-
- struct Cell
- {
- Cell() : column(-1), row(-1) {}
- Cell(int c, int r) : column(c), row(r) {}
+ 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)
+ {
+ }
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;
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
// 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;
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;
};
/**
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);
}
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);
}
{
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);
#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());
}
}
-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;
}
{
}
-QAccessibleInterface* KItemListViewAccessible::cell(int index) const
+QAccessibleInterface *KItemListViewAccessible::cell(int index) const
{
if (index < 0 || index >= view()->model()->count()) {
return nullptr;
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;
}
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) {
return QList<int>();
}
-QAccessibleInterface* KItemListViewAccessible::summary() const
+QAccessibleInterface *KItemListViewAccessible::summary() const
{
return nullptr;
}
return true;
}
-void KItemListViewAccessible::modelChange(QAccessibleTableModelChangeEvent* /*event*/)
-{}
+void KItemListViewAccessible::modelChange(QAccessibleTableModelChangeEvent * /*event*/)
+{
+}
QAccessible::Role KItemListViewAccessible::role() 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;
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();
}
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();
}
}
-QAccessibleInterface* KItemListViewAccessible::child(int index) const
+QAccessibleInterface *KItemListViewAccessible::child(int index) const
{
if (index >= 0 && index < childCount()) {
return cell(index);
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;
}
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
return m_view->controller()->selectionManager()->isSelected(m_index);
}
-QAccessibleInterface* KItemListAccessibleCell::table() const
+QAccessibleInterface *KItemListAccessibleCell::table() const
{
return QAccessible::queryAccessibleInterface(m_view);
}
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;
}
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;
}
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);
}
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)
{
}
return 1;
}
-int KItemListContainerAccessible::indexOfChild(const QAccessibleInterface* child) const
+int KItemListContainerAccessible::indexOfChild(const QAccessibleInterface *child) const
{
if (child->object() == container()->controller()->view()) {
return 0;
return -1;
}
-QAccessibleInterface* KItemListContainerAccessible::child(int index) const
+QAccessibleInterface *KItemListContainerAccessible::child(int index) const
{
if (index == 0) {
return QAccessible::queryAccessibleInterface(container()->controller()->view());
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
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;
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;
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();
* 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;
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;
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
{
}
-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);
}
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);
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)
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()) {
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();
}
}
-void KItemListWidget::setVisibleRoles(const QList<QByteArray>& roles)
+void KItemListWidget::setVisibleRoles(const QList<QByteArray> &roles)
{
const QList<QByteArray> previousRoles = m_visibleRoles;
m_visibleRoles = roles;
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) {
}
}
-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;
update();
}
-const KItemListStyleOption& KItemListWidget::styleOption() const
+const KItemListStyleOption &KItemListWidget::styleOption() const
{
return m_styleOption;
}
return m_expansionAreaHovered;
}
-void KItemListWidget::setHoverPosition(const QPointF& pos)
+void KItemListWidget::setHoverPosition(const QPointF &pos)
{
if (m_selectionToggle) {
m_selectionToggle->setHovered(selectionToggleRect().contains(pos));
return m_enabledSelectionToggle;
}
-void KItemListWidget::setSiblingsInformation(const QBitArray& siblings)
+void KItemListWidget::setSiblingsInformation(const QBitArray &siblings)
{
const QBitArray previous = m_siblingsInfo;
m_siblingsInfo = siblings;
return m_siblingsInfo;
}
-void KItemListWidget::setEditedRole(const QByteArray& role)
+void KItemListWidget::setEditedRole(const QByteArray &role)
{
if (m_editedRole != role) {
const QByteArray previous = m_editedRole;
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
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());
return pixmap;
}
-void KItemListWidget::dataChanged(const QHash<QByteArray, QVariant>& current,
- const QSet<QByteArray>& roles)
+void KItemListWidget::dataChanged(const QHash<QByteArray, QVariant> ¤t, 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> ¤t, 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)
Q_UNUSED(width)
}
-void KItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
- const KItemListStyleOption& previous)
+void KItemListWidget::styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous)
{
Q_UNUSED(previous)
Q_UNUSED(enabled)
}
-void KItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
+void KItemListWidget::siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
}
-void KItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
+void KItemListWidget::editedRoleChanged(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
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());
}
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);
viewItemOption.rect = selectionRect().toRect();
style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &viewItemOption, painter, widget);
}
-
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;
};
/**
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;
/**
* 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.
void setExpansionAreaHovered(bool hover);
bool expansionAreaHovered() const;
- void setHoverPosition(const QPointF& pos);
+ void setHoverPosition(const QPointF &pos);
void setAlternateBackground(bool enable);
bool alternateBackground() const;
* 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;
/**
* the role is empty. Derived classes must implement
* editedRoleChanged().
*/
- void setEditedRole(const QByteArray& role);
+ void setEditedRole(const QByteArray &role);
QByteArray editedRole() const;
/**
* 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.
* @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> ¤t, const QSet<QByteArray> &roles = QSet<QByteArray>());
+ virtual void visibleRolesChanged(const QList<QByteArray> ¤t, 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 ¤t, const KItemListStyleOption &previous);
virtual void currentChanged(bool current);
virtual void selectedChanged(bool selected);
virtual void hoveredChanged(bool hovered);
virtual void alternateBackgroundChanged(bool enabled);
- virtual void siblingsInformationChanged(const QBitArray& current, const QBitArray& previous);
- virtual void editedRoleChanged(const QByteArray& current, const QByteArray& previous);
+ virtual void siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous);
+ virtual void editedRoleChanged(const QByteArray ¤t, const QByteArray &previous);
virtual void iconSizeChanged(int current, int previous);
- void resizeEvent(QGraphicsSceneResizeEvent* event) override;
+ void resizeEvent(QGraphicsSceneResizeEvent *event) override;
void clearHoverCache();
/**
int hoverSequenceIndex() const;
- const KItemListWidgetInformant* informant() const;
+ const KItemListWidgetInformant *informant() const;
private Q_SLOTS:
void slotHoverAnimationFinished();
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;
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
-
-
#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)
{
}
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;
}
}
-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)
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)
Q_UNUSED(current)
}
-void KItemModelBase::onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems)
+void KItemModelBase::onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems)
{
Q_UNUSED(current)
Q_UNUSED(previous)
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. */
* 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
* 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;
/**
* @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
* 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.
* 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
* @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.
* - 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
* - 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.
* 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
void groupsChanged();
void groupedSortingChanged(bool current);
- void sortRoleChanged(const QByteArray& current, const QByteArray& previous);
+ void sortRoleChanged(const QByteArray ¤t, const QByteArray &previous);
void sortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
protected:
* itemsInserted() signal afterwards.
* The implementation should resort only if \a resortItems is true.
*/
- virtual void onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems = true);
+ virtual void onSortRoleChanged(const QByteArray ¤t, const QByteArray &previous, bool resortItems = true);
/**
* Is invoked if the sort order has been changed by KItemModelBase::setSortOrder(). Allows
}
#endif
-
-
#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;
};
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();
#include "kitemset.h"
-
KItemSet::iterator KItemSet::insert(int i)
{
if (m_itemRanges.empty()) {
}
}
-KItemSet KItemSet::operator+(const KItemSet& other) const
+KItemSet KItemSet::operator+(const KItemSet &other) const
{
KItemSet sum;
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));
}
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.
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;
}
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-
#ifndef KITEMSET_H
#define KITEMSET_H
{
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.
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;
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;
return r;
}
- inline iterator& operator--()
+ inline iterator &operator--()
{
if (m_offset == 0) {
--m_rangeIt;
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;
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;
return r;
}
- inline const_iterator& operator--()
+ inline const_iterator &operator--()
{
if (m_offset == 0) {
--m_rangeIt;
* 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:
/**
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;
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;
}
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;
#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();
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);
}
}
-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
m_dirtyCache = true;
}
-void KStandardItemListGroupHeader::dataChanged(const QVariant& current, const QVariant& previous)
+void KStandardItemListGroupHeader::dataChanged(const QVariant ¤t, const QVariant &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
m_dirtyCache = true;
}
-void KStandardItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent* event)
+void KStandardItemListGroupHeader::resizeEvent(QGraphicsSceneResizeEvent *event)
{
KItemListGroupHeader::resizeEvent(event);
m_dirtyCache = true;
m_text = text;
}
}
-
Q_OBJECT
public:
- explicit KStandardItemListGroupHeader(QGraphicsWidget* parent = nullptr);
+ explicit KStandardItemListGroupHeader(QGraphicsWidget *parent = nullptr);
~KStandardItemListGroupHeader() override;
- void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
protected:
- void paintRole(QPainter* painter, const QRectF& roleBounds, const QColor& color) override;
- void paintSeparator(QPainter* painter, const QColor& color) override;
+ void paintRole(QPainter *painter, const QRectF &roleBounds, const QColor &color) override;
+ void paintSeparator(QPainter *painter, const QColor &color) override;
void roleChanged(const QByteArray ¤t, const QByteArray &previous) override;
- void dataChanged(const QVariant& current, const QVariant& previous) override;
- void resizeEvent(QGraphicsSceneResizeEvent* event) override;
+ void dataChanged(const QVariant ¤t, const QVariant &previous) override;
+ void resizeEvent(QGraphicsSceneResizeEvent *event) override;
private:
void updateCache();
QPixmap m_pixmap;
};
#endif
-
-
#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);
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.
// 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;
}
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();
{
if (model()) {
const auto widgets = visibleItemListWidgets();
- for (KItemListWidget* widget : widgets) {
+ for (KItemListWidget *widget : widgets) {
initializeItemListWidget(widget);
}
}
}
-
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;
};
#endif
-
-
// #define KSTANDARDITEMLISTWIDGET_DEBUG
-KStandardItemListWidgetInformant::KStandardItemListWidgetInformant() :
- KItemListWidgetInformant()
+KStandardItemListWidgetInformant::KStandardItemListWidgetInformant()
+ : KItemListWidgetInformant()
{
}
{
}
-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;
}
}
-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);
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.
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();
}
// 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);
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;
}
// 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.
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);
}
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)
{
}
return m_layout;
}
-void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow) {
+void KStandardItemListWidget::setHighlightEntireRow(bool highlightEntireRow)
+{
if (m_highlightEntireRow != highlightEntireRow) {
m_highlightEntireRow = highlightEntireRow;
m_dirtyLayout = true;
}
}
-bool KStandardItemListWidget::highlightEntireRow() const {
+bool KStandardItemListWidget::highlightEntireRow() const
+{
return m_highlightEntireRow;
}
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);
drawSiblingsInformation(painter);
}
- const KItemListStyleOption& itemListStyleOption = styleOption();
+ const KItemListStyleOption &itemListStyleOption = styleOption();
if (isHovered() && !m_pixmap.isNull()) {
if (hoverOpacity() < 1.0) {
/*
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
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) {
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;
}
// 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;
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);
QRectF KStandardItemListWidget::selectionRect() const
{
- const_cast<KStandardItemListWidget*>(this)->triggerCacheRefreshing();
+ const_cast<KStandardItemListWidget *>(this)->triggerCacheRefreshing();
switch (m_layout) {
case IconsLayout:
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;
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) {
// 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);
return clippedPixmap;
}
-
-KItemListWidgetInformant* KStandardItemListWidget::createInformant()
+KItemListWidgetInformant *KStandardItemListWidget::createInformant()
{
return new KStandardItemListWidgetInformant();
}
{
}
-bool KStandardItemListWidget::isRoleRightAligned(const QByteArray& role) const
+bool KStandardItemListWidget::isRoleRightAligned(const QByteArray &role) const
{
Q_UNUSED(role)
return false;
return false;
}
-QFont KStandardItemListWidget::customizedFont(const QFont& baseFont) const
+QFont KStandardItemListWidget::customizedFont(const QFont &baseFont) const
{
return baseFont;
}
return QPalette::Text;
}
-void KStandardItemListWidget::setTextColor(const QColor& color)
+void KStandardItemListWidget::setTextColor(const QColor &color)
{
if (color != m_customTextColor) {
m_customTextColor = color;
return styleOption().palette.color(group, role);
}
-void KStandardItemListWidget::setOverlay(const QPixmap& overlay)
+void KStandardItemListWidget::setOverlay(const QPixmap &overlay)
{
m_overlay = overlay;
m_dirtyContent = true;
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> ¤t, const QSet<QByteArray> &roles)
{
Q_UNUSED(current)
// 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);
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> ¤t, 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)
m_dirtyLayout = true;
}
-void KStandardItemListWidget::sidePaddingChanged(qreal padding) {
+void KStandardItemListWidget::sidePaddingChanged(qreal padding)
+{
Q_UNUSED(padding)
m_dirtyLayout = true;
}
-void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption& current,
- const KItemListStyleOption& previous)
+void KStandardItemListWidget::styleOptionChanged(const KItemListStyleOption ¤t, const KItemListStyleOption &previous)
{
KItemListWidget::styleOptionChanged(current, previous);
m_dirtyContent = true;
}
-void KStandardItemListWidget::siblingsInformationChanged(const QBitArray& current, const QBitArray& previous)
+void KStandardItemListWidget::siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
m_dirtyLayout = true;
}
-int KStandardItemListWidget::selectionLength(const QString& text) const
+int KStandardItemListWidget::selectionLength(const QString &text) const
{
return text.length();
}
-void KStandardItemListWidget::editedRoleChanged(const QByteArray& current, const QByteArray& previous)
+void KStandardItemListWidget::editedRoleChanged(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(previous)
- QGraphicsView* parent = scene()->views()[0];
+ QGraphicsView *parent = scene()->views()[0];
if (current.isEmpty() || !parent || current != "text") {
if (m_roleEditor) {
Q_EMIT roleEditingCanceled(index(), current, data().value(current));
- disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled,
- this, &KStandardItemListWidget::slotRoleEditingCanceled);
- disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished,
- this, &KStandardItemListWidget::slotRoleEditingFinished);
+ disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingCanceled, this, &KStandardItemListWidget::slotRoleEditingCanceled);
+ disconnect(m_roleEditor, &KItemListRoleEditor::roleEditingFinished, this, &KStandardItemListWidget::slotRoleEditingFinished);
if (m_oldRoleEditor) {
m_oldRoleEditor->deleteLater();
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);
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);
update();
}
-void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent* event)
+void KStandardItemListWidget::resizeEvent(QGraphicsSceneResizeEvent *event)
{
if (m_roleEditor) {
setEditedRole(QByteArray());
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;
}
}
}
-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);
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();
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();
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) {
}
}
- 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];
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
}
if (m_isCut) {
- KIconEffect* effect = KIconLoader::global()->iconEffect();
+ KIconEffect *effect = KIconLoader::global()->iconEffect();
m_pixmap = effect->apply(m_pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
}
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;
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) {
} 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);
}
// 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);
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);
}
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;
}
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
return ret;
}
}
- return m_customizedFontMetrics.elidedText(text,Qt::ElideRight,
- elidingWidth);
+ return m_customizedFontMetrics.elidedText(text, Qt::ElideRight, elidingWidth);
}
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);
// 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;
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;
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);
// +------+
m_textRect = QRectF();
- const KItemListStyleOption& option = styleOption();
+ const KItemListStyleOption &option = styleOption();
const QHash<QByteArray, QVariant> values = data();
const qreal widgetHeight = size().height();
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
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
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;
}
}
-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;
}
}
-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();
}
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
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"));
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;
}
// 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;
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;
}
-
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:
/**
* 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()
};
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);
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;
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:
/**
* @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
/**
* @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:
*
* @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> ¤t, const QSet<QByteArray> &roles = QSet<QByteArray>()) override;
+ void visibleRolesChanged(const QList<QByteArray> ¤t, 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 ¤t, const KItemListStyleOption &previous) override;
void hoveredChanged(bool hovered) override;
void selectedChanged(bool selected) override;
- void siblingsInformationChanged(const QBitArray& current, const QBitArray& previous) override;
- void editedRoleChanged(const QByteArray& current, const QByteArray& previous) override;
+ void siblingsInformationChanged(const QBitArray ¤t, const QBitArray &previous) override;
+ void editedRoleChanged(const QByteArray ¤t, const QByteArray &previous) override;
void iconSizeChanged(int current, int previous) override;
- void resizeEvent(QGraphicsSceneResizeEvent* event) override;
- void showEvent(QShowEvent* event) override;
- void hideEvent(QHideEvent* event) override;
+ void resizeEvent(QGraphicsSceneResizeEvent *event) override;
+ void showEvent(QShowEvent *event) override;
+ void hideEvent(QHideEvent *event) override;
bool event(QEvent *event) override;
- struct TextInfo
- {
+ struct TextInfo {
QPointF pos;
QStaticText staticText;
};
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();
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;
*/
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;
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;
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
#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() {
}
}
-struct KBalooRolesProviderSingleton
-{
+struct KBalooRolesProviderSingleton {
KBalooRolesProvider instance;
};
Q_GLOBAL_STATIC(KBalooRolesProviderSingleton, s_balooRolesProvider)
-
-KBalooRolesProvider& KBalooRolesProvider::instance()
+KBalooRolesProvider &KBalooRolesProvider::instance()
{
return s_balooRolesProvider->instance;
}
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)) {
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) {
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");
m_roles.insert(QByteArrayLiteral("comment"));
m_roles.insert(QByteArrayLiteral("originUrl"));
}
-
#include <QSet>
#include <QVariant>
-namespace Baloo {
- class File;
+namespace Baloo
+{
+class File;
}
/**
class DOLPHIN_EXPORT KBalooRolesProvider
{
public:
- static KBalooRolesProvider& instance();
+ static KBalooRolesProvider &instance();
virtual ~KBalooRolesProvider();
/**
* @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();
};
#endif
-
#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();
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);
}
}
-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;
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) {
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();
} 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();
}
}
-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);
}
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 {
}
}
-QThread* KDirectoryContentsCounter::m_workerThread = nullptr;
+QThread *KDirectoryContentsCounter::m_workerThread = nullptr;
Q_OBJECT
public:
- explicit KDirectoryContentsCounter(KFileItemModel* model, QObject* parent = nullptr);
+ explicit KDirectoryContentsCounter(KFileItemModel *model, QObject *parent = nullptr);
~KDirectoryContentsCounter() override;
/**
* 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
#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;
// 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;
}
}
#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;
#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);
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 {
long size;
};
- explicit KDirectoryContentsCounterWorker(QObject* parent = nullptr);
+ explicit KDirectoryContentsCounterWorker(QObject *parent = nullptr);
/**
* Counts the items inside the directory \a path using the options
*
* @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:
/**
// 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)
};
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);
}
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) {
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);
}
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;
#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()
{
}
m_regExp = nullptr;
}
-void KFileItemModelFilter::setPattern(const QString& filter)
+void KFileItemModelFilter::setPattern(const QString &filter)
{
m_pattern = filter;
m_lowerCasePattern = filter.toLower();
return m_pattern;
}
-void KFileItemModelFilter::setMimeTypes(const QStringList& types)
+void KFileItemModelFilter::setMimeTypes(const QStringList &types)
{
m_mimeTypes = types;
}
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();
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();
}
}
-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;
}
*/
class DOLPHIN_EXPORT KFileItemModelFilter
{
-
public:
KFileItemModelFilter();
virtual ~KFileItemModelFilter();
* 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;
/**
* @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
-
-
* 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).
* 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;
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();
* 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).
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);
}
#endif
-
#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;
{
}
-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;
}
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);
}
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) {
}
}
-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);
}
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)
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);
}
}
-void KItemListHeaderWidget::mousePressEvent(QGraphicsSceneMouseEvent* event)
+void KItemListHeaderWidget::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() & Qt::LeftButton) {
m_pressedMousePos = event->pos();
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 {
}
}
-void KItemListHeaderWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
+void KItemListHeaderWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsWidget::mouseReleaseEvent(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 {
QApplication::restoreOverrideCursor();
}
-void KItemListHeaderWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
+void KItemListHeaderWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsWidget::mouseMoveEvent(event);
}
}
-void KItemListHeaderWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
+void KItemListHeaderWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseDoubleClickEvent(event);
}
}
-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) {
}
}
-void KItemListHeaderWidget::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
+void KItemListHeaderWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
QGraphicsWidget::hoverMoveEvent(event);
- const QPointF& pos = event->pos();
+ const QPointF &pos = event->pos();
updateHoveredRoleIndex(pos);
- if ((m_hoveredRoleIndex >= 0 && isAboveRoleGrip(pos, m_hoveredRoleIndex)) ||
- isAbovePaddingGrip(pos, PaddingGrip::Leading) ||
- isAbovePaddingGrip(pos, PaddingGrip::Trailing)) {
+ if ((m_hoveredRoleIndex >= 0 && isAboveRoleGrip(pos, m_hoveredRoleIndex)) || isAbovePaddingGrip(pos, PaddingGrip::Leading)
+ || isAbovePaddingGrip(pos, PaddingGrip::Trailing)) {
setCursor(Qt::SplitHCursor);
} else {
unsetCursor();
}
}
-void KItemListHeaderWidget::slotSortRoleChanged(const QByteArray& current, const QByteArray& previous)
+void KItemListHeaderWidget::slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(current)
Q_UNUSED(previous)
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();
// 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;
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;
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;
// 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;
}
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) {
}
}
-void KItemListHeaderWidget::updateHoveredRoleIndex(const QPointF& pos)
+void KItemListHeaderWidget::updateHoveredRoleIndex(const QPointF &pos)
{
const int hoverIndex = roleIndexAt(pos);
if (m_hoveredRoleIndex != hoverIndex) {
}
}
-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) {
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) {
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);
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;
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;
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;
}
return -1;
}
-
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;
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);
* 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
* the current sort role. Note that no signal will be emitted if the
* sort role of the model has been changed without user interaction.
*/
- void sortRoleChanged(const QByteArray& current, const QByteArray& previous);
+ void sortRoleChanged(const QByteArray ¤t, const QByteArray &previous);
protected:
- void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override;
- void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override;
- void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override;
- void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override;
- void hoverMoveEvent(QGraphicsSceneHoverEvent* event) override;
+ void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
+ void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
+ void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override;
+ void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
+ void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
+ void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override;
private Q_SLOTS:
- void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous);
+ void slotSortRoleChanged(const QByteArray ¤t, const QByteArray &previous);
void slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
private:
-
- enum PaddingGrip
- {
+ enum PaddingGrip {
Leading,
Trailing,
};
- void paintRole(QPainter* painter,
- const QByteArray& role,
- const QRectF& rect,
- int orderIndex,
- QWidget* widget = nullptr) const;
+ void paintRole(QPainter *painter, const QByteArray &role, const QRectF &rect, int orderIndex, QWidget *widget = nullptr) const;
- void updatePressedRoleIndex(const QPointF& pos);
- void updateHoveredRoleIndex(const QPointF& pos);
- int roleIndexAt(const QPointF& pos) const;
- bool isAboveRoleGrip(const QPointF& pos, int roleIndex) const;
- bool isAbovePaddingGrip(const QPointF& pos, PaddingGrip paddingGrip) const;
+ void updatePressedRoleIndex(const QPointF &pos);
+ void updateHoveredRoleIndex(const QPointF &pos);
+ int roleIndexAt(const QPointF &pos) const;
+ bool isAboveRoleGrip(const QPointF &pos, int roleIndex) const;
+ bool isAbovePaddingGrip(const QPointF &pos, PaddingGrip paddingGrip) const;
/**
* Creates a pixmap of the role with the index \a roleIndex that is shown
/**
* @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;
RoleOperation m_roleOperation;
QPointF m_pressedMousePos;
- struct MovingRole
- {
+ struct MovingRole {
QPixmap pixmap;
int x;
int xDec;
};
#endif
-
-
#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();
}
return (keyboardInputTimeElapsed > m_timeout) || !keyboardTimeWasValid;
}
-void KItemListKeyboardSearchManager::addKeys(const QString& keys)
+void KItemListKeyboardSearchManager::addKeys(const QString &keys)
{
if (shouldClearSearchIfInputTimeReached()) {
m_searchedString.clear();
}
}
-void KItemListKeyboardSearchManager::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
+void KItemListKeyboardSearchManager::slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous)
{
if (!previous.isEmpty() && current.isEmpty() && previous.count() > 0 && current.count() == 0) {
// The selection has been emptied. We should cancel the search.
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.
public Q_SLOTS:
void slotCurrentChanged(int current, int previous);
- void slotSelectionChanged(const KItemSet& current, const KItemSet& previous);
+ void slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous);
Q_SIGNALS:
/**
*/
// 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();
};
#endif
-
-
#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);
{
}
-void KItemListRoleEditor::setRole(const QByteArray& role)
+void KItemListRoleEditor::setRole(const QByteArray &role)
{
m_role = role;
}
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();
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();
}
return KTextEdit::event(event);
}
-void KItemListRoleEditor::keyPressEvent(QKeyEvent* event)
+void KItemListRoleEditor::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Escape:
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);
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);
}
}
-
#include <KTextEdit>
-enum EditResultDirection{
+enum EditResultDirection {
EditDone,
EditNext,
EditPrevious,
};
Q_DECLARE_METATYPE(EditResultDirection)
-struct EditResult
-{
+struct EditResult {
QString newName;
EditResultDirection direction;
};
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:
/**
#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()
{
}
{
}
-void KItemListRubberBand::setStartPosition(const QPointF& pos)
+void KItemListRubberBand::setStartPosition(const QPointF &pos)
{
if (m_startPos != pos) {
const QPointF previous = m_startPos;
return m_startPos;
}
-void KItemListRubberBand::setEndPosition(const QPointF& pos)
+void KItemListRubberBand::setEndPosition(const QPointF &pos)
{
if (m_endPos != pos) {
const QPointF previous = m_endPos;
{
return m_active;
}
-
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);
Q_SIGNALS:
void activationChanged(bool active);
- void startPositionChanged(const QPointF& current, const QPointF& previous);
- void endPositionChanged(const QPointF& current, const QPointF& previous);
+ void startPositionChanged(const QPointF ¤t, const QPointF &previous);
+ void endPositionChanged(const QPointF ¤t, const QPointF &previous);
private:
bool m_active;
};
#endif
-
-
#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)
{
}
}
}
-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)
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);
return iconSize;
}
-
#include <QGraphicsWidget>
#include <QPixmap>
-
/**
* @brief Allows to toggle between the selected and unselected state of an item.
*/
Q_OBJECT
public:
- explicit KItemListSelectionToggle(QGraphicsItem* parent);
+ explicit KItemListSelectionToggle(QGraphicsItem *parent);
~KItemListSelectionToggle() override;
void setChecked(bool checked);
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();
};
#endif
-
-
#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)
{
}
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;
}
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'.
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();
}
}
-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);
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) {
class DOLPHIN_EXPORT KItemListSizeHintResolver
{
public:
- explicit KItemListSizeHintResolver(const KItemListView* itemListView);
+ explicit KItemListSizeHintResolver(const KItemListView *itemListView);
virtual ~KItemListSizeHintResolver();
QSizeF minSizeHint();
QSizeF sizeHint(int index);
bool isElided(int index);
- void itemsInserted(const KItemRangeList& itemRanges);
- void itemsRemoved(const KItemRangeList& itemRanges);
- void itemsMoved(const KItemRange& range, const QList<int>& movedToIndexes);
- void itemsChanged(int index, int count, const QSet<QByteArray>& roles);
+ void itemsInserted(const KItemRangeList &itemRanges);
+ void itemsRemoved(const KItemRangeList &itemRanges);
+ void itemsMoved(const KItemRange &range, const QList<int> &movedToIndexes);
+ void itemsChanged(int index, int count, const QSet<QByteArray> &roles);
void clearCache();
void updateCache();
private:
- const KItemListView* m_itemListView;
+ const KItemListView *m_itemListView;
mutable QVector<std::pair<qreal /* height */, bool /* isElided */>> m_logicalHeightHintCache;
mutable qreal m_logicalWidthHint;
mutable qreal m_minHeightHint;
#include <QStyle>
#include <QWheelEvent>
-KItemListSmoothScroller::KItemListSmoothScroller(QScrollBar* scrollBar,
- QObject* parent) :
- QObject(parent),
- m_scrollBarPressed(false),
- m_smoothScrolling(true),
- m_scrollBar(scrollBar),
- m_animation(nullptr)
+KItemListSmoothScroller::KItemListSmoothScroller(QScrollBar *scrollBar, QObject *parent)
+ : QObject(parent)
+ , m_scrollBarPressed(false)
+ , m_smoothScrolling(true)
+ , m_scrollBar(scrollBar)
+ , m_animation(nullptr)
{
m_animation = new QPropertyAnimation(this);
const int animationDuration = m_scrollBar->style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, m_scrollBar);
const bool animationEnabled = (animationDuration > 0);
m_animation->setDuration(animationEnabled ? animationDuration : 1);
- connect(m_animation, &QPropertyAnimation::stateChanged,
- this, &KItemListSmoothScroller::slotAnimationStateChanged);
+ connect(m_animation, &QPropertyAnimation::stateChanged, this, &KItemListSmoothScroller::slotAnimationStateChanged);
m_scrollBar->installEventFilter(this);
}
m_scrollBar = scrollBar;
}
-QScrollBar* KItemListSmoothScroller::scrollBar() const
+QScrollBar *KItemListSmoothScroller::scrollBar() const
{
return m_scrollBar;
}
-void KItemListSmoothScroller::setTargetObject(QObject* target)
+void KItemListSmoothScroller::setTargetObject(QObject *target)
{
m_animation->setTargetObject(target);
}
-QObject* KItemListSmoothScroller::targetObject() const
+QObject *KItemListSmoothScroller::targetObject() const
{
return m_animation->targetObject();
}
-void KItemListSmoothScroller::setPropertyName(const QByteArray& propertyName)
+void KItemListSmoothScroller::setPropertyName(const QByteArray &propertyName)
{
m_animation->setPropertyName(propertyName);
}
void KItemListSmoothScroller::scrollContentsBy(qreal distance)
{
- QObject* target = targetObject();
+ QObject *target = targetObject();
if (!target) {
return;
}
return true;
}
-bool KItemListSmoothScroller::eventFilter(QObject* obj, QEvent* event)
+bool KItemListSmoothScroller::eventFilter(QObject *obj, QEvent *event)
{
Q_ASSERT(obj == m_scrollBar);
return QObject::eventFilter(obj, event);
}
-void KItemListSmoothScroller::slotAnimationStateChanged(QAbstractAnimation::State newState,
- QAbstractAnimation::State oldState)
+void KItemListSmoothScroller::slotAnimationStateChanged(QAbstractAnimation::State newState, QAbstractAnimation::State oldState)
{
Q_UNUSED(oldState)
if (newState == QAbstractAnimation::Stopped && m_smoothScrolling && !m_scrollBarPressed) {
}
}
-void KItemListSmoothScroller::handleWheelEvent(QWheelEvent* event)
+void KItemListSmoothScroller::handleWheelEvent(QWheelEvent *event)
{
const bool previous = m_smoothScrolling;
m_smoothScrolling = previous;
}
-
Q_OBJECT
public:
- explicit KItemListSmoothScroller(QScrollBar* scrollBar,
- QObject* parent = nullptr);
+ explicit KItemListSmoothScroller(QScrollBar *scrollBar, QObject *parent = nullptr);
~KItemListSmoothScroller() override;
- void setScrollBar(QScrollBar* scrollBar);
- QScrollBar* scrollBar() const;
+ void setScrollBar(QScrollBar *scrollBar);
+ QScrollBar *scrollBar() const;
- void setTargetObject(QObject* target);
- QObject* targetObject() const;
+ void setTargetObject(QObject *target);
+ QObject *targetObject() const;
- void setPropertyName(const QByteArray& propertyName);
+ void setPropertyName(const QByteArray &propertyName);
QByteArray propertyName() const;
/**
/**
* Forwards wheel events to the scrollbar, ensuring smooth and proper scrolling
*/
- void handleWheelEvent(QWheelEvent* event);
+ void handleWheelEvent(QWheelEvent *event);
Q_SIGNALS:
/**
* Emitted when the scrolling animation has finished
*/
void scrollingStopped();
+
protected:
- bool eventFilter(QObject* obj, QEvent* event) override;
+ bool eventFilter(QObject *obj, QEvent *event) override;
private Q_SLOTS:
- void slotAnimationStateChanged(QAbstractAnimation::State newState,
- QAbstractAnimation::State oldState);
+ void slotAnimationStateChanged(QAbstractAnimation::State newState, QAbstractAnimation::State oldState);
private:
bool m_scrollBarPressed;
bool m_smoothScrolling;
- QScrollBar* m_scrollBar;
- QPropertyAnimation* m_animation;
+ QScrollBar *m_scrollBar;
+ QPropertyAnimation *m_animation;
};
#endif
-
-
#include <QPropertyAnimation>
-KItemListViewAnimation::KItemListViewAnimation(QObject* parent) :
- QObject(parent),
- m_scrollOrientation(Qt::Vertical),
- m_scrollOffset(0),
- m_animation()
+KItemListViewAnimation::KItemListViewAnimation(QObject *parent)
+ : QObject(parent)
+ , m_scrollOrientation(Qt::Vertical)
+ , m_scrollOffset(0)
+ , m_animation()
{
}
continue;
}
- QHashIterator<QGraphicsWidget*, QPropertyAnimation*> it(m_animation[type]);
+ QHashIterator<QGraphicsWidget *, QPropertyAnimation *> it(m_animation[type]);
while (it.hasNext()) {
it.next();
- QGraphicsWidget* widget = it.key();
- QPropertyAnimation* propertyAnim = it.value();
+ QGraphicsWidget *widget = it.key();
+ QPropertyAnimation *propertyAnim = it.value();
QPointF currentPos = widget->pos();
if (m_scrollOrientation == Qt::Vertical) {
if (type == MovingAnimation) {
// Stop the animation, calculate the moved start- and end-value
// and restart the animation for the remaining duration.
- const int remainingDuration = propertyAnim->duration()
- - propertyAnim->currentTime();
+ const int remainingDuration = propertyAnim->duration() - propertyAnim->currentTime();
const bool block = propertyAnim->signalsBlocked();
propertyAnim->blockSignals(true);
return m_scrollOffset;
}
-void KItemListViewAnimation::start(QGraphicsWidget* widget, AnimationType type, const QVariant& endValue)
+void KItemListViewAnimation::start(QGraphicsWidget *widget, AnimationType type, const QVariant &endValue)
{
stop(widget, type);
- QPropertyAnimation* propertyAnim = nullptr;
+ QPropertyAnimation *propertyAnim = nullptr;
const int animationDuration = widget->style()->styleHint(QStyle::SH_Widget_Animate) ? 200 : 1;
switch (type) {
propertyAnim->start();
}
-void KItemListViewAnimation::stop(QGraphicsWidget* widget, AnimationType type)
+void KItemListViewAnimation::stop(QGraphicsWidget *widget, AnimationType type)
{
- QPropertyAnimation* propertyAnim = m_animation[type].value(widget);
+ QPropertyAnimation *propertyAnim = m_animation[type].value(widget);
if (propertyAnim) {
propertyAnim->stop();
switch (type) {
- case MovingAnimation: break;
- case CreateAnimation: widget->setOpacity(1.0); break;
- case DeleteAnimation: widget->setOpacity(0.0); break;
- case ResizeAnimation: break;
- default: break;
+ case MovingAnimation:
+ break;
+ case CreateAnimation:
+ widget->setOpacity(1.0);
+ break;
+ case DeleteAnimation:
+ widget->setOpacity(0.0);
+ break;
+ case ResizeAnimation:
+ break;
+ default:
+ break;
}
m_animation[type].remove(widget);
}
}
-void KItemListViewAnimation::stop(QGraphicsWidget* widget)
+void KItemListViewAnimation::stop(QGraphicsWidget *widget)
{
for (int type = 0; type < AnimationTypeCount; ++type) {
stop(widget, static_cast<AnimationType>(type));
return m_animation[type].value(widget);
}
-bool KItemListViewAnimation::isStarted(QGraphicsWidget* widget) const
+bool KItemListViewAnimation::isStarted(QGraphicsWidget *widget) const
{
for (int type = 0; type < AnimationTypeCount; ++type) {
if (isStarted(widget, static_cast<AnimationType>(type))) {
void KItemListViewAnimation::slotFinished()
{
- QPropertyAnimation* finishedAnim = qobject_cast<QPropertyAnimation*>(sender());
+ QPropertyAnimation *finishedAnim = qobject_cast<QPropertyAnimation *>(sender());
for (int type = 0; type < AnimationTypeCount; ++type) {
- QMutableHashIterator<QGraphicsWidget*, QPropertyAnimation*> it(m_animation[type]);
+ QMutableHashIterator<QGraphicsWidget *, QPropertyAnimation *> it(m_animation[type]);
while (it.hasNext()) {
it.next();
- QPropertyAnimation* propertyAnim = it.value();
+ QPropertyAnimation *propertyAnim = it.value();
if (propertyAnim == finishedAnim) {
- QGraphicsWidget* widget = it.key();
+ QGraphicsWidget *widget = it.key();
it.remove();
finishedAnim->deleteLater();
}
Q_ASSERT(false);
}
-
Q_OBJECT
public:
- enum AnimationType {
- MovingAnimation,
- CreateAnimation,
- DeleteAnimation,
- ResizeAnimation,
- IconResizeAnimation,
- AnimationTypeCount
- };
-
- explicit KItemListViewAnimation(QObject* parent = nullptr);
+ enum AnimationType { MovingAnimation, CreateAnimation, DeleteAnimation, ResizeAnimation, IconResizeAnimation, AnimationTypeCount };
+
+ explicit KItemListViewAnimation(QObject *parent = nullptr);
~KItemListViewAnimation() override;
void setScrollOrientation(Qt::Orientation orientation);
* of the type is already running, this animation will be stopped before starting
* the new animation.
*/
- void start(QGraphicsWidget* widget, AnimationType type, const QVariant& endValue = QVariant());
+ void start(QGraphicsWidget *widget, AnimationType type, const QVariant &endValue = QVariant());
/**
* Stops the animation of the type \a type for the widget \a widget.
*/
- void stop(QGraphicsWidget* widget, AnimationType type);
+ void stop(QGraphicsWidget *widget, AnimationType type);
/**
* Stops all animations that have been applied to the widget \a widget.
*/
- void stop(QGraphicsWidget* widget);
+ void stop(QGraphicsWidget *widget);
/**
* @return True if the animation of the type \a type has been started
/**
* @return True if any animation has been started for the widget.
*/
- bool isStarted(QGraphicsWidget* widget) const;
+ bool isStarted(QGraphicsWidget *widget) const;
Q_SIGNALS:
- void finished(QGraphicsWidget* widget, KItemListViewAnimation::AnimationType type);
+ void finished(QGraphicsWidget *widget, KItemListViewAnimation::AnimationType type);
private Q_SLOTS:
void slotFinished();
private:
Qt::Orientation m_scrollOrientation;
qreal m_scrollOffset;
- QHash<QGraphicsWidget*, QPropertyAnimation*> m_animation[AnimationTypeCount];
+ QHash<QGraphicsWidget *, QPropertyAnimation *> m_animation[AnimationTypeCount];
};
#endif
-
-
// #define KITEMLISTVIEWLAYOUTER_DEBUG
-KItemListViewLayouter::KItemListViewLayouter(KItemListSizeHintResolver* sizeHintResolver, QObject* parent) :
- QObject(parent),
- m_dirty(true),
- m_visibleIndexesDirty(true),
- m_scrollOrientation(Qt::Vertical),
- m_size(),
- m_itemSize(128, 128),
- m_itemMargin(),
- m_headerHeight(0),
- m_model(nullptr),
- m_sizeHintResolver(sizeHintResolver),
- m_scrollOffset(0),
- m_maximumScrollOffset(0),
- m_itemOffset(0),
- m_maximumItemOffset(0),
- m_firstVisibleIndex(-1),
- m_lastVisibleIndex(-1),
- m_columnWidth(0),
- m_xPosInc(0),
- m_columnCount(0),
- m_rowOffsets(),
- m_columnOffsets(),
- m_groupItemIndexes(),
- m_groupHeaderHeight(0),
- m_groupHeaderMargin(0),
- m_itemInfos()
+KItemListViewLayouter::KItemListViewLayouter(KItemListSizeHintResolver *sizeHintResolver, QObject *parent)
+ : QObject(parent)
+ , m_dirty(true)
+ , m_visibleIndexesDirty(true)
+ , m_scrollOrientation(Qt::Vertical)
+ , m_size()
+ , m_itemSize(128, 128)
+ , m_itemMargin()
+ , m_headerHeight(0)
+ , m_model(nullptr)
+ , m_sizeHintResolver(sizeHintResolver)
+ , m_scrollOffset(0)
+ , m_maximumScrollOffset(0)
+ , m_itemOffset(0)
+ , m_maximumItemOffset(0)
+ , m_firstVisibleIndex(-1)
+ , m_lastVisibleIndex(-1)
+ , m_columnWidth(0)
+ , m_xPosInc(0)
+ , m_columnCount(0)
+ , m_rowOffsets()
+ , m_columnOffsets()
+ , m_groupItemIndexes()
+ , m_groupHeaderHeight(0)
+ , m_groupHeaderMargin(0)
+ , m_itemInfos()
{
Q_ASSERT(m_sizeHintResolver);
}
return m_scrollOrientation;
}
-void KItemListViewLayouter::setSize(const QSizeF& size)
+void KItemListViewLayouter::setSize(const QSizeF &size)
{
if (m_size != size) {
if (m_scrollOrientation == Qt::Vertical) {
return m_size;
}
-void KItemListViewLayouter::setItemSize(const QSizeF& size)
+void KItemListViewLayouter::setItemSize(const QSizeF &size)
{
if (m_itemSize != size) {
m_itemSize = size;
return m_itemSize;
}
-void KItemListViewLayouter::setItemMargin(const QSizeF& margin)
+void KItemListViewLayouter::setItemMargin(const QSizeF &margin)
{
if (m_itemMargin != margin) {
m_itemMargin = margin;
qreal KItemListViewLayouter::maximumScrollOffset() const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
return m_maximumScrollOffset;
}
qreal KItemListViewLayouter::maximumItemOffset() const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
return m_maximumItemOffset;
}
-void KItemListViewLayouter::setModel(const KItemModelBase* model)
+void KItemListViewLayouter::setModel(const KItemModelBase *model)
{
if (m_model != model) {
m_model = model;
}
}
-const KItemModelBase* KItemListViewLayouter::model() const
+const KItemModelBase *KItemListViewLayouter::model() const
{
return m_model;
}
int KItemListViewLayouter::firstVisibleIndex() const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
return m_firstVisibleIndex;
}
int KItemListViewLayouter::lastVisibleIndex() const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
return m_lastVisibleIndex;
}
QRectF KItemListViewLayouter::itemRect(int index) const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
if (index < 0 || index >= m_itemInfos.count()) {
return QRectF();
}
QRectF KItemListViewLayouter::groupHeaderRect(int index) const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
const QRectF firstItemRect = itemRect(index);
QPointF pos = firstItemRect.topLeft();
break;
}
- const qreal itemWidth = (m_scrollOrientation == Qt::Vertical)
- ? m_sizeHintResolver->sizeHint(index).width()
- : m_sizeHintResolver->sizeHint(index).height();
+ const qreal itemWidth =
+ (m_scrollOrientation == Qt::Vertical) ? m_sizeHintResolver->sizeHint(index).width() : m_sizeHintResolver->sizeHint(index).height();
if (itemWidth > headerWidth) {
headerWidth = itemWidth;
int KItemListViewLayouter::itemColumn(int index) const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
if (index < 0 || index >= m_itemInfos.count()) {
return -1;
}
- return (m_scrollOrientation == Qt::Vertical)
- ? m_itemInfos[index].column
- : m_itemInfos[index].row;
+ return (m_scrollOrientation == Qt::Vertical) ? m_itemInfos[index].column : m_itemInfos[index].row;
}
int KItemListViewLayouter::itemRow(int index) const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
if (index < 0 || index >= m_itemInfos.count()) {
return -1;
}
- return (m_scrollOrientation == Qt::Vertical)
- ? m_itemInfos[index].row
- : m_itemInfos[index].column;
+ return (m_scrollOrientation == Qt::Vertical) ? m_itemInfos[index].row : m_itemInfos[index].column;
}
int KItemListViewLayouter::maximumVisibleItems() const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
const int height = static_cast<int>(m_size.height());
const int rowHeight = static_cast<int>(m_itemSize.height());
bool KItemListViewLayouter::isFirstGroupItem(int itemIndex) const
{
- const_cast<KItemListViewLayouter*>(this)->doLayout();
+ const_cast<KItemListViewLayouter *>(this)->doLayout();
return m_groupItemIndexes.contains(itemIndex);
}
m_dirty = true;
}
-
#ifndef QT_NO_DEBUG
- bool KItemListViewLayouter::isDirty()
- {
- return m_dirty;
- }
+bool KItemListViewLayouter::isDirty()
+{
+ return m_dirty;
+}
#endif
void KItemListViewLayouter::doLayout()
{
// we always want to update visible indexes after performing a layout
- auto qsg = qScopeGuard([this] { updateVisibleIndexes(); });
+ auto qsg = qScopeGuard([this] {
+ updateVisibleIndexes();
+ });
if (!m_dirty) {
return;
currentOffset += m_groupHeaderHeight;
}
- if (QGuiApplication::isLeftToRight()) for (int column = 0; column < m_columnCount; ++column) {
- m_columnOffsets[column] = currentOffset;
- currentOffset += m_columnWidth;
- }
- else for (int column = 0; column < m_columnCount; ++column) {
- m_columnOffsets[column] = currentOffset - m_columnWidth;
- currentOffset -= m_columnWidth;
- }
+ if (QGuiApplication::isLeftToRight())
+ for (int column = 0; column < m_columnCount; ++column) {
+ m_columnOffsets[column] = currentOffset;
+ currentOffset += m_columnWidth;
+ }
+ else
+ for (int column = 0; column < m_columnCount; ++column) {
+ m_columnOffsets[column] = currentOffset - m_columnWidth;
+ currentOffset -= m_columnWidth;
+ }
// Prepare the QVector which stores the y-coordinate for each new row.
int numberOfRows = (itemCount + m_columnCount - 1) / m_columnCount;
requiredItemHeight = sizeHintHeight;
}
- ItemInfo& itemInfo = m_itemInfos[index];
+ ItemInfo &itemInfo = m_itemInfos[index];
itemInfo.column = column;
itemInfo.row = row;
m_groupItemIndexes.clear();
- const QList<QPair<int, QVariant> > groups = m_model->groups();
+ const QList<QPair<int, QVariant>> groups = m_model->groups();
if (groups.isEmpty()) {
return false;
}
{
return 100;
}
-
Q_OBJECT
public:
- explicit KItemListViewLayouter(KItemListSizeHintResolver* sizeHintResolver, QObject* parent = nullptr);
+ explicit KItemListViewLayouter(KItemListSizeHintResolver *sizeHintResolver, QObject *parent = nullptr);
~KItemListViewLayouter() override;
void setScrollOrientation(Qt::Orientation orientation);
Qt::Orientation scrollOrientation() const;
- void setSize(const QSizeF& size);
+ void setSize(const QSizeF &size);
QSizeF size() const;
- void setItemSize(const QSizeF& size);
+ void setItemSize(const QSizeF &size);
QSizeF itemSize() const;
/**
* Margin between the rows and columns of items.
*/
- void setItemMargin(const QSizeF& margin);
+ void setItemMargin(const QSizeF &margin);
QSizeF itemMargin() const;
/**
qreal maximumItemOffset() const;
- void setModel(const KItemModelBase* model);
- const KItemModelBase* model() const;
+ void setModel(const KItemModelBase *model);
+ const KItemModelBase *model() const;
/**
* @return The first (at least partly) visible index. -1 is returned
QSizeF m_itemSize;
QSizeF m_itemMargin;
qreal m_headerHeight;
- const KItemModelBase* m_model;
- KItemListSizeHintResolver* m_sizeHintResolver;
+ const KItemModelBase *m_model;
+ KItemListSizeHintResolver *m_sizeHintResolver;
qreal m_scrollOffset;
qreal m_maximumScrollOffset;
};
#endif
-
-
#include <QImage>
#include <QPainter>
-static const quint32 stackBlur8Mul[255] =
-{
- 512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
- 454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
- 482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
- 437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
- 497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
- 320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
- 446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
- 329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
- 505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
- 399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
- 324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
- 268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
- 451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
- 385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
- 332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
- 289,287,285,282,280,278,275,273,271,269,267,265,263,261,259
-};
-
-static const quint32 stackBlur8Shr[255] =
-{
- 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
- 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
- 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
- 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
- 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
- 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
- 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
- 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
- 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
- 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
- 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
- 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
- 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
- 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
- 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
- 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24
-};
-
-static void blurHorizontal(QImage& image, unsigned int* stack, int div, int radius)
+static const quint32 stackBlur8Mul[255] = {
+ 512, 512, 456, 512, 328, 456, 335, 512, 405, 328, 271, 456, 388, 335, 292, 512, 454, 405, 364, 328, 298, 271, 496, 456, 420, 388, 360, 335, 312,
+ 292, 273, 512, 482, 454, 428, 405, 383, 364, 345, 328, 312, 298, 284, 271, 259, 496, 475, 456, 437, 420, 404, 388, 374, 360, 347, 335, 323, 312,
+ 302, 292, 282, 273, 265, 512, 497, 482, 468, 454, 441, 428, 417, 405, 394, 383, 373, 364, 354, 345, 337, 328, 320, 312, 305, 298, 291, 284, 278,
+ 271, 265, 259, 507, 496, 485, 475, 465, 456, 446, 437, 428, 420, 412, 404, 396, 388, 381, 374, 367, 360, 354, 347, 341, 335, 329, 323, 318, 312,
+ 307, 302, 297, 292, 287, 282, 278, 273, 269, 265, 261, 512, 505, 497, 489, 482, 475, 468, 461, 454, 447, 441, 435, 428, 422, 417, 411, 405, 399,
+ 394, 389, 383, 378, 373, 368, 364, 359, 354, 350, 345, 341, 337, 332, 328, 324, 320, 316, 312, 309, 305, 301, 298, 294, 291, 287, 284, 281, 278,
+ 274, 271, 268, 265, 262, 259, 257, 507, 501, 496, 491, 485, 480, 475, 470, 465, 460, 456, 451, 446, 442, 437, 433, 428, 424, 420, 416, 412, 408,
+ 404, 400, 396, 392, 388, 385, 381, 377, 374, 370, 367, 363, 360, 357, 354, 350, 347, 344, 341, 338, 335, 332, 329, 326, 323, 320, 318, 315, 312,
+ 310, 307, 304, 302, 299, 297, 294, 292, 289, 287, 285, 282, 280, 278, 275, 273, 271, 269, 267, 265, 263, 261, 259};
+
+static const quint32 stackBlur8Shr[255] = {
+ 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+ 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+ 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24};
+
+static void blurHorizontal(QImage &image, unsigned int *stack, int div, int radius)
{
int stackindex;
int stackstart;
- quint32 * const pixels = reinterpret_cast<quint32 *>(image.bits());
+ quint32 *const pixels = reinterpret_cast<quint32 *>(image.bits());
quint32 pixel;
int w = image.width();
unsigned int sum, sumIn, sumOut;
for (int y = 0; y < h; y++) {
- sum = 0;
- sumIn = 0;
+ sum = 0;
+ sumIn = 0;
sumOut = 0;
const int yw = y * w;
for (int i = 1; i <= radius; i++) {
pixel = pixels[yw + qMin(i, wm)];
- unsigned int* stackpix = &stack[i + radius];
+ unsigned int *stackpix = &stack[i + radius];
*stackpix = qAlpha(pixel);
- sum += *stackpix * (radius + 1 - i);
+ sum += *stackpix * (radius + 1 - i);
sumIn += *stackpix;
}
stackstart -= div;
}
- unsigned int* stackpix = &stack[stackstart];
+ unsigned int *stackpix = &stack[stackstart];
sumOut -= *stackpix;
*stackpix = qAlpha(pixel);
sumIn += *stackpix;
- sum += sumIn;
+ sum += sumIn;
if (++stackindex >= div) {
stackindex = 0;
stackpix = &stack[stackindex];
sumOut += *stackpix;
- sumIn -= *stackpix;
+ sumIn -= *stackpix;
}
}
}
-static void blurVertical(QImage& image, unsigned int* stack, int div, int radius)
+static void blurVertical(QImage &image, unsigned int *stack, int div, int radius)
{
int stackindex;
int stackstart;
- quint32 * const pixels = reinterpret_cast<quint32 *>(image.bits());
+ quint32 *const pixels = reinterpret_cast<quint32 *>(image.bits());
quint32 pixel;
int w = image.width();
unsigned int sum, sumIn, sumOut;
for (int x = 0; x < w; x++) {
- sum = 0;
- sumIn = 0;
+ sum = 0;
+ sumIn = 0;
sumOut = 0;
pixel = pixels[x];
for (int i = 1; i <= radius; i++) {
pixel = pixels[qMin(i, hm) * w + x];
- unsigned int* stackpix = &stack[i + radius];
+ unsigned int *stackpix = &stack[i + radius];
*stackpix = qAlpha(pixel);
- sum += *stackpix * (radius + 1 - i);
+ sum += *stackpix * (radius + 1 - i);
sumIn += *stackpix;
}
if (stackstart >= div)
stackstart -= div;
- unsigned int* stackpix = &stack[stackstart];
+ unsigned int *stackpix = &stack[stackstart];
sumOut -= *stackpix;
*stackpix = qAlpha(pixel);
sumIn += *stackpix;
- sum += sumIn;
+ sum += sumIn;
if (++stackindex >= div) {
stackindex = 0;
stackpix = &stack[stackindex];
sumOut += *stackpix;
- sumIn -= *stackpix;
+ sumIn -= *stackpix;
}
}
}
-static void stackBlur(QImage& image, float radius)
+static void stackBlur(QImage &image, float radius)
{
radius = qRound(radius);
int div = int(radius * 2) + 1;
- unsigned int* stack = new unsigned int[div];
+ unsigned int *stack = new unsigned int[div];
blurHorizontal(image, stack, div, radius);
blurVertical(image, stack, div, radius);
- delete [] stack;
+ delete[] stack;
}
-static void shadowBlur(QImage& image, float radius, const QColor& color)
+static void shadowBlur(QImage &image, float radius, const QColor &color)
{
if (radius < 0) {
return;
p.fillRect(image.rect(), color);
}
-namespace {
- /** Helper class for drawing frames for KPixmapModifier::applyFrame(). */
- class TileSet
- {
- public:
- enum { LeftMargin = 3, TopMargin = 2, RightMargin = 3, BottomMargin = 4 };
-
- enum Tile { TopLeftCorner = 0, TopSide, TopRightCorner, LeftSide,
- RightSide, BottomLeftCorner, BottomSide, BottomRightCorner,
- NumTiles };
-
- TileSet()
- {
- QImage image(8 * 3, 8 * 3, QImage::Format_ARGB32_Premultiplied);
-
- QPainter p(&image);
- p.setCompositionMode(QPainter::CompositionMode_Source);
- p.fillRect(image.rect(), Qt::transparent);
- p.fillRect(image.rect().adjusted(3, 3, -3, -3), Qt::black);
- p.end();
-
- shadowBlur(image, 3, Qt::black);
-
- QPixmap pixmap = QPixmap::fromImage(image);
- m_tiles[TopLeftCorner] = pixmap.copy(0, 0, 8, 8);
- m_tiles[TopSide] = pixmap.copy(8, 0, 8, 8);
- m_tiles[TopRightCorner] = pixmap.copy(16, 0, 8, 8);
- m_tiles[LeftSide] = pixmap.copy(0, 8, 8, 8);
- m_tiles[RightSide] = pixmap.copy(16, 8, 8, 8);
- m_tiles[BottomLeftCorner] = pixmap.copy(0, 16, 8, 8);
- m_tiles[BottomSide] = pixmap.copy(8, 16, 8, 8);
- m_tiles[BottomRightCorner] = pixmap.copy(16, 16, 8, 8);
- }
+namespace
+{
+/** Helper class for drawing frames for KPixmapModifier::applyFrame(). */
+class TileSet
+{
+public:
+ enum { LeftMargin = 3, TopMargin = 2, RightMargin = 3, BottomMargin = 4 };
- void paint(QPainter* p, const QRect& r)
- {
- p->drawPixmap(r.topLeft(), m_tiles[TopLeftCorner]);
- if (r.width() - 16 > 0) {
- p->drawTiledPixmap(r.x() + 8, r.y(), r.width() - 16, 8, m_tiles[TopSide]);
- }
- p->drawPixmap(r.right() - 8 + 1, r.y(), m_tiles[TopRightCorner]);
- if (r.height() - 16 > 0) {
- p->drawTiledPixmap(r.x(), r.y() + 8, 8, r.height() - 16, m_tiles[LeftSide]);
- p->drawTiledPixmap(r.right() - 8 + 1, r.y() + 8, 8, r.height() - 16, m_tiles[RightSide]);
- }
- p->drawPixmap(r.x(), r.bottom() - 8 + 1, m_tiles[BottomLeftCorner]);
- if (r.width() - 16 > 0) {
- p->drawTiledPixmap(r.x() + 8, r.bottom() - 8 + 1, r.width() - 16, 8, m_tiles[BottomSide]);
- }
- p->drawPixmap(r.right() - 8 + 1, r.bottom() - 8 + 1, m_tiles[BottomRightCorner]);
+ enum Tile { TopLeftCorner = 0, TopSide, TopRightCorner, LeftSide, RightSide, BottomLeftCorner, BottomSide, BottomRightCorner, NumTiles };
+
+ TileSet()
+ {
+ QImage image(8 * 3, 8 * 3, QImage::Format_ARGB32_Premultiplied);
+
+ QPainter p(&image);
+ p.setCompositionMode(QPainter::CompositionMode_Source);
+ p.fillRect(image.rect(), Qt::transparent);
+ p.fillRect(image.rect().adjusted(3, 3, -3, -3), Qt::black);
+ p.end();
+
+ shadowBlur(image, 3, Qt::black);
+
+ QPixmap pixmap = QPixmap::fromImage(image);
+ m_tiles[TopLeftCorner] = pixmap.copy(0, 0, 8, 8);
+ m_tiles[TopSide] = pixmap.copy(8, 0, 8, 8);
+ m_tiles[TopRightCorner] = pixmap.copy(16, 0, 8, 8);
+ m_tiles[LeftSide] = pixmap.copy(0, 8, 8, 8);
+ m_tiles[RightSide] = pixmap.copy(16, 8, 8, 8);
+ m_tiles[BottomLeftCorner] = pixmap.copy(0, 16, 8, 8);
+ m_tiles[BottomSide] = pixmap.copy(8, 16, 8, 8);
+ m_tiles[BottomRightCorner] = pixmap.copy(16, 16, 8, 8);
+ }
- const QRect contentRect = r.adjusted(LeftMargin + 1, TopMargin + 1,
- -(RightMargin + 1), -(BottomMargin + 1));
- p->fillRect(contentRect, Qt::transparent);
+ void paint(QPainter *p, const QRect &r)
+ {
+ p->drawPixmap(r.topLeft(), m_tiles[TopLeftCorner]);
+ if (r.width() - 16 > 0) {
+ p->drawTiledPixmap(r.x() + 8, r.y(), r.width() - 16, 8, m_tiles[TopSide]);
+ }
+ p->drawPixmap(r.right() - 8 + 1, r.y(), m_tiles[TopRightCorner]);
+ if (r.height() - 16 > 0) {
+ p->drawTiledPixmap(r.x(), r.y() + 8, 8, r.height() - 16, m_tiles[LeftSide]);
+ p->drawTiledPixmap(r.right() - 8 + 1, r.y() + 8, 8, r.height() - 16, m_tiles[RightSide]);
}
+ p->drawPixmap(r.x(), r.bottom() - 8 + 1, m_tiles[BottomLeftCorner]);
+ if (r.width() - 16 > 0) {
+ p->drawTiledPixmap(r.x() + 8, r.bottom() - 8 + 1, r.width() - 16, 8, m_tiles[BottomSide]);
+ }
+ p->drawPixmap(r.right() - 8 + 1, r.bottom() - 8 + 1, m_tiles[BottomRightCorner]);
+
+ const QRect contentRect = r.adjusted(LeftMargin + 1, TopMargin + 1, -(RightMargin + 1), -(BottomMargin + 1));
+ p->fillRect(contentRect, Qt::transparent);
+ }
- QPixmap m_tiles[NumTiles];
- };
+ QPixmap m_tiles[NumTiles];
+};
}
-void KPixmapModifier::scale(QPixmap& pixmap, const QSize& scaledSize)
+void KPixmapModifier::scale(QPixmap &pixmap, const QSize &scaledSize)
{
if (scaledSize.isEmpty() || pixmap.isNull()) {
pixmap = QPixmap();
pixmap.setDevicePixelRatio(dpr);
}
-void KPixmapModifier::applyFrame(QPixmap& icon, const QSize& scaledSize)
+void KPixmapModifier::applyFrame(QPixmap &icon, const QSize &scaledSize)
{
if (icon.isNull()) {
icon = QPixmap(scaledSize);
qreal dpr = qApp->devicePixelRatio();
// Resize the icon to the maximum size minus the space required for the frame
- const QSize size(scaledSize.width() - TileSet::LeftMargin - TileSet::RightMargin,
- scaledSize.height() - TileSet::TopMargin - TileSet::BottomMargin);
+ const QSize size(scaledSize.width() - TileSet::LeftMargin - TileSet::RightMargin, scaledSize.height() - TileSet::TopMargin - TileSet::BottomMargin);
scale(icon, size * dpr);
icon.setDevicePixelRatio(dpr);
QPainter painter;
painter.begin(&framedIcon);
painter.setCompositionMode(QPainter::CompositionMode_Source);
- tileSet.paint(&painter, QRect(QPoint(0,0), framedIcon.size() / dpr));
+ tileSet.paint(&painter, QRect(QPoint(0, 0), framedIcon.size() / dpr));
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.drawPixmap(TileSet::LeftMargin, TileSet::TopMargin, icon);
icon = framedIcon;
}
-QSize KPixmapModifier::sizeInsideFrame(const QSize& frameSize)
+QSize KPixmapModifier::sizeInsideFrame(const QSize &frameSize)
{
- return QSize(frameSize.width() - TileSet::LeftMargin - TileSet::RightMargin,
- frameSize.height() - TileSet::TopMargin - TileSet::BottomMargin);
+ return QSize(frameSize.width() - TileSet::LeftMargin - TileSet::RightMargin, frameSize.height() - TileSet::TopMargin - TileSet::BottomMargin);
}
-
* @arg scaledSize is assumed to be the scaled to the same device pixel ratio as the source pixmap
* @arg scaledSize is in device pixels
*/
- static void scale(QPixmap& pixmap, const QSize& scaledSize);
+ static void scale(QPixmap &pixmap, const QSize &scaledSize);
/**
* Resize and paint a frame round an icon
* @arg scaledSize is in device-independent pixels
* The returned image will be scaled by the application devicePixelRatio
*/
- static void applyFrame(QPixmap& icon, const QSize& scaledSize);
+ static void applyFrame(QPixmap &icon, const QSize &scaledSize);
/**
* return and paint a frame round an icon
* @return is in device-independent pixels
*/
- static QSize sizeInsideFrame(const QSize& frameSize);
+ static QSize sizeInsideFrame(const QSize &frameSize);
};
#endif
-
-
* SPDX-License-Identifier: GPL-2.0-or-later
*/
+#include "config-dolphin.h"
#include "dbusinterface.h"
#include "dolphin_generalsettings.h"
#include "dolphin_version.h"
#include "dolphindebug.h"
#include "dolphinmainwindow.h"
#include "global.h"
-#include "config-dolphin.h"
#if HAVE_KUSERFEEDBACK
#include "userfeedback/dolphinfeedbackprovider.h"
#endif
#include <KAboutData>
+#include <KConfigGui>
#include <KCrash>
#include <KDBusService>
-#include <KLocalizedString>
-#include <KConfigGui>
#include <KIO/PreviewJob>
+#include <KLocalizedString>
#include <KWindowSystem>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
// Prohibit using sudo or kdesu (but allow using the root user directly)
if (getuid() == 0) {
if (!qEnvironmentVariableIsEmpty("SUDO_USER")) {
- std::cout << "Running Dolphin with sudo can cause bugs and expose you to security vulnerabilities."
- << std::endl;
+ std::cout << "Running Dolphin with sudo can cause bugs and expose you to security vulnerabilities." << std::endl;
return EXIT_FAILURE;
} else if (!qEnvironmentVariableIsEmpty("KDESU_USER")) {
- std::cout << "Running Dolphin with kdesu can cause bugs and expose you to security vulnerabilities."
- << std::endl;
+ std::cout << "Running Dolphin with kdesu can cause bugs and expose you to security vulnerabilities." << std::endl;
return EXIT_FAILURE;
}
}
KLocalizedString::setApplicationDomain("dolphin");
- KAboutData aboutData(QStringLiteral("dolphin"), i18n("Dolphin"), QStringLiteral(DOLPHIN_VERSION_STRING),
+ KAboutData aboutData(QStringLiteral("dolphin"),
+ i18n("Dolphin"),
+ QStringLiteral(DOLPHIN_VERSION_STRING),
i18nc("@title", "File Manager"),
KAboutLicense::GPL,
i18nc("@info:credit", "(C) 2006-2022 The Dolphin Developers"));
aboutData.addAuthor(i18nc("@info:credit", "Peter Penz"),
i18nc("@info:credit", "Maintainer and developer (2006-2012)"),
QStringLiteral("peter.penz19@gmail.com"));
- aboutData.addAuthor(i18nc("@info:credit", "Sebastian Trüg"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("trueg@kde.org"));
- aboutData.addAuthor(i18nc("@info:credit", "David Faure"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("faure@kde.org"));
- aboutData.addAuthor(i18nc("@info:credit", "Aaron J. Seigo"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("aseigo@kde.org"));
- aboutData.addAuthor(i18nc("@info:credit", "Rafael Fernández López"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("ereslibre@kde.org"));
- aboutData.addAuthor(i18nc("@info:credit", "Kevin Ottens"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("ervin@kde.org"));
- aboutData.addAuthor(i18nc("@info:credit", "Holger Freyther"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("freyther@gmx.net"));
- aboutData.addAuthor(i18nc("@info:credit", "Max Blazejak"),
- i18nc("@info:credit", "Developer"),
- QStringLiteral("m43ksrocks@gmail.com"));
- aboutData.addAuthor(i18nc("@info:credit", "Michael Austin"),
- i18nc("@info:credit", "Documentation"),
- QStringLiteral("tuxedup@users.sourceforge.net"));
+ aboutData.addAuthor(i18nc("@info:credit", "Sebastian Trüg"), i18nc("@info:credit", "Developer"), QStringLiteral("trueg@kde.org"));
+ aboutData.addAuthor(i18nc("@info:credit", "David Faure"), i18nc("@info:credit", "Developer"), QStringLiteral("faure@kde.org"));
+ aboutData.addAuthor(i18nc("@info:credit", "Aaron J. Seigo"), i18nc("@info:credit", "Developer"), QStringLiteral("aseigo@kde.org"));
+ aboutData.addAuthor(i18nc("@info:credit", "Rafael Fernández López"), i18nc("@info:credit", "Developer"), QStringLiteral("ereslibre@kde.org"));
+ aboutData.addAuthor(i18nc("@info:credit", "Kevin Ottens"), i18nc("@info:credit", "Developer"), QStringLiteral("ervin@kde.org"));
+ aboutData.addAuthor(i18nc("@info:credit", "Holger Freyther"), i18nc("@info:credit", "Developer"), QStringLiteral("freyther@gmx.net"));
+ aboutData.addAuthor(i18nc("@info:credit", "Max Blazejak"), i18nc("@info:credit", "Developer"), QStringLiteral("m43ksrocks@gmail.com"));
+ aboutData.addAuthor(i18nc("@info:credit", "Michael Austin"), i18nc("@info:credit", "Documentation"), QStringLiteral("tuxedup@users.sourceforge.net"));
KAboutData::setApplicationData(aboutData);
aboutData.setupCommandLine(&parser);
// command line options
- parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("select"), i18nc("@info:shell", "The files and folders passed as arguments "
- "will be selected.")));
+ parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("select"),
+ i18nc("@info:shell",
+ "The files and folders passed as arguments "
+ "will be selected.")));
parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("split"), i18nc("@info:shell", "Dolphin will get started with a split view.")));
parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("new-window"), i18nc("@info:shell", "Dolphin will explicitly open in a new window.")));
- parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("daemon"), i18nc("@info:shell", "Start Dolphin Daemon (only required for DBus Interface).")));
+ parser.addOption(
+ QCommandLineOption(QStringList() << QStringLiteral("daemon"), i18nc("@info:shell", "Start Dolphin Daemon (only required for DBus Interface).")));
parser.addPositionalArgument(QStringLiteral("+[Url]"), i18nc("@info:shell", "Document to open"));
parser.process(app);
// We later mutate urls, so we need to store if it was empty originally
const bool startedWithURLs = !urls.isEmpty();
-
if (parser.isSet(QStringLiteral("daemon"))) {
// Disable session management for the daemonized version
// See https://bugs.kde.org/show_bug.cgi?id=417219
}
if (!parser.isSet(QStringLiteral("new-window"))) {
-
QString token;
if (KWindowSystem::isPlatformWayland()) {
token = qEnvironmentVariable("XDG_ACTIVATION_TOKEN");
urls.append(urls.last());
}
- DolphinMainWindow* mainWindow = new DolphinMainWindow();
+ DolphinMainWindow *mainWindow = new DolphinMainWindow();
if (openFiles) {
mainWindow->openFiles(urls, splitView);
// 2. The "remember state" setting is enabled or session restoration after
// reboot is in use
// 3. There is a session available to restore
- if (!parser.isSet(QStringLiteral("new-window"))
- && (app.isSessionRestored() || GeneralSettings::rememberOpenedTabs())
- ) {
+ if (!parser.isSet(QStringLiteral("new-window")) && (app.isSessionRestored() || GeneralSettings::rememberOpenedTabs())) {
// Get saved state data for the last-closed Dolphin instance
const QString serviceName = QStringLiteral("org.kde.dolphin-%1").arg(QCoreApplication::applicationPid());
if (Dolphin::dolphinGuiInstances(serviceName).size() > 0) {
#include <QMouseEvent>
#include <QToolBar>
-MiddleClickActionEventFilter::MiddleClickActionEventFilter(QObject *parent) : QObject(parent)
+MiddleClickActionEventFilter::MiddleClickActionEventFilter(QObject *parent)
+ : QObject(parent)
{
-
}
MiddleClickActionEventFilter::~MiddleClickActionEventFilter() = default;
bool MiddleClickActionEventFilter::eventFilter(QObject *watched, QEvent *event)
{
- if (event->type() == QEvent::MouseButtonPress
- || event->type() == QEvent::MouseButtonRelease) {
+ if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) {
QMouseEvent *me = static_cast<QMouseEvent *>(event);
if (me->button() == Qt::MiddleButton) {
private:
QPointer<QAction> m_lastMiddlePressedAction;
-
};
#include "foldersitemlistwidget.h"
-FoldersItemListWidget::FoldersItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent) :
- KFileItemListWidget(informant, parent)
+FoldersItemListWidget::FoldersItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent)
+ : KFileItemListWidget(informant, parent)
{
}
{
return QPalette::WindowText;
}
-
Q_OBJECT
public:
- FoldersItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent);
+ FoldersItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent);
~FoldersItemListWidget() override;
protected:
};
#endif
-
-
#include "treeviewcontextmenu.h"
#include "views/draganddrophelper.h"
-#include <KJobWidgets>
-#include <KJobUiDelegate>
#include <KIO/CopyJob>
#include <KIO/DropJob>
#include <KIO/FileUndoManager>
#include <KIO/RenameFileDialog>
+#include <KJobUiDelegate>
+#include <KJobWidgets>
#include <QApplication>
#include <QBoxLayout>
#include <QPropertyAnimation>
#include <QTimer>
-FoldersPanel::FoldersPanel(QWidget* parent) :
- Panel(parent),
- m_updateCurrentItem(false),
- m_controller(nullptr),
- m_model(nullptr)
+FoldersPanel::FoldersPanel(QWidget *parent)
+ : Panel(parent)
+ , m_updateCurrentItem(false)
+ , m_controller(nullptr)
+ , m_model(nullptr)
{
setLayoutDirection(Qt::LeftToRight);
}
FoldersPanelSettings::self()->save();
if (m_controller) {
- KItemListView* view = m_controller->view();
+ KItemListView *view = m_controller->view();
m_controller->setView(nullptr);
delete view;
}
return FoldersPanelSettings::autoScrolling();
}
-void FoldersPanel::rename(const KFileItem& item)
+void FoldersPanel::rename(const KFileItem &item)
{
if (GeneralSettings::renameInline()) {
const int index = m_model->index(item);
m_controller->view()->editRole(index, "text");
} else {
- KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(KFileItemList({item}), this);
+ KIO::RenameFileDialog *dialog = new KIO::RenameFileDialog(KFileItemList({item}), this);
dialog->open();
}
}
}
}
-
-void FoldersPanel::showEvent(QShowEvent* event)
+void FoldersPanel::showEvent(QShowEvent *event)
{
if (event->spontaneous()) {
Panel::showEvent(event);
// Postpone the creating of the controller to the first show event.
// This assures that no performance and memory overhead is given when the folders panel is not
// used at all and stays invisible.
- KFileItemListView* view = new KFileItemListView();
+ KFileItemListView *view = new KFileItemListView();
view->setScanDirectories(false);
view->setWidgetCreator(new KItemListWidgetCreator<FoldersItemListWidget>());
view->setSupportsItemExpanding(true);
// opening the folders panel.
view->setOpacity(0);
- connect(view, &KFileItemListView::roleEditingFinished,
- this, &FoldersPanel::slotRoleEditingFinished);
+ connect(view, &KFileItemListView::roleEditingFinished, this, &FoldersPanel::slotRoleEditingFinished);
m_model = new KFileItemModel(this);
m_model->setShowDirectoriesOnly(true);
connect(m_controller, &KItemListController::viewContextMenuRequested, this, &FoldersPanel::slotViewContextMenuRequested);
connect(m_controller, &KItemListController::itemDropEvent, this, &FoldersPanel::slotItemDropEvent);
- KItemListContainer* container = new KItemListContainer(m_controller, this);
+ KItemListContainer *container = new KItemListContainer(m_controller, this);
container->setEnabledFrame(false);
- QVBoxLayout* layout = new QVBoxLayout(this);
+ QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(container);
}
Panel::showEvent(event);
}
-void FoldersPanel::keyPressEvent(QKeyEvent* event)
+void FoldersPanel::keyPressEvent(QKeyEvent *event)
{
const int key = event->key();
if ((key == Qt::Key_Enter) || (key == Qt::Key_Return)) {
}
}
-void FoldersPanel::slotItemContextMenuRequested(int index, const QPointF& pos)
+void FoldersPanel::slotItemContextMenuRequested(int index, const QPointF &pos)
{
const KFileItem fileItem = m_model->fileItem(index);
}
}
-void FoldersPanel::slotViewContextMenuRequested(const QPointF& pos)
+void FoldersPanel::slotViewContextMenuRequested(const QPointF &pos)
{
QPointer<TreeViewContextMenu> contextMenu = new TreeViewContextMenu(this, KFileItem());
contextMenu.data()->open(pos.toPoint());
}
}
-void FoldersPanel::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
+void FoldersPanel::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event)
{
if (index >= 0) {
KFileItem destItem = m_model->fileItem(index);
return;
}
- QDropEvent dropEvent(event->pos().toPoint(),
- event->possibleActions(),
- event->mimeData(),
- event->buttons(),
- event->modifiers());
+ QDropEvent dropEvent(event->pos().toPoint(), event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
KIO::DropJob *job = DragAndDropHelper::dropUrls(destItem.mostLocalUrl(), &dropEvent, this);
if (job) {
}
}
-void FoldersPanel::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
+void FoldersPanel::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value)
{
if (role == "text") {
const KFileItem item = m_model->fileItem(index);
QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
- KIO::Job* job = KIO::moveAs(oldUrl, newUrl);
+ KIO::Job *job = KIO::moveAs(oldUrl, newUrl);
KJobWidgets::setWindow(job, this);
KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
job->uiDelegate()->setAutoErrorHandlingEnabled(true);
void FoldersPanel::startFadeInAnimation()
{
- QPropertyAnimation* anim = new QPropertyAnimation(m_controller->view(), "opacity", this);
+ QPropertyAnimation *anim = new QPropertyAnimation(m_controller->view(), "opacity", this);
anim->setStartValue(0);
anim->setEndValue(1);
anim->setEasingCurve(QEasingCurve::InOutQuad);
anim->setDuration(200);
}
-void FoldersPanel::loadTree(const QUrl& url, FoldersPanel::NavigationBehaviour navigationBehaviour)
+void FoldersPanel::loadTree(const QUrl &url, FoldersPanel::NavigationBehaviour navigationBehaviour)
{
Q_ASSERT(m_controller);
baseUrl = url;
baseUrl.setPath(QStringLiteral("/"));
} else if (Dolphin::homeUrl().isParentOf(url) || (Dolphin::homeUrl() == url)) {
- if (FoldersPanelSettings::limitFoldersPanelToHome() ) {
+ if (FoldersPanelSettings::limitFoldersPanelToHome()) {
baseUrl = Dolphin::homeUrl();
} else {
// Use the root directory as base for local URLs (#150941)
const int index = m_model->index(url);
if (jumpHome) {
- Q_EMIT folderActivated(baseUrl);
+ Q_EMIT folderActivated(baseUrl);
} else if (index >= 0) {
updateCurrentItem(index);
} else if (url == baseUrl) {
void FoldersPanel::updateCurrentItem(int index)
{
- KItemListSelectionManager* selectionManager = m_controller->selectionManager();
+ KItemListSelectionManager *selectionManager = m_controller->selectionManager();
selectionManager->setCurrentItem(index);
selectionManager->clearSelection();
selectionManager->setSelected(index);
m_controller->view()->scrollToItem(index);
}
-
Q_OBJECT
public:
- explicit FoldersPanel(QWidget* parent = nullptr);
+ explicit FoldersPanel(QWidget *parent = nullptr);
~FoldersPanel() override;
void setShowHiddenFiles(bool show);
void setAutoScrolling(bool enable);
bool autoScrolling() const;
- void rename(const KFileItem& item);
+ void rename(const KFileItem &item);
Q_SIGNALS:
- void folderActivated(const QUrl& url);
+ void folderActivated(const QUrl &url);
void folderInNewTab(const QUrl &url);
void folderInNewActiveTab(const QUrl &url);
- void errorMessage(const QString& error);
+ void errorMessage(const QString &error);
protected:
/** @see Panel::urlChanged() */
bool urlChanged() override;
/** @see QWidget::showEvent() */
- void showEvent(QShowEvent* event) override;
+ void showEvent(QShowEvent *event) override;
/** @see QWidget::keyPressEvent() */
- void keyPressEvent(QKeyEvent* event) override;
+ void keyPressEvent(QKeyEvent *event) override;
private Q_SLOTS:
void slotItemActivated(int index);
void slotItemMiddleClicked(int index);
- void slotItemContextMenuRequested(int index, const QPointF& pos);
- void slotViewContextMenuRequested(const QPointF& pos);
- void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event);
- void slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value);
+ void slotItemContextMenuRequested(int index, const QPointF &pos);
+ void slotViewContextMenuRequested(const QPointF &pos);
+ void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event);
+ void slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value);
void slotLoadingCompleted();
*/
void startFadeInAnimation();
-
private:
/**
* Indicate if it is allowed to leave current location.
*/
enum NavigationBehaviour {
- StayWhereYouAre, ///< Don't leave current location.
- AllowJumpHome ///< Go Home only when context menu option got checked.
+ StayWhereYouAre, ///< Don't leave current location.
+ AllowJumpHome ///< Go Home only when context menu option got checked.
};
/**
* Initializes the base URL of the tree and expands all
* @param url URL of the leaf directory that should get expanded.
* @param navigationBehaviour Navigation behaviour \see NavigationBehaviour
*/
- void loadTree(const QUrl& url, NavigationBehaviour navigationBehaviour = StayWhereYouAre);
+ void loadTree(const QUrl &url, NavigationBehaviour navigationBehaviour = StayWhereYouAre);
void reloadTree();
private:
bool m_updateCurrentItem;
- KItemListController* m_controller;
- KFileItemModel* m_model;
+ KItemListController *m_controller;
+ KFileItemModel *m_model;
};
#endif // FOLDERSPANEL_H
#include <QMimeData>
#include <QPointer>
-TreeViewContextMenu::TreeViewContextMenu(FoldersPanel* parent,
- const KFileItem& fileInfo) :
- QObject(parent),
- m_parent(parent),
- m_fileItem(fileInfo)
+TreeViewContextMenu::TreeViewContextMenu(FoldersPanel *parent, const KFileItem &fileInfo)
+ : QObject(parent)
+ , m_parent(parent)
+ , m_fileItem(fileInfo)
{
}
{
}
-void TreeViewContextMenu::open(const QPoint& pos)
+void TreeViewContextMenu::open(const QPoint &pos)
{
- QMenu* popup = new QMenu(m_parent);
+ QMenu *popup = new QMenu(m_parent);
if (!m_fileItem.isNull()) {
KFileItemListProperties capabilities(KFileItemList() << m_fileItem);
// insert 'Cut', 'Copy' and 'Paste'
- QAction* cutAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-cut")), i18nc("@action:inmenu", "Cut"), this);
+ QAction *cutAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-cut")), i18nc("@action:inmenu", "Cut"), this);
cutAction->setEnabled(capabilities.supportsMoving());
connect(cutAction, &QAction::triggered, this, &TreeViewContextMenu::cut);
- QAction* copyAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18nc("@action:inmenu", "Copy"), this);
+ QAction *copyAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-copy")), i18nc("@action:inmenu", "Copy"), this);
connect(copyAction, &QAction::triggered, this, &TreeViewContextMenu::copy);
const QMimeData *mimeData = QApplication::clipboard()->mimeData();
bool canPaste;
const QString text = KIO::pasteActionText(mimeData, &canPaste, m_fileItem);
- QAction* pasteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
+ QAction *pasteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
connect(pasteAction, &QAction::triggered, this, &TreeViewContextMenu::paste);
pasteAction->setEnabled(canPaste);
popup->addSeparator();
// insert 'Rename'
- QAction* renameAction = new QAction(i18nc("@action:inmenu", "Rename..."), this);
+ QAction *renameAction = new QAction(i18nc("@action:inmenu", "Rename..."), this);
renameAction->setEnabled(capabilities.supportsMoving());
renameAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename")));
connect(renameAction, &QAction::triggered, this, &TreeViewContextMenu::rename);
const QUrl url = m_fileItem.url();
if (url.isLocalFile()) {
- QAction* moveToTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("user-trash")),
- i18nc("@action:inmenu", "Move to Trash"), this);
+ QAction *moveToTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("user-trash")), i18nc("@action:inmenu", "Move to Trash"), this);
const bool enableMoveToTrash = capabilities.isLocal() && capabilities.supportsMoving();
moveToTrashAction->setEnabled(enableMoveToTrash);
connect(moveToTrashAction, &QAction::triggered, this, &TreeViewContextMenu::moveToTrash);
}
if (showDeleteCommand) {
- QAction* deleteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18nc("@action:inmenu", "Delete"), this);
+ QAction *deleteAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18nc("@action:inmenu", "Delete"), this);
deleteAction->setEnabled(capabilities.supportsDeleting());
connect(deleteAction, &QAction::triggered, this, &TreeViewContextMenu::deleteItem);
popup->addAction(deleteAction);
}
// insert 'Show Hidden Files'
- QAction* showHiddenFilesAction = new QAction(i18nc("@action:inmenu", "Show Hidden Files"), this);
+ QAction *showHiddenFilesAction = new QAction(i18nc("@action:inmenu", "Show Hidden Files"), this);
showHiddenFilesAction->setCheckable(true);
showHiddenFilesAction->setChecked(m_parent->showHiddenFiles());
popup->addAction(showHiddenFilesAction);
// insert 'Limit to Home Directory'
const QUrl url = m_fileItem.url();
const bool enableLimitToHomeDirectory = url.isLocalFile();
- QAction* limitFoldersPanelToHomeAction = new QAction(i18nc("@action:inmenu", "Limit to Home Directory"), this);
+ QAction *limitFoldersPanelToHomeAction = new QAction(i18nc("@action:inmenu", "Limit to Home Directory"), this);
limitFoldersPanelToHomeAction->setCheckable(true);
limitFoldersPanelToHomeAction->setEnabled(enableLimitToHomeDirectory);
limitFoldersPanelToHomeAction->setChecked(m_parent->limitFoldersPanelToHome());
}
// insert 'Automatic Scrolling'
- QAction* autoScrollingAction = new QAction(i18nc("@action:inmenu", "Automatic Scrolling"), this);
+ QAction *autoScrollingAction = new QAction(i18nc("@action:inmenu", "Automatic Scrolling"), this);
autoScrollingAction->setCheckable(true);
autoScrollingAction->setChecked(m_parent->autoScrolling());
// TODO: Temporary disabled. Horizontal autoscrolling will be implemented later either
if (!m_fileItem.isNull()) {
// insert 'Properties' entry
- QAction* propertiesAction = new QAction(i18nc("@action:inmenu", "Properties"), this);
+ QAction *propertiesAction = new QAction(i18nc("@action:inmenu", "Properties"), this);
propertiesAction->setIcon(QIcon::fromTheme(QStringLiteral("document-properties")));
connect(propertiesAction, &QAction::triggered, this, &TreeViewContextMenu::showProperties);
popup->addAction(propertiesAction);
}
- const QList<QAction*> customActions = m_parent->customContextMenuActions();
+ const QList<QAction *> customActions = m_parent->customContextMenuActions();
if (!customActions.isEmpty()) {
popup->addSeparator();
- for (QAction* action : customActions) {
+ for (QAction *action : customActions) {
popup->addAction(action);
}
}
}
}
-void TreeViewContextMenu::populateMimeData(QMimeData* mimeData, bool cut)
+void TreeViewContextMenu::populateMimeData(QMimeData *mimeData, bool cut)
{
QList<QUrl> kdeUrls;
kdeUrls.append(m_fileItem.url());
void TreeViewContextMenu::cut()
{
- QMimeData* mimeData = new QMimeData();
+ QMimeData *mimeData = new QMimeData();
populateMimeData(mimeData, true);
QApplication::clipboard()->setMimeData(mimeData);
}
void TreeViewContextMenu::copy()
{
- QMimeData* mimeData = new QMimeData();
+ QMimeData *mimeData = new QMimeData();
populateMimeData(mimeData, false);
QApplication::clipboard()->setMimeData(mimeData);
}
KIO::JobUiDelegate uiDelegate;
uiDelegate.setWindow(m_parent);
if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) {
- KIO::Job* job = KIO::trash(list);
+ KIO::Job *job = KIO::trash(list);
KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job);
KJobWidgets::setWindow(job, m_parent);
job->uiDelegate()->setAutoErrorHandlingEnabled(true);
KIO::JobUiDelegate uiDelegate;
uiDelegate.setWindow(m_parent);
if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) {
- KIO::Job* job = KIO::del(list);
+ KIO::Job *job = KIO::del(list);
KJobWidgets::setWindow(job, m_parent);
job->uiDelegate()->setAutoErrorHandlingEnabled(true);
}
void TreeViewContextMenu::showProperties()
{
- KPropertiesDialog* dialog = new KPropertiesDialog(m_fileItem.url(), m_parent);
+ KPropertiesDialog *dialog = new KPropertiesDialog(m_fileItem.url(), m_parent);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
{
m_parent->setAutoScrolling(enable);
}
-
* is applied. If 0 is passed, the context menu
* is above the viewport.
*/
- TreeViewContextMenu(FoldersPanel* parent,
- const KFileItem& fileInfo);
+ TreeViewContextMenu(FoldersPanel *parent, const KFileItem &fileInfo);
~TreeViewContextMenu() override;
/** Opens the context menu modal. */
- void open(const QPoint& pos);
+ void open(const QPoint &pos);
private Q_SLOTS:
/** Cuts the item m_fileItem. */
void setAutoScrolling(bool enable);
private:
- void populateMimeData(QMimeData* mimeData, bool cut);
+ void populateMimeData(QMimeData *mimeData, bool cut);
private:
- FoldersPanel* m_parent;
+ FoldersPanel *m_parent;
KFileItem m_fileItem;
};
#include <Baloo/FileMetaDataWidget>
#include <QApplication>
+#include <QMenu>
#include <QShowEvent>
-#include <QVBoxLayout>
#include <QTimer>
-#include <QMenu>
+#include <QVBoxLayout>
#include "dolphin_informationpanelsettings.h"
-InformationPanel::InformationPanel(QWidget* parent) :
- Panel(parent),
- m_initialized(false),
- m_infoTimer(nullptr),
- m_urlChangedTimer(nullptr),
- m_resetUrlTimer(nullptr),
- m_shownUrl(),
- m_urlCandidate(),
- m_invalidUrlCandidate(),
- m_hoveredItem(),
- m_selection(),
- m_folderStatJob(nullptr),
- m_content(nullptr)
+InformationPanel::InformationPanel(QWidget *parent)
+ : Panel(parent)
+ , m_initialized(false)
+ , m_infoTimer(nullptr)
+ , m_urlChangedTimer(nullptr)
+ , m_resetUrlTimer(nullptr)
+ , m_shownUrl()
+ , m_urlCandidate()
+ , m_invalidUrlCandidate()
+ , m_hoveredItem()
+ , m_selection()
+ , m_folderStatJob(nullptr)
+ , m_content(nullptr)
{
}
{
}
-void InformationPanel::setSelection(const KFileItemList& selection)
+void InformationPanel::setSelection(const KFileItemList &selection)
{
m_selection = selection;
}
}
-void InformationPanel::requestDelayedItemInfo(const KFileItem& item)
+void InformationPanel::requestDelayedItemInfo(const KFileItem &item)
{
if (!isVisible()) {
return;
return true;
}
-void InformationPanel::showEvent(QShowEvent* event)
+void InformationPanel::showEvent(QShowEvent *event)
{
Panel::showEvent(event);
if (!event->spontaneous()) {
}
}
-void InformationPanel::resizeEvent(QResizeEvent* event)
+void InformationPanel::resizeEvent(QResizeEvent *event)
{
if (isVisible()) {
m_urlCandidate = m_shownUrl;
Panel::resizeEvent(event);
}
-void InformationPanel::contextMenuEvent(QContextMenuEvent* event)
+void InformationPanel::contextMenuEvent(QContextMenuEvent *event)
{
showContextMenu(event->globalPos());
Panel::contextMenuEvent(event);
{
QMenu popup(this);
- QAction* previewAction = popup.addAction(i18nc("@action:inmenu", "Preview"));
+ QAction *previewAction = popup.addAction(i18nc("@action:inmenu", "Preview"));
previewAction->setIcon(QIcon::fromTheme(QStringLiteral("view-preview")));
previewAction->setCheckable(true);
previewAction->setChecked(InformationPanelSettings::previewsShown());
- QAction* previewAutoPlayAction = popup.addAction(i18nc("@action:inmenu", "Auto-Play media files"));
+ QAction *previewAutoPlayAction = popup.addAction(i18nc("@action:inmenu", "Auto-Play media files"));
previewAutoPlayAction->setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start")));
previewAutoPlayAction->setCheckable(true);
previewAutoPlayAction->setChecked(InformationPanelSettings::previewsAutoPlay());
- QAction* configureAction = popup.addAction(i18nc("@action:inmenu", "Configure..."));
+ QAction *configureAction = popup.addAction(i18nc("@action:inmenu", "Configure..."));
configureAction->setIcon(QIcon::fromTheme(QStringLiteral("configure")));
if (m_inConfigurationMode) {
configureAction->setEnabled(false);
}
- QAction* dateformatAction = popup.addAction(i18nc("@action:inmenu", "Condensed Date"));
+ QAction *dateformatAction = popup.addAction(i18nc("@action:inmenu", "Condensed Date"));
dateformatAction->setIcon(QIcon::fromTheme(QStringLiteral("change-date-symbolic")));
dateformatAction->setCheckable(true);
dateformatAction->setChecked(InformationPanelSettings::dateFormat() == static_cast<int>(Baloo::DateFormats::ShortFormat));
// Open the popup and adjust the settings for the
// selected action.
- QAction* action = popup.exec(pos);
+ QAction *action = popup.exec(pos);
if (!action) {
return;
}
if (m_folderStatJob->uiDelegate()) {
KJobWidgets::setWindow(m_folderStatJob, this);
}
- connect(m_folderStatJob, &KIO::Job::result,
- this, &InformationPanel::slotFolderStatFinished);
+ connect(m_folderStatJob, &KIO::Job::result, this, &InformationPanel::slotFolderStatFinished);
}
}
-void InformationPanel::slotFolderStatFinished(KJob* job)
+void InformationPanel::slotFolderStatFinished(KJob *job)
{
m_folderStatJob = nullptr;
- const KIO::UDSEntry entry = static_cast<KIO::StatJob*>(job)->statResult();
+ const KIO::UDSEntry entry = static_cast<KIO::StatJob *>(job)->statResult();
m_content->showItem(KFileItem(entry, m_shownUrl));
}
}
}
-void InformationPanel::slotFileRenamed(const QString& source, const QString& dest)
+void InformationPanel::slotFileRenamed(const QString &source, const QString &dest)
{
auto sourceUrl = QUrl::fromUserInput(source);
if (m_shownUrl == sourceUrl) {
}
}
-void InformationPanel::slotFilesAdded(const QString& directory)
+void InformationPanel::slotFilesAdded(const QString &directory)
{
if (m_shownUrl == QUrl::fromUserInput(directory)) {
// If the 'trash' icon changes because the trash has been emptied or got filled,
}
}
-void InformationPanel::slotFilesChanged(const QStringList& files)
+void InformationPanel::slotFilesChanged(const QStringList &files)
{
- for (const QString& fileName : files) {
+ for (const QString &fileName : files) {
if (m_shownUrl == QUrl::fromUserInput(fileName)) {
showItemInfo();
break;
}
}
-void InformationPanel::slotFilesRemoved(const QStringList& files)
+void InformationPanel::slotFilesRemoved(const QStringList &files)
{
- for (const QString& fileName : files) {
+ for (const QString &fileName : files) {
if (m_shownUrl == QUrl::fromUserInput(fileName)) {
// the currently shown item has been removed, show
// the parent directory as fallback
}
}
-void InformationPanel::slotEnteredDirectory(const QString& directory)
+void InformationPanel::slotEnteredDirectory(const QString &directory)
{
Q_UNUSED(directory)
}
-void InformationPanel::slotLeftDirectory(const QString& directory)
+void InformationPanel::slotLeftDirectory(const QString &directory)
{
if (m_shownUrl == QUrl::fromUserInput(directory)) {
// The signal 'leftDirectory' is also emitted when a media
m_urlCandidate.clear();
}
-bool InformationPanel::isEqualToShownUrl(const QUrl& url) const
+bool InformationPanel::isEqualToShownUrl(const QUrl &url) const
{
return m_shownUrl.matches(url, QUrl::StripTrailingSlash);
}
m_infoTimer = new QTimer(this);
m_infoTimer->setInterval(300);
m_infoTimer->setSingleShot(true);
- connect(m_infoTimer, &QTimer::timeout,
- this, &InformationPanel::slotInfoTimeout);
+ connect(m_infoTimer, &QTimer::timeout, this, &InformationPanel::slotInfoTimeout);
m_urlChangedTimer = new QTimer(this);
m_urlChangedTimer->setInterval(200);
m_urlChangedTimer->setSingleShot(true);
- connect(m_urlChangedTimer, &QTimer::timeout,
- this, &InformationPanel::showItemInfo);
+ connect(m_urlChangedTimer, &QTimer::timeout, this, &InformationPanel::showItemInfo);
m_resetUrlTimer = new QTimer(this);
m_resetUrlTimer->setInterval(1000);
m_resetUrlTimer->setSingleShot(true);
- connect(m_resetUrlTimer, &QTimer::timeout,
- this, &InformationPanel::reset);
+ connect(m_resetUrlTimer, &QTimer::timeout, this, &InformationPanel::reset);
Q_ASSERT(m_urlChangedTimer->interval() < m_infoTimer->interval());
Q_ASSERT(m_urlChangedTimer->interval() < m_resetUrlTimer->interval());
- org::kde::KDirNotify* dirNotify = new org::kde::KDirNotify(QString(), QString(),
- QDBusConnection::sessionBus(), this);
+ org::kde::KDirNotify *dirNotify = new org::kde::KDirNotify(QString(), QString(), QDBusConnection::sessionBus(), this);
connect(dirNotify, &OrgKdeKDirNotifyInterface::FileRenamed, this, &InformationPanel::slotFileRenamed);
connect(dirNotify, &OrgKdeKDirNotifyInterface::FilesAdded, this, &InformationPanel::slotFilesAdded);
connect(dirNotify, &OrgKdeKDirNotifyInterface::FilesChanged, this, &InformationPanel::slotFilesChanged);
m_content = new InformationPanelContent(this);
connect(m_content, &InformationPanelContent::urlActivated, this, &InformationPanel::urlActivated);
- connect(m_content, &InformationPanelContent::configurationFinished, this, [this]() { m_inConfigurationMode = false; });
+ connect(m_content, &InformationPanelContent::configurationFinished, this, [this]() {
+ m_inConfigurationMode = false;
+ });
connect(m_content, &InformationPanelContent::contextMenuRequested, this, &InformationPanel::showContextMenu);
- QVBoxLayout* layout = new QVBoxLayout(this);
+ QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_content);
m_initialized = true;
}
-
class InformationPanelContent;
namespace KIO
{
- class Job;
+class Job;
}
/**
Q_OBJECT
public:
- explicit InformationPanel(QWidget* parent = nullptr);
+ explicit InformationPanel(QWidget *parent = nullptr);
~InformationPanel() override;
Q_SIGNALS:
- void urlActivated(const QUrl& url);
+ void urlActivated(const QUrl &url);
public Q_SLOTS:
/**
* This is invoked to inform the panel that the user has selected a new
* set of items.
*/
- void setSelection(const KFileItemList& selection);
+ void setSelection(const KFileItemList &selection);
/**
* Does a delayed request of information for the item \a item.
* are invoked, then the request will be skipped. Requesting a delayed item information
* makes sense when hovering items.
*/
- void requestDelayedItemInfo(const KFileItem& item);
+ void requestDelayedItemInfo(const KFileItem &item);
void slotFilesItemChanged(const KFileItemList &changedFileItems);
bool urlChanged() override;
/** @see QWidget::showEvent() */
- void showEvent(QShowEvent* event) override;
+ void showEvent(QShowEvent *event) override;
/** @see QWidget::resizeEvent() */
- void resizeEvent(QResizeEvent* event) override;
+ void resizeEvent(QResizeEvent *event) override;
/** @see QWidget::contextMenuEvent() */
- void contextMenuEvent(QContextMenuEvent* event) override;
+ void contextMenuEvent(QContextMenuEvent *event) override;
private Q_SLOTS:
/**
* Shows the information for the currently displayed folder as a result from
* a stat job issued in showItemInfo().
*/
- void slotFolderStatFinished(KJob* job);
+ void slotFolderStatFinished(KJob *job);
/**
* Triggered if the request for item information has timed out.
*/
void reset();
- void slotFileRenamed(const QString& source, const QString& dest);
- void slotFilesAdded(const QString& directory);
- void slotFilesChanged(const QStringList& files);
- void slotFilesRemoved(const QStringList& files);
- void slotEnteredDirectory(const QString& directory);
- void slotLeftDirectory(const QString& directory);
+ void slotFileRenamed(const QString &source, const QString &dest);
+ void slotFilesAdded(const QString &directory);
+ void slotFilesChanged(const QStringList &files);
+ void slotFilesRemoved(const QStringList &files);
+ void slotEnteredDirectory(const QString &directory);
+ void slotLeftDirectory(const QString &directory);
private:
/** Assures that any pending item information request is cancelled. */
/**
* Returns true, if \a url is equal to the shown URL m_shownUrl.
*/
- bool isEqualToShownUrl(const QUrl& url) const;
+ bool isEqualToShownUrl(const QUrl &url) const;
/**
* Marks the URL as invalid and will reset the Information Panel
private:
bool m_initialized;
- QTimer* m_infoTimer;
- QTimer* m_urlChangedTimer;
- QTimer* m_resetUrlTimer;
+ QTimer *m_infoTimer;
+ QTimer *m_urlChangedTimer;
+ QTimer *m_resetUrlTimer;
// URL that is currently shown in the Information Panel.
QUrl m_shownUrl;
KFileItem m_hoveredItem;
KFileItemList m_selection;
- KIO::Job* m_folderStatJob;
+ KIO::Job *m_folderStatJob;
- InformationPanelContent* m_content;
+ InformationPanelContent *m_content;
bool m_inConfigurationMode = false;
};
#include "informationpanelcontent.h"
-#include <KIO/PreviewJob>
#include <KConfigGroup>
+#include <KIO/PreviewJob>
#include <KIconEffect>
#include <KIconLoader>
#include <KJobWidgets>
const int PLAY_ARROW_SIZE = 24;
const int PLAY_ARROW_BORDER_SIZE = 2;
-InformationPanelContent::InformationPanelContent(QWidget* parent) :
- QWidget(parent),
- m_item(),
- m_previewJob(nullptr),
- m_outdatedPreviewTimer(nullptr),
- m_preview(nullptr),
- m_phononWidget(nullptr),
- m_nameLabel(nullptr),
- m_metaDataWidget(nullptr),
- m_metaDataArea(nullptr),
- m_isVideo(false)
+InformationPanelContent::InformationPanelContent(QWidget *parent)
+ : QWidget(parent)
+ , m_item()
+ , m_previewJob(nullptr)
+ , m_outdatedPreviewTimer(nullptr)
+ , m_preview(nullptr)
+ , m_phononWidget(nullptr)
+ , m_nameLabel(nullptr)
+ , m_metaDataWidget(nullptr)
+ , m_metaDataArea(nullptr)
+ , m_isVideo(false)
{
parent->installEventFilter(this);
m_outdatedPreviewTimer = new QTimer(this);
m_outdatedPreviewTimer->setInterval(100);
m_outdatedPreviewTimer->setSingleShot(true);
- connect(m_outdatedPreviewTimer, &QTimer::timeout,
- this, &InformationPanelContent::markOutdatedPreview);
+ connect(m_outdatedPreviewTimer, &QTimer::timeout, this, &InformationPanelContent::markOutdatedPreview);
- QVBoxLayout* layout = new QVBoxLayout(this);
+ QVBoxLayout *layout = new QVBoxLayout(this);
// preview
const int minPreviewWidth = KIconLoader::SizeEnormous + KIconLoader::SizeMedium;
m_phononWidget->hide();
m_phononWidget->setMinimumWidth(minPreviewWidth);
m_phononWidget->setAutoPlay(InformationPanelSettings::previewsAutoPlay());
- connect(m_phononWidget, &PhononWidget::hasVideoChanged,
- this, &InformationPanelContent::slotHasVideoChanged);
+ connect(m_phononWidget, &PhononWidget::hasVideoChanged, this, &InformationPanelContent::slotHasVideoChanged);
// name
m_nameLabel = new QLabel(parent);
m_metaDataWidget = new Baloo::FileMetaDataWidget(parent);
m_metaDataWidget->setDateFormat(static_cast<Baloo::DateFormats>(InformationPanelSettings::dateFormat()));
- connect(m_metaDataWidget, &Baloo::FileMetaDataWidget::urlActivated,
- this, &InformationPanelContent::urlActivated);
+ connect(m_metaDataWidget, &Baloo::FileMetaDataWidget::urlActivated, this, &InformationPanelContent::urlActivated);
m_metaDataWidget->setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
m_metaDataWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
// Configuration
- m_configureLabel = new QLabel(i18nc("@label::textbox",
- "Select which data should be shown:"), this);
+ m_configureLabel = new QLabel(i18nc("@label::textbox", "Select which data should be shown:"), this);
m_configureLabel->setWordWrap(true);
m_configureLabel->setVisible(false);
m_configureButtons = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
m_configureButtons->setVisible(false);
connect(m_configureButtons, &QDialogButtonBox::accepted, this, [this]() {
- m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Accept);
- m_configureButtons->setVisible(false);
- m_configureLabel->setVisible(false);
- Q_EMIT configurationFinished();
- }
- );
+ m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Accept);
+ m_configureButtons->setVisible(false);
+ m_configureLabel->setVisible(false);
+ Q_EMIT configurationFinished();
+ });
connect(m_configureButtons, &QDialogButtonBox::rejected, this, [this]() {
- m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Cancel);
- m_configureButtons->setVisible(false);
- m_configureLabel->setVisible(false);
- Q_EMIT configurationFinished();
- }
- );
+ m_metaDataWidget->setConfigurationMode(Baloo::ConfigurationMode::Cancel);
+ m_configureButtons->setVisible(false);
+ m_configureLabel->setVisible(false);
+ Q_EMIT configurationFinished();
+ });
m_metaDataArea = new QScrollArea(parent);
m_metaDataArea->setWidget(m_metaDataWidget);
m_metaDataArea->setWidgetResizable(true);
m_metaDataArea->setFrameShape(QFrame::NoFrame);
- QWidget* viewport = m_metaDataArea->viewport();
+ QWidget *viewport = m_metaDataArea->viewport();
QScroller::grabGesture(viewport, QScroller::TouchGesture);
viewport->installEventFilter(this);
InformationPanelSettings::self()->save();
}
-void InformationPanelContent::showItem(const KFileItem& item)
+void InformationPanelContent::showItem(const KFileItem &item)
{
// compares item entries, comparing items only compares urls
if (m_item.entry() != item.entry()) {
const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
const QStringList plugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
- m_previewJob = new KIO::PreviewJob(KFileItemList() << m_item,
- QSize(m_preview->width(), m_preview->height()),
- &plugins);
+ m_previewJob = new KIO::PreviewJob(KFileItemList() << m_item, QSize(m_preview->width(), m_preview->height()), &plugins);
m_previewJob->setScaleType(KIO::PreviewJob::Unscaled);
m_previewJob->setIgnoreMaximumSize(m_item.isLocalFile() && !m_item.isSlow());
if (m_previewJob->uiDelegate()) {
KJobWidgets::setWindow(m_previewJob, this);
}
- connect(m_previewJob.data(), &KIO::PreviewJob::gotPreview,
- this, &InformationPanelContent::showPreview);
- connect(m_previewJob.data(), &KIO::PreviewJob::failed,
- this, &InformationPanelContent::showIcon);
+ connect(m_previewJob.data(), &KIO::PreviewJob::gotPreview, this, &InformationPanelContent::showPreview);
+ connect(m_previewJob.data(), &KIO::PreviewJob::failed, this, &InformationPanelContent::showIcon);
}
void InformationPanelContent::refreshPreview()
m_preview->setCursor(Qt::ArrowCursor);
setNameLabelText(m_item.text());
if (InformationPanelSettings::previewsShown()) {
-
const QUrl itemUrl = m_item.url();
const bool isSearchUrl = itemUrl.scheme().contains(QLatin1String("search")) && m_item.localPath().isEmpty();
if (isSearchUrl) {
// in the case of a search-URL the URL is not readable for humans
// (at least not useful to show in the Information Panel)
- m_preview->setPixmap(
- QIcon::fromTheme(QStringLiteral("baloo")).pixmap(m_preview->height(), m_preview->width())
- );
+ m_preview->setPixmap(QIcon::fromTheme(QStringLiteral("baloo")).pixmap(m_preview->height(), m_preview->width()));
} else {
-
refreshPixmapView();
const QString mimeType = m_item.mimetype();
// we don't need to update the preview/phonon widget states
// unless the previewed file has changed,
// or the setting previewshown has changed
- if ((m_phononWidget->state() != Phonon::State::PlayingState &&
- m_phononWidget->state() != Phonon::State::PausedState &&
- m_phononWidget->state() != Phonon::State::StoppedState) ||
- m_item.targetUrl() != m_phononWidget->url() ||
- (!m_preview->isVisible() &&! m_phononWidget->isVisible())) {
-
+ if ((m_phononWidget->state() != Phonon::State::PlayingState && m_phononWidget->state() != Phonon::State::PausedState
+ && m_phononWidget->state() != Phonon::State::StoppedState)
+ || m_item.targetUrl() != m_phononWidget->url() || (!m_preview->isVisible() && !m_phononWidget->isVisible())) {
if (InformationPanelSettings::previewsAutoPlay() && m_isVideo) {
// hides the preview now to avoid flickering when the autoplay video starts
m_preview->hide();
m_metaDataWidget->setItems(KFileItemList() << m_item);
}
-void InformationPanelContent::showItems(const KFileItemList& items)
+void InformationPanelContent::showItems(const KFileItemList &items)
{
// If there is a preview job, kill it to prevent that we have jobs for
// multiple items running, and thus a race condition (bug 250787).
m_preview->stopAnimatedImage();
- m_preview->setPixmap(
- QIcon::fromTheme(QStringLiteral("dialog-information")).pixmap(m_preview->height(), m_preview->width())
- );
+ m_preview->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-information")).pixmap(m_preview->height(), m_preview->width()));
setNameLabelText(i18ncp("@label", "%1 item selected", "%1 items selected", items.count()));
m_metaDataWidget->setItems(items);
m_item = KFileItem();
}
-bool InformationPanelContent::eventFilter(QObject* obj, QEvent* event)
+bool InformationPanelContent::eventFilter(QObject *obj, QEvent *event)
{
switch (event->type()) {
case QEvent::Resize: {
- QResizeEvent* resizeEvent = static_cast<QResizeEvent*>(event);
+ QResizeEvent *resizeEvent = static_cast<QResizeEvent *>(event);
if (obj == m_metaDataArea->viewport()) {
// The size of the meta text area has changed. Adjust the fixed
// width in a way that no horizontal scrollbar needs to be shown.
return QWidget::eventFilter(obj, event);
}
-bool InformationPanelContent::event(QEvent* event)
+bool InformationPanelContent::event(QEvent *event)
{
if (event->type() == QEvent::Gesture) {
- gestureEvent(static_cast<QGestureEvent*>(event));
+ gestureEvent(static_cast<QGestureEvent *>(event));
return true;
}
return QWidget::event(event);
}
-bool InformationPanelContent::gestureEvent(QGestureEvent* event)
+bool InformationPanelContent::gestureEvent(QGestureEvent *event)
{
if (!underMouse()) {
return false;
}
- QTapAndHoldGesture* tap = static_cast<QTapAndHoldGesture*>(event->gesture(Qt::TapAndHoldGesture));
+ QTapAndHoldGesture *tap = static_cast<QTapAndHoldGesture *>(event->gesture(Qt::TapAndHoldGesture));
if (tap) {
if (tap->state() == Qt::GestureFinished) {
return false;
}
-void InformationPanelContent::showIcon(const KFileItem& item)
+void InformationPanelContent::showIcon(const KFileItem &item)
{
m_outdatedPreviewTimer->stop();
QPixmap pixmap = QIcon::fromTheme(item.iconName()).pixmap(m_preview->height(), m_preview->width());
m_preview->setPixmap(pixmap);
}
-void InformationPanelContent::showPreview(const KFileItem& item,
- const QPixmap& pixmap)
+void InformationPanelContent::showPreview(const KFileItem &item, const QPixmap &pixmap)
{
m_outdatedPreviewTimer->stop();
QPainterPath path;
path.addPolygon(arrow);
- QLinearGradient gradient(QPointF(zeroX, zeroY + arrowSize / 2),
- QPointF(zeroX + arrowSize, zeroY + arrowSize / 2));
+ QLinearGradient gradient(QPointF(zeroX, zeroY + arrowSize / 2), QPointF(zeroX + arrowSize, zeroY + arrowSize / 2));
QColor whiteColor = Qt::white;
QColor blackColor = Qt::black;
showIcon(m_item);
} else {
KIconEffect *iconEffect = KIconLoader::global()->iconEffect();
- QPixmap disabledPixmap = iconEffect->apply(m_preview->pixmap(),
- KIconLoader::Desktop,
- KIconLoader::DisabledState);
+ QPixmap disabledPixmap = iconEffect->apply(m_preview->pixmap(), KIconLoader::Desktop, KIconLoader::DisabledState);
m_preview->setPixmap(disabledPixmap);
}
}
}
}
-void InformationPanelContent::setPreviewAutoPlay(bool autoPlay) {
+void InformationPanelContent::setPreviewAutoPlay(bool autoPlay)
+{
m_phononWidget->setAutoPlay(autoPlay);
}
-void InformationPanelContent::setNameLabelText(const QString& text)
+void InformationPanelContent::setNameLabelText(const QString &text)
{
QTextOption textOption;
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
m_phononWidget->setVideoSize(QSize(maxWidth, maxWidth));
}
}
-
#ifndef INFORMATIONPANELCONTENT_H
#define INFORMATIONPANELCONTENT_H
-#include <KFileItem>
#include "config-dolphin.h"
+#include <KFileItem>
#include <QPointer>
#include <QUrl>
class QScrollArea;
class QGestureEvent;
-namespace KIO {
- class PreviewJob;
+namespace KIO
+{
+class PreviewJob;
}
-namespace Baloo {
- class FileMetaDataWidget;
+namespace Baloo
+{
+class FileMetaDataWidget;
}
/**
Q_OBJECT
public:
- explicit InformationPanelContent(QWidget* parent = nullptr);
+ explicit InformationPanelContent(QWidget *parent = nullptr);
~InformationPanelContent() override;
/**
* The preview of the item is generated asynchronously,
* the other meta information are fetched synchronously.
*/
- void showItem(const KFileItem& item);
+ void showItem(const KFileItem &item);
/**
* Shows the meta information for the items \p items and its preview
*/
- void showItems(const KFileItemList& items);
+ void showItems(const KFileItemList &items);
KFileItemList items();
void setPreviewAutoPlay(bool autoPlay);
Q_SIGNALS:
- void urlActivated( const QUrl& url );
+ void urlActivated(const QUrl &url);
void configurationFinished();
- void contextMenuRequested(const QPoint& pos);
+ void contextMenuRequested(const QPoint &pos);
public Q_SLOTS:
/**
protected:
/** @see QObject::eventFilter() */
- bool eventFilter(QObject* obj, QEvent* event) override;
+ bool eventFilter(QObject *obj, QEvent *event) override;
- bool event(QEvent * event) override;
+ bool event(QEvent *event) override;
private Q_SLOTS:
/**
* Is invoked if no preview is available for the item. In this
* case the icon will be shown.
*/
- void showIcon(const KFileItem& item);
+ void showIcon(const KFileItem &item);
/**
* Is invoked if a preview is available for the item. The preview
* \a pixmap is shown inside the info page.
*/
- void showPreview(const KFileItem& item, const QPixmap& pixmap);
+ void showPreview(const KFileItem &item, const QPixmap &pixmap);
/**
* Marks the currently shown preview as outdated
* label width (QLabel::setWordWrap() does not work if the
* text represents one extremely long word).
*/
- void setNameLabelText(const QString& text);
+ void setNameLabelText(const QString &text);
/**
* Adjusts the sizes of the widgets dependent on the available
*/
void refreshPixmapView();
- bool gestureEvent(QGestureEvent* event);
+ bool gestureEvent(QGestureEvent *event);
private:
KFileItem m_item;
QPointer<KIO::PreviewJob> m_previewJob;
- QTimer* m_outdatedPreviewTimer;
-
- PixmapViewer* m_preview;
- PhononWidget* m_phononWidget;
- QLabel* m_nameLabel;
- Baloo::FileMetaDataWidget* m_metaDataWidget;
- QScrollArea* m_metaDataArea;
- QLabel* m_configureLabel;
- QDialogButtonBox* m_configureButtons;
+ QTimer *m_outdatedPreviewTimer;
+
+ PixmapViewer *m_preview;
+ PhononWidget *m_phononWidget;
+ QLabel *m_nameLabel;
+ Baloo::FileMetaDataWidget *m_metaDataWidget;
+ QScrollArea *m_metaDataArea;
+ QLabel *m_configureLabel;
+ QDialogButtonBox *m_configureButtons;
bool m_isVideo;
};
{
Q_OBJECT
- public:
- EmbeddedVideoPlayer(QWidget *parent = nullptr) :
- Phonon::VideoWidget(parent)
- {
- }
+public:
+ EmbeddedVideoPlayer(QWidget *parent = nullptr)
+ : Phonon::VideoWidget(parent)
+ {
+ }
- void setSizeHint(const QSize& size)
- {
- m_sizeHint = size;
- updateGeometry();
- }
+ void setSizeHint(const QSize &size)
+ {
+ m_sizeHint = size;
+ updateGeometry();
+ }
- QSize sizeHint() const override
- {
- return m_sizeHint.isValid() ? m_sizeHint : Phonon::VideoWidget::sizeHint();
- }
+ QSize sizeHint() const override
+ {
+ return m_sizeHint.isValid() ? m_sizeHint : Phonon::VideoWidget::sizeHint();
+ }
- private:
- QSize m_sizeHint;
+private:
+ QSize m_sizeHint;
};
PhononWidget::PhononWidget(QWidget *parent)
- : QWidget(parent),
- m_url(),
- m_playButton(nullptr),
- m_pauseButton(nullptr),
- m_topLayout(nullptr),
- m_media(nullptr),
- m_seekSlider(nullptr),
- m_audioOutput(nullptr),
- m_videoPlayer(nullptr)
+ : QWidget(parent)
+ , m_url()
+ , m_playButton(nullptr)
+ , m_pauseButton(nullptr)
+ , m_topLayout(nullptr)
+ , m_media(nullptr)
+ , m_seekSlider(nullptr)
+ , m_audioOutput(nullptr)
+ , m_videoPlayer(nullptr)
{
}
{
Q_UNUSED(object)
if (event->type() == QEvent::MouseButtonPress) {
- const QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
+ const QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if (mouseEvent->button() == Qt::LeftButton) {
// toggle playback
togglePlayback();
return false;
}
-void PhononWidget::setVideoSize(const QSize& size)
+void PhononWidget::setVideoSize(const QSize &size)
{
if (m_videoSize != size) {
m_videoSize = size;
{
if (!m_media) {
m_media = new Phonon::MediaObject(this);
- connect(m_media, &Phonon::MediaObject::stateChanged,
- this, &PhononWidget::stateChanged);
- connect(m_media, &Phonon::MediaObject::finished,
- this, &PhononWidget::finished);
+ connect(m_media, &Phonon::MediaObject::stateChanged, this, &PhononWidget::stateChanged);
+ connect(m_media, &Phonon::MediaObject::finished, this, &PhononWidget::finished);
m_seekSlider->setMediaObject(m_media);
}
namespace Phonon
{
- class AudioOutput;
- class MediaObject;
- class SeekSlider;
- class VideoPlayer;
+class AudioOutput;
+class MediaObject;
+class SeekSlider;
+class VideoPlayer;
} // namespace Phonon
class EmbeddedVideoPlayer;
class PhononWidget : public QWidget
{
Q_OBJECT
- public:
-
- enum MediaKind {
- Video,
- Audio
- };
-
- explicit PhononWidget(QWidget *parent = nullptr);
-
- void setUrl(const QUrl &url, MediaKind kind);
- QUrl url() const;
- void clearUrl();
-
- void setVideoSize(const QSize& size);
- QSize videoSize() const;
- Phonon::State state() const;
-
- void setAutoPlay(bool autoPlay);
- bool eventFilter(QObject *object, QEvent *event) override;
-
- Q_SIGNALS:
- /**
- * Is emitted whenever the video-state
- * has changed: If true is returned, a video
- * including control-buttons will be shown.
- * If false is returned, no video is shown
- * and the control-buttons are available for
- * audio only.
- */
- void hasVideoChanged(bool hasVideo);
-
- public Q_SLOTS:
- void play();
-
- protected:
- void showEvent(QShowEvent *event) override;
- void hideEvent(QHideEvent *event) override;
-
- private Q_SLOTS:
- void stateChanged(Phonon::State newstate);
- void stop();
- void finished();
-
- private:
- void applyVideoSize();
-
- private:
- void togglePlayback();
-
- QUrl m_url;
- QSize m_videoSize;
-
- QToolButton *m_playButton;
- QToolButton *m_pauseButton;
-
- QVBoxLayout *m_topLayout;
- Phonon::MediaObject *m_media;
- Phonon::SeekSlider *m_seekSlider;
- Phonon::AudioOutput *m_audioOutput;
- EmbeddedVideoPlayer *m_videoPlayer;
- bool m_autoPlay;
- bool m_isVideo;
+public:
+ enum MediaKind { Video, Audio };
+
+ explicit PhononWidget(QWidget *parent = nullptr);
+
+ void setUrl(const QUrl &url, MediaKind kind);
+ QUrl url() const;
+ void clearUrl();
+
+ void setVideoSize(const QSize &size);
+ QSize videoSize() const;
+ Phonon::State state() const;
+
+ void setAutoPlay(bool autoPlay);
+ bool eventFilter(QObject *object, QEvent *event) override;
+
+Q_SIGNALS:
+ /**
+ * Is emitted whenever the video-state
+ * has changed: If true is returned, a video
+ * including control-buttons will be shown.
+ * If false is returned, no video is shown
+ * and the control-buttons are available for
+ * audio only.
+ */
+ void hasVideoChanged(bool hasVideo);
+
+public Q_SLOTS:
+ void play();
+
+protected:
+ void showEvent(QShowEvent *event) override;
+ void hideEvent(QHideEvent *event) override;
+
+private Q_SLOTS:
+ void stateChanged(Phonon::State newstate);
+ void stop();
+ void finished();
+
+private:
+ void applyVideoSize();
+
+private:
+ void togglePlayback();
+
+ QUrl m_url;
+ QSize m_videoSize;
+
+ QToolButton *m_playButton;
+ QToolButton *m_pauseButton;
+
+ QVBoxLayout *m_topLayout;
+ Phonon::MediaObject *m_media;
+ Phonon::SeekSlider *m_seekSlider;
+ Phonon::AudioOutput *m_audioOutput;
+ EmbeddedVideoPlayer *m_videoPlayer;
+ bool m_autoPlay;
+ bool m_isVideo;
};
#endif // PHONONWIDGET_H
#include <QPainter>
#include <QStyle>
-PixmapViewer::PixmapViewer(QWidget* parent, Transition transition) :
- QWidget(parent),
- m_animatedImage(nullptr),
- m_transition(transition),
- m_animationStep(0),
- m_sizeHint(),
- m_hasAnimatedImage(false)
+PixmapViewer::PixmapViewer(QWidget *parent, Transition transition)
+ : QWidget(parent)
+ , m_animatedImage(nullptr)
+ , m_transition(transition)
+ , m_animationStep(0)
+ , m_sizeHint()
+ , m_hasAnimatedImage(false)
{
setMinimumWidth(KIconLoader::SizeEnormous);
setMinimumHeight(KIconLoader::SizeEnormous);
{
}
-void PixmapViewer::setPixmap(const QPixmap& pixmap)
+void PixmapViewer::setPixmap(const QPixmap &pixmap)
{
if (pixmap.isNull()) {
return;
m_pixmap = pixmap;
update();
- const bool animateTransition = (m_transition != NoTransition) &&
- (m_pixmap.size() != m_oldPixmap.size());
+ const bool animateTransition = (m_transition != NoTransition) && (m_pixmap.size() != m_oldPixmap.size());
if (animateTransition) {
m_animation.start();
} else if (m_hasAnimatedImage) {
}
}
-void PixmapViewer::setSizeHint(const QSize& size)
+void PixmapViewer::setSizeHint(const QSize &size)
{
if (m_animatedImage && size != m_sizeHint) {
m_animatedImage->stop();
m_hasAnimatedImage = m_animatedImage->isValid() && (m_animatedImage->frameCount() > 1);
}
-
QString PixmapViewer::animatedImageFileName() const
{
if (!m_hasAnimatedImage) {
return m_animatedImage->fileName();
}
-void PixmapViewer::paintEvent(QPaintEvent* event)
+void PixmapViewer::paintEvent(QPaintEvent *event)
{
QWidget::paintEvent(event);
if (m_transition != NoTransition || (m_hasAnimatedImage && m_animatedImage->state() != QMovie::Running)) {
const float value = m_animation.currentValue();
- const int scaledWidth = static_cast<int>((m_oldPixmap.width() * (1.0 - value)) + (m_pixmap.width() * value));
+ const int scaledWidth = static_cast<int>((m_oldPixmap.width() * (1.0 - value)) + (m_pixmap.width() * value));
const int scaledHeight = static_cast<int>((m_oldPixmap.height() * (1.0 - value)) + (m_pixmap.height() * value));
- const bool useOldPixmap = (m_transition == SizeTransition) &&
- (m_oldPixmap.width() > m_pixmap.width());
- const QPixmap& largePixmap = useOldPixmap ? m_oldPixmap : m_pixmap;
+ const bool useOldPixmap = (m_transition == SizeTransition) && (m_oldPixmap.width() > m_pixmap.width());
+ const QPixmap &largePixmap = useOldPixmap ? m_oldPixmap : m_pixmap;
if (!largePixmap.isNull()) {
- const QPixmap scaledPixmap = largePixmap.scaled(scaledWidth,
- scaledHeight,
- Qt::IgnoreAspectRatio,
- Qt::FastTransformation);
+ const QPixmap scaledPixmap = largePixmap.scaled(scaledWidth, scaledHeight, Qt::IgnoreAspectRatio, Qt::FastTransformation);
style()->drawItemPixmap(&painter, rect(), Qt::AlignCenter, scaledPixmap);
}
void PixmapViewer::updateAnimatedImageFrame()
{
- Q_ASSERT (m_animatedImage);
+ Q_ASSERT(m_animatedImage);
m_pixmap = m_animatedImage->currentPixmap();
update();
bool PixmapViewer::isAnimatedMimeType(const QString &mimeType)
{
const QList<QByteArray> imageFormats = QImageReader::imageFormatsForMimeType(mimeType.toUtf8());
- return std::any_of(imageFormats.begin(), imageFormats.end(),
- [](const QByteArray &format){ return QMovie::supportedFormats().contains(format); });
+ return std::any_of(imageFormats.begin(), imageFormats.end(), [](const QByteArray &format) {
+ return QMovie::supportedFormats().contains(format);
+ });
}
Q_OBJECT
public:
- enum Transition
- {
+ enum Transition {
/** No transition is done when the pixmap is changed. */
NoTransition,
SizeTransition
};
- explicit PixmapViewer(QWidget* parent,
- Transition transition = DefaultTransition);
+ explicit PixmapViewer(QWidget *parent, Transition transition = DefaultTransition);
~PixmapViewer() override;
- void setPixmap(const QPixmap& pixmap);
+ void setPixmap(const QPixmap &pixmap);
QPixmap pixmap() const;
/**
* Sets the size hint to \a size and triggers a relayout
* of the parent widget. Per default no size hint is given.
*/
- void setSizeHint(const QSize& size);
+ void setSizeHint(const QSize &size);
QSize sizeHint() const override;
- void setAnimatedImageFileName(const QString& fileName);
+ void setAnimatedImageFileName(const QString &fileName);
QString animatedImageFileName() const;
void stopAnimatedImage();
static bool isAnimatedMimeType(const QString &mimeType);
protected:
- void paintEvent(QPaintEvent* event) override;
+ void paintEvent(QPaintEvent *event) override;
private Q_SLOTS:
void checkPendingPixmaps();
private:
QPixmap m_pixmap;
QPixmap m_oldPixmap;
- QMovie* m_animatedImage;
+ QMovie *m_animatedImage;
QQueue<QPixmap> m_pendingPixmaps;
QTimeLine m_animation;
Transition m_transition;
return m_pixmap;
}
-
#endif
#include "panel.h"
-Panel::Panel(QWidget* parent) :
- QWidget(parent),
- m_url(),
- m_customContextMenuActions()
+Panel::Panel(QWidget *parent)
+ : QWidget(parent)
+ , m_url()
+ , m_customContextMenuActions()
{
}
return m_url;
}
-void Panel::setCustomContextMenuActions(const QList<QAction*>& actions)
+void Panel::setCustomContextMenuActions(const QList<QAction *> &actions)
{
m_customContextMenuActions = actions;
}
-QList<QAction*> Panel::customContextMenuActions() const
+QList<QAction *> Panel::customContextMenuActions() const
{
return m_customContextMenuActions;
}
return QSize(180, 180);
}
-void Panel::setUrl(const QUrl& url)
+void Panel::setUrl(const QUrl &url)
{
if (url.matches(m_url, QUrl::StripTrailingSlash)) {
return;
void Panel::readSettings()
{
-
}
-
Q_OBJECT
public:
- explicit Panel(QWidget* parent = nullptr);
+ explicit Panel(QWidget *parent = nullptr);
~Panel() override;
/** Returns the current set URL of the active Dolphin view. */
* context menu actions. Allows an application to apply custom actions to
* the panel.
*/
- void setCustomContextMenuActions(const QList<QAction*>& actions);
- QList<QAction*> customContextMenuActions() const;
+ void setCustomContextMenuActions(const QList<QAction *> &actions);
+ QList<QAction *> customContextMenuActions() const;
QSize sizeHint() const override;
private:
QUrl m_url;
- QList<QAction*> m_customContextMenuActions;
+ QList<QAction *> m_customContextMenuActions;
};
#endif // PANEL_H
#include "placespanel.h"
-#include "dolphinplacesmodelsingleton.h"
#include "dolphin_generalsettings.h"
#include "dolphin_placespanelsettings.h"
+#include "dolphinplacesmodelsingleton.h"
#include "global.h"
-#include "views/draganddrophelper.h"
#include "settings/dolphinsettingsdialog.h"
+#include "views/draganddrophelper.h"
#include <KFilePlacesModel>
#include <KIO/DropJob>
#include <Solid/StorageAccess>
-PlacesPanel::PlacesPanel(QWidget* parent)
+PlacesPanel::PlacesPanel(QWidget *parent)
: KFilePlacesView(parent)
{
setDropOnPlaceEnabled(true);
- connect(this, &PlacesPanel::urlsDropped,
- this, &PlacesPanel::slotUrlsDropped);
+ connect(this, &PlacesPanel::urlsDropped, this, &PlacesPanel::slotUrlsDropped);
setAutoResizeItemsEnabled(false);
// Don't store 0 size, let's keep -1 for default/small/automatic
iconSize = -1;
}
- PlacesPanelSettings* settings = PlacesPanelSettings::self();
+ PlacesPanelSettings *settings = PlacesPanelSettings::self();
settings->setIconSize(iconSize);
settings->save();
});
KFilePlacesView::setUrl(url);
}
-QList<QAction*> PlacesPanel::customContextMenuActions() const
+QList<QAction *> PlacesPanel::customContextMenuActions() const
{
return m_customContextMenuActions;
}
setIconSize(QSize(iconSize, iconSize));
}
-void PlacesPanel::showEvent(QShowEvent* event)
+void PlacesPanel::showEvent(QShowEvent *event)
{
if (!event->spontaneous() && !model()) {
readSettings();
{
const QUrl url = currentIndex().data(KFilePlacesModel::UrlRole).toUrl();
- DolphinSettingsDialog* settingsDialog = new DolphinSettingsDialog(url, this);
+ DolphinSettingsDialog *settingsDialog = new DolphinSettingsDialog(url, this);
settingsDialog->setCurrentPage(settingsDialog->trashSettings);
settingsDialog->setAttribute(Qt::WA_DeleteOnClose);
settingsDialog->show();
}
-void PlacesPanel::slotUrlsDropped(const QUrl& dest, QDropEvent* event, QWidget* parent)
+void PlacesPanel::slotUrlsDropped(const QUrl &dest, QDropEvent *event, QWidget *parent)
{
KIO::DropJob *job = DragAndDropHelper::dropUrls(dest, event, parent);
if (job) {
void PlacesPanel::slotTearDownRequestedExternally(const QString &udi)
{
Q_UNUSED(udi);
- auto *storageAccess = static_cast<Solid::StorageAccess*>(sender());
+ auto *storageAccess = static_cast<Solid::StorageAccess *>(sender());
Q_EMIT storageTearDownExternallyRequested(storageAccess->filePath());
}
#include "panels/panel.h"
-#include <QUrl>
#include <KFilePlacesView>
+#include <QUrl>
#include <Solid/SolidNamespace> // Solid::ErrorType
Q_OBJECT
public:
- explicit PlacesPanel(QWidget* parent);
+ explicit PlacesPanel(QWidget *parent);
~PlacesPanel() override;
void setUrl(const QUrl &url); // override
// for compatibility with Panel, actions that are shown
// on the view's context menu
- QList<QAction*> customContextMenuActions() const;
- void setCustomContextMenuActions(const QList<QAction*>& actions);
+ QList<QAction *> customContextMenuActions() const;
+ void setCustomContextMenuActions(const QList<QAction *> &actions);
void requestTearDown();
void proceedWithTearDown();
void readSettings();
Q_SIGNALS:
- void errorMessage(const QString& error);
- void storageTearDownRequested(const QString& mountPath);
- void storageTearDownExternallyRequested(const QString& mountPath);
+ void errorMessage(const QString &error);
+ void storageTearDownRequested(const QString &mountPath);
+ void storageTearDownExternallyRequested(const QString &mountPath);
void storageTearDownSuccessful();
protected:
- void showEvent(QShowEvent* event) override;
+ void showEvent(QShowEvent *event) override;
void dragMoveEvent(QDragMoveEvent *event) override;
private Q_SLOTS:
void slotConfigureTrash();
- void slotUrlsDropped(const QUrl& dest, QDropEvent* event, QWidget* parent);
+ void slotUrlsDropped(const QUrl &dest, QDropEvent *event, QWidget *parent);
void slotContextMenuAboutToShow(const QModelIndex &index, QMenu *menu);
void slotTearDownRequested(const QModelIndex &index);
void slotTearDownRequestedExternally(const QString &udi);
void connectDeviceSignals(const QModelIndex &idx);
QUrl m_url; // only used for initial setUrl
- QList<QAction*> m_customContextMenuActions;
+ QList<QAction *> m_customContextMenuActions;
QPersistentModelIndex m_indexToTearDown;
#include <QTimer>
#include <QVBoxLayout>
-TerminalPanel::TerminalPanel(QWidget* parent) :
- Panel(parent),
- m_clearTerminal(true),
- m_mostLocalUrlJob(nullptr),
- m_layout(nullptr),
- m_terminal(nullptr),
- m_terminalWidget(nullptr),
- m_konsolePartMissingMessage(nullptr),
- m_konsolePart(nullptr),
- m_konsolePartCurrentDirectory(),
- m_sendCdToTerminalHistory(),
- m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"),
- QStringLiteral("/org/kde/KIOFuse"),
- QDBusConnection::sessionBus())
+TerminalPanel::TerminalPanel(QWidget *parent)
+ : Panel(parent)
+ , m_clearTerminal(true)
+ , m_mostLocalUrlJob(nullptr)
+ , m_layout(nullptr)
+ , m_terminal(nullptr)
+ , m_terminalWidget(nullptr)
+ , m_konsolePartMissingMessage(nullptr)
+ , m_konsolePart(nullptr)
+ , m_konsolePartCurrentDirectory()
+ , m_sendCdToTerminalHistory()
+ , m_kiofuseInterface(QStringLiteral("org.kde.KIOFuse"), QStringLiteral("/org/kde/KIOFuse"), QDBusConnection::sessionBus())
{
m_layout = new QVBoxLayout(this);
m_layout->setContentsMargins(0, 0, 0, 0);
bool TerminalPanel::isHiddenInVisibleWindow() const
{
- return parentWidget()
- && parentWidget()->isHidden();
+ return parentWidget() && parentWidget()->isHidden();
}
void TerminalPanel::dockVisibilityChanged()
// respond when e.g. Dolphin is minimized.
if (isHiddenInVisibleWindow() && m_terminal && !hasProgramRunning()) {
// Make sure that the following "cd /" command will not affect the view.
- disconnect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)),
- this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
+ disconnect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
// Make sure this terminal does not prevent unmounting any removable drives
changeDir(QUrl::fromLocalFile(QStringLiteral("/")));
return true;
}
-void TerminalPanel::showEvent(QShowEvent* event)
+void TerminalPanel::showEvent(QShowEvent *event)
{
if (event->spontaneous()) {
Panel::showEvent(event);
if (m_konsolePartMissingMessage) {
m_layout->removeWidget(m_konsolePartMissingMessage);
}
- m_terminal = qobject_cast<TerminalInterface*>(m_konsolePart);
+ m_terminal = qobject_cast<TerminalInterface *>(m_konsolePart);
// needed to collect the correct KonsolePart actionCollection
// namely the one of the single inner terminal and not the outer KonsolePart
} else if (!m_konsolePartMissingMessage) {
const auto konsoleInstallUrl = QUrl("appstream://org.kde.konsole.desktop");
- const auto konsoleNotInstalledText = i18n("Terminal cannot be shown because Konsole is not installed. "
- "Please install it and then reopen the panel.");
+ const auto konsoleNotInstalledText = i18n(
+ "Terminal cannot be shown because Konsole is not installed. "
+ "Please install it and then reopen the panel.");
m_konsolePartMissingMessage = new KMessageWidget(konsoleNotInstalledText, this);
m_konsolePartMissingMessage->setCloseButtonVisible(false);
m_konsolePartMissingMessage->hide();
}
if (m_terminal) {
m_terminal->showShellInDir(url().toLocalFile());
- if(!hasProgramRunning()) {
+ if (!hasProgramRunning()) {
changeDir(url());
}
m_terminalWidget->setFocus();
- connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)),
- this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
+ connect(m_konsolePart, SIGNAL(currentDirectoryChanged(QString)), this, SLOT(slotKonsolePartCurrentDirectoryChanged(QString)));
}
Panel::showEvent(event);
}
-void TerminalPanel::changeDir(const QUrl& url)
+void TerminalPanel::changeDir(const QUrl &url)
{
delete m_mostLocalUrlJob;
m_mostLocalUrlJob = nullptr;
sendCdToTerminalKIOFuse(url);
}
-void TerminalPanel::sendCdToTerminal(const QString& dir, HistoryPolicy addToHistory)
+void TerminalPanel::sendCdToTerminal(const QString &dir, HistoryPolicy addToHistory)
{
- if (dir == m_konsolePartCurrentDirectory // We are already there
+ if (dir == m_konsolePartCurrentDirectory // We are already there
&& m_sendCdToTerminalHistory.isEmpty() // …and that is not because the terminal couldn't keep up
) {
m_clearTerminal = false;
}
}
-void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url) {
+void TerminalPanel::sendCdToTerminalKIOFuse(const QUrl &url)
+{
// URL isn't local, only hope for the terminal to be in sync with the
// DolphinView is to mount the remote URL in KIOFuse and point to it.
// If we can't do that for any reason, silently fail.
auto reply = m_kiofuseInterface.mountUrl(url.toString());
- QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
- QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
+ QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
+ QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) {
watcher->deleteLater();
if (!reply.isError()) {
// Successfully mounted, point to the KIOFuse equivalent path.
});
}
-void TerminalPanel::slotMostLocalUrlResult(KJob* job)
+void TerminalPanel::slotMostLocalUrlResult(KJob *job)
{
- KIO::StatJob* statJob = static_cast<KIO::StatJob *>(job);
+ KIO::StatJob *statJob = static_cast<KIO::StatJob *>(job);
const QUrl url = statJob->mostLocalUrl();
if (url.isLocalFile()) {
sendCdToTerminal(url.toLocalFile());
m_mostLocalUrlJob = nullptr;
}
-void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString& dir)
+void TerminalPanel::slotKonsolePartCurrentDirectoryChanged(const QString &dir)
{
m_konsolePartCurrentDirectory = QDir(dir).canonicalPath();
}
auto reply = m_kiofuseInterface.remoteUrl(m_konsolePartCurrentDirectory);
- QDBusPendingCallWatcher * watcher = new QDBusPendingCallWatcher(reply, this);
- QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] (QDBusPendingCallWatcher* watcher) {
+ QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(reply, this);
+ QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, [=](QDBusPendingCallWatcher *watcher) {
watcher->deleteLater();
if (reply.isError()) {
// KIOFuse errored out... just show the normal URL
class QVBoxLayout;
class QWidget;
-namespace KIO {
- class StatJob;
+namespace KIO
+{
+class StatJob;
}
-namespace KParts {
- class ReadOnlyPart;
+namespace KParts
+{
+class ReadOnlyPart;
}
class KJob;
/**
Q_OBJECT
public:
- explicit TerminalPanel(QWidget* parent = nullptr);
+ explicit TerminalPanel(QWidget *parent = nullptr);
~TerminalPanel() override;
/**
/**
* Is emitted if the an URL change is requested.
*/
- void changeUrl(const QUrl& url);
+ void changeUrl(const QUrl &url);
protected:
bool urlChanged() override;
- void showEvent(QShowEvent* event) override;
+ void showEvent(QShowEvent *event) override;
private Q_SLOTS:
- void slotMostLocalUrlResult(KJob* job);
- void slotKonsolePartCurrentDirectoryChanged(const QString& dir);
+ void slotMostLocalUrlResult(KJob *job);
+ void slotKonsolePartCurrentDirectoryChanged(const QString &dir);
private:
- enum class HistoryPolicy {
- AddToHistory,
- SkipHistory
- };
+ enum class HistoryPolicy { AddToHistory, SkipHistory };
- void changeDir(const QUrl& url);
- void sendCdToTerminal(const QString& path, HistoryPolicy addToHistory = HistoryPolicy::AddToHistory);
+ void changeDir(const QUrl &url);
+ void sendCdToTerminal(const QString &path, HistoryPolicy addToHistory = HistoryPolicy::AddToHistory);
void sendCdToTerminalKIOFuse(const QUrl &url);
+
private:
bool m_clearTerminal;
- KIO::StatJob* m_mostLocalUrlJob;
+ KIO::StatJob *m_mostLocalUrlJob;
- QVBoxLayout* m_layout;
- TerminalInterface* m_terminal;
- QWidget* m_terminalWidget;
- KMessageWidget* m_konsolePartMissingMessage;
- KParts::ReadOnlyPart* m_konsolePart;
+ QVBoxLayout *m_layout;
+ TerminalInterface *m_terminal;
+ QWidget *m_terminalWidget;
+ KMessageWidget *m_konsolePartMissingMessage;
+ KParts::ReadOnlyPart *m_konsolePart;
QString m_konsolePartCurrentDirectory;
QQueue<QString> m_sendCdToTerminalHistory;
org::kde::KIOFuse::VFS m_kiofuseInterface;
#include <QMenu>
#include <QToolButton>
-DolphinFacetsWidget::DolphinFacetsWidget(QWidget* parent) :
- QWidget(parent),
- m_typeSelector(nullptr),
- m_dateSelector(nullptr),
- m_ratingSelector(nullptr),
- m_tagsSelector(nullptr)
+DolphinFacetsWidget::DolphinFacetsWidget(QWidget *parent)
+ : QWidget(parent)
+ , m_typeSelector(nullptr)
+ , m_dateSelector(nullptr)
+ , m_ratingSelector(nullptr)
+ , m_tagsSelector(nullptr)
{
m_typeSelector = new QComboBox(this);
m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("none")), i18nc("@item:inlistbox", "Any Type"), QString());
- m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("inode-directory")), i18nc("@item:inlistbox", "Folders") , QStringLiteral("Folder"));
- m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("text-x-generic")), i18nc("@item:inlistbox", "Documents") , QStringLiteral("Document"));
- m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("image-x-generic")), i18nc("@item:inlistbox", "Images") , QStringLiteral("Image"));
+ m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("inode-directory")), i18nc("@item:inlistbox", "Folders"), QStringLiteral("Folder"));
+ m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("text-x-generic")), i18nc("@item:inlistbox", "Documents"), QStringLiteral("Document"));
+ m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("image-x-generic")), i18nc("@item:inlistbox", "Images"), QStringLiteral("Image"));
m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("audio-x-generic")), i18nc("@item:inlistbox", "Audio Files"), QStringLiteral("Audio"));
- m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("video-x-generic")), i18nc("@item:inlistbox", "Videos") , QStringLiteral("Video"));
+ m_typeSelector->addItem(QIcon::fromTheme(QStringLiteral("video-x-generic")), i18nc("@item:inlistbox", "Videos"), QStringLiteral("Video"));
initComboBox(m_typeSelector);
const QDate currentDate = QDate::currentDate();
m_dateSelector = new QComboBox(this);
m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar")), i18nc("@item:inlistbox", "Any Date"), QDate());
- m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Today") , currentDate);
- m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Yesterday") , currentDate.addDays(-1));
- m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-week")), i18nc("@item:inlistbox", "This Week") , currentDate.addDays(1 - currentDate.dayOfWeek()));
- m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-month")), i18nc("@item:inlistbox", "This Month"), currentDate.addDays(1 - currentDate.day()));
- m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-year")), i18nc("@item:inlistbox", "This Year") , currentDate.addDays(1 - currentDate.dayOfYear()));
+ m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Today"), currentDate);
+ m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("go-jump-today")), i18nc("@item:inlistbox", "Yesterday"), currentDate.addDays(-1));
+ m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-week")),
+ i18nc("@item:inlistbox", "This Week"),
+ currentDate.addDays(1 - currentDate.dayOfWeek()));
+ m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-month")),
+ i18nc("@item:inlistbox", "This Month"),
+ currentDate.addDays(1 - currentDate.day()));
+ m_dateSelector->addItem(QIcon::fromTheme(QStringLiteral("view-calendar-year")),
+ i18nc("@item:inlistbox", "This Year"),
+ currentDate.addDays(1 - currentDate.dayOfYear()));
initComboBox(m_dateSelector);
m_ratingSelector = new QComboBox(this);
connect(&m_tagsLister, &KCoreDirLister::itemsAdded, this, &DolphinFacetsWidget::updateTagsMenuItems);
updateTagsMenu();
- QHBoxLayout* topLayout = new QHBoxLayout(this);
+ QHBoxLayout *topLayout = new QHBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
topLayout->addWidget(m_typeSelector);
topLayout->addWidget(m_dateSelector);
return m_typeSelector->currentData().toString();
}
-bool DolphinFacetsWidget::isSearchTerm(const QString& term) const
+bool DolphinFacetsWidget::isSearchTerm(const QString &term) const
{
- static const QLatin1String searchTokens[] {
- QLatin1String("modified>="),
- QLatin1String("rating>="),
- QLatin1String("tag:"), QLatin1String("tag=")
- };
+ static const QLatin1String searchTokens[]{QLatin1String("modified>="), QLatin1String("rating>="), QLatin1String("tag:"), QLatin1String("tag=")};
for (const auto &searchToken : searchTokens) {
if (term.startsWith(searchToken)) {
return false;
}
-void DolphinFacetsWidget::setSearchTerm(const QString& term)
+void DolphinFacetsWidget::setSearchTerm(const QString &term)
{
if (term.startsWith(QLatin1String("modified>="))) {
const QString value = term.mid(10);
const QString value = term.mid(8);
const int stars = value.toInt() / 2;
setRating(stars);
- } else if (term.startsWith(QLatin1String("tag:")) ||
- term.startsWith(QLatin1String("tag="))) {
+ } else if (term.startsWith(QLatin1String("tag:")) || term.startsWith(QLatin1String("tag="))) {
const QString value = term.mid(4);
addSearchTag(value);
}
}
-void DolphinFacetsWidget::setFacetType(const QString& type)
+void DolphinFacetsWidget::setFacetType(const QString &type)
{
for (int index = 0; index <= m_typeSelector->count(); index++) {
if (type == m_typeSelector->itemData(index).toString()) {
m_ratingSelector->setCurrentIndex(stars);
}
-void DolphinFacetsWidget::setTimespan(const QDate& date)
+void DolphinFacetsWidget::setTimespan(const QDate &date)
{
if (!date.isValid()) {
return;
}
}
-void DolphinFacetsWidget::addSearchTag(const QString& tag)
+void DolphinFacetsWidget::addSearchTag(const QString &tag)
{
if (tag.isEmpty() || m_searchTags.contains(tag)) {
return;
updateTagsSelector();
}
-void DolphinFacetsWidget::removeSearchTag(const QString& tag)
+void DolphinFacetsWidget::removeSearchTag(const QString &tag)
{
if (tag.isEmpty() || !m_searchTags.contains(tag)) {
return;
updateTagsMenu();
}
-void DolphinFacetsWidget::initComboBox(QComboBox* combo)
+void DolphinFacetsWidget::initComboBox(QComboBox *combo)
{
combo->setFrame(false);
combo->setMinimumHeight(parentWidget()->height());
if (hasSelectedTags) {
const QString tagsText = m_searchTags.join(i18nc("String list separator", ", "));
- m_tagsSelector->setText(i18ncp("@action:button %2 is a list of tags",
- "Tag: %2", "Tags: %2",m_searchTags.count(), tagsText));
+ m_tagsSelector->setText(i18ncp("@action:button %2 is a list of tags", "Tag: %2", "Tags: %2", m_searchTags.count(), tagsText));
} else {
m_tagsSelector->setText(i18nc("@action:button", "Add Tags"));
}
}
}
-void DolphinFacetsWidget::updateTagsMenuItems(const QUrl&, const KFileItemList& items)
+void DolphinFacetsWidget::updateTagsMenuItems(const QUrl &, const KFileItemList &items)
{
QMenu *tagsMenu = m_tagsSelector->menu();
tagsMenu->clear();
QStringList allTags = QStringList(m_searchTags);
- for (const KFileItem &item: items) {
+ for (const KFileItem &item : items) {
allTags.append(item.name());
}
allTags.sort(Qt::CaseInsensitive);
const bool onlyOneTag = allTags.count() == 1;
- for (const QString& tagName : qAsConst(allTags)) {
+ for (const QString &tagName : qAsConst(allTags)) {
QAction *action = tagsMenu->addAction(QIcon::fromTheme(QStringLiteral("tag")), tagName);
action->setCheckable(true);
action->setChecked(m_searchTags.contains(tagName));
#ifndef DOLPHINFACETSWIDGET_H
#define DOLPHINFACETSWIDGET_H
-#include <QWidget>
#include <KCoreDirLister>
+#include <QWidget>
class QComboBox;
class QDate;
Q_OBJECT
public:
- explicit DolphinFacetsWidget(QWidget* parent = nullptr);
+ explicit DolphinFacetsWidget(QWidget *parent = nullptr);
~DolphinFacetsWidget() override;
QStringList searchTerms() const;
QString facetType() const;
- bool isSearchTerm(const QString& term) const;
- void setSearchTerm(const QString& term);
+ bool isSearchTerm(const QString &term) const;
+ void setSearchTerm(const QString &term);
void resetSearchTerms();
- void setFacetType(const QString& type);
+ void setFacetType(const QString &type);
Q_SIGNALS:
void facetChanged();
protected:
- void changeEvent(QEvent* event) override;
+ void changeEvent(QEvent *event) override;
private Q_SLOTS:
void updateTagsMenu();
- void updateTagsMenuItems(const QUrl&, const KFileItemList& items);
+ void updateTagsMenuItems(const QUrl &, const KFileItemList &items);
private:
void setRating(const int stars);
- void setTimespan(const QDate& date);
- void addSearchTag(const QString& tag);
- void removeSearchTag(const QString& tag);
+ void setTimespan(const QDate &date);
+ void addSearchTag(const QString &tag);
+ void removeSearchTag(const QString &tag);
void resetSearchTags();
- void initComboBox(QComboBox* combo);
+ void initComboBox(QComboBox *combo);
void updateTagsSelector();
private:
- QComboBox* m_typeSelector;
- QComboBox* m_dateSelector;
- QComboBox* m_ratingSelector;
- QToolButton* m_tagsSelector;
+ QComboBox *m_typeSelector;
+ QComboBox *m_dateSelector;
+ QComboBox *m_ratingSelector;
+ QToolButton *m_tagsSelector;
QStringList m_searchTags;
KCoreDirLister m_tagsLister;
#include <Baloo/Query>
#endif
-namespace {
+namespace
+{
#if HAVE_BALOO
- /** Checks if a given term in the Baloo::Query::searchString() is a special search term
- * @return: the specific search token of the term, or an empty QString() if none is found
- */
- QString searchTermToken(const QString& term)
- {
- static const QLatin1String searchTokens[] {
- QLatin1String("filename:"),
- QLatin1String("modified>="),
- QLatin1String("rating>="),
- QLatin1String("tag:"), QLatin1String("tag=")
- };
-
- for (const auto &searchToken : searchTokens) {
- if (term.startsWith(searchToken)) {
- return searchToken;
- }
+/** Checks if a given term in the Baloo::Query::searchString() is a special search term
+ * @return: the specific search token of the term, or an empty QString() if none is found
+ */
+QString searchTermToken(const QString &term)
+{
+ static const QLatin1String searchTokens[]{QLatin1String("filename:"),
+ QLatin1String("modified>="),
+ QLatin1String("rating>="),
+ QLatin1String("tag:"),
+ QLatin1String("tag=")};
+
+ for (const auto &searchToken : searchTokens) {
+ if (term.startsWith(searchToken)) {
+ return searchToken;
}
- return QString();
}
+ return QString();
+}
- QString stripQuotes(const QString& text)
- {
- if (text.length() >= 2 && text.at(0) == QLatin1Char('"')
- && text.back() == QLatin1Char('"')) {
- return text.mid(1, text.size() - 2);
- }
- return text;
+QString stripQuotes(const QString &text)
+{
+ if (text.length() >= 2 && text.at(0) == QLatin1Char('"') && text.back() == QLatin1Char('"')) {
+ return text.mid(1, text.size() - 2);
}
+ return text;
+}
- QStringList splitOutsideQuotes(const QString& text)
- {
- // Match groups on 3 possible conditions:
- // - Groups with two leading quotes must close both on them (filename:""abc xyz" tuv")
- // - Groups enclosed in quotes
- // - Words separated by spaces
- const QRegularExpression subTermsRegExp("(\\S*?\"\"[^\"]+\"[^\"]+\"+|\\S*?\"[^\"]+\"+|(?<=\\s|^)\\S+(?=\\s|$))");
- auto subTermsMatchIterator = subTermsRegExp.globalMatch(text);
-
- QStringList textParts;
- while (subTermsMatchIterator.hasNext()) {
- textParts << subTermsMatchIterator.next().captured(0);
- }
- return textParts;
+QStringList splitOutsideQuotes(const QString &text)
+{
+ // Match groups on 3 possible conditions:
+ // - Groups with two leading quotes must close both on them (filename:""abc xyz" tuv")
+ // - Groups enclosed in quotes
+ // - Words separated by spaces
+ const QRegularExpression subTermsRegExp("(\\S*?\"\"[^\"]+\"[^\"]+\"+|\\S*?\"[^\"]+\"+|(?<=\\s|^)\\S+(?=\\s|$))");
+ auto subTermsMatchIterator = subTermsRegExp.globalMatch(text);
+
+ QStringList textParts;
+ while (subTermsMatchIterator.hasNext()) {
+ textParts << subTermsMatchIterator.next().captured(0);
}
+ return textParts;
+}
#endif
- QString trimChar(const QString& text, const QLatin1Char aChar)
- {
- const int start = text.startsWith(aChar) ? 1 : 0;
- const int end = (text.length() > 1 && text.endsWith(aChar)) ? 1 : 0;
+QString trimChar(const QString &text, const QLatin1Char aChar)
+{
+ const int start = text.startsWith(aChar) ? 1 : 0;
+ const int end = (text.length() > 1 && text.endsWith(aChar)) ? 1 : 0;
- return text.mid(start, text.length() - start - end);
- }
+ return text.mid(start, text.length() - start - end);
+}
}
-
-DolphinQuery DolphinQuery::fromSearchUrl(const QUrl& searchUrl)
+DolphinQuery DolphinQuery::fromSearchUrl(const QUrl &searchUrl)
{
DolphinQuery model;
model.m_searchUrl = searchUrl;
return model;
}
-bool DolphinQuery::supportsScheme(const QString& urlScheme)
+bool DolphinQuery::supportsScheme(const QString &urlScheme)
{
static const QStringList supportedSchemes = {
QStringLiteral("baloosearch"),
QString fileName;
const QStringList subTerms = splitOutsideQuotes(query.searchString());
- for (const QString& subTerm : subTerms) {
+ for (const QString &subTerm : subTerms) {
const QString token = searchTermToken(subTerm);
const QString value = stripQuotes(subTerm.mid(token.length()));
#endif
}
-
QUrl DolphinQuery::searchUrl() const
{
return m_searchUrl;
{
public:
/** Parses the components of @p searchUrl for the supported schemes */
- static DolphinQuery fromSearchUrl(const QUrl& searchUrl);
+ static DolphinQuery fromSearchUrl(const QUrl &searchUrl);
/** Checks whether the DolphinQuery supports the given @p urlScheme */
- static bool supportsScheme(const QString& urlScheme);
+ static bool supportsScheme(const QString &urlScheme);
/** @return the \a searchUrl passed to Baloo::Query::fromSearchUrl() */
QUrl searchUrl() const;
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-#include "global.h"
#include "dolphinsearchbox.h"
+#include "global.h"
#include "dolphin_searchsettings.h"
#include "dolphinfacetswidget.h"
#include "dolphinplacesmodelsingleton.h"
#include "dolphinquery.h"
+#include "config-dolphin.h"
#include <KLocalizedString>
#include <KMoreToolsMenuFactory>
#include <KSeparator>
-#include "config-dolphin.h"
#if HAVE_BALOO
-#include <Baloo/Query>
#include <Baloo/IndexerConfig>
+#include <Baloo/Query>
#endif
#include <QButtonGroup>
#include <QToolButton>
#include <QUrlQuery>
-DolphinSearchBox::DolphinSearchBox(QWidget* parent) :
- QWidget(parent),
- m_startedSearching(false),
- m_active(true),
- m_topLayout(nullptr),
- m_searchInput(nullptr),
- m_saveSearchAction(nullptr),
- m_optionsScrollArea(nullptr),
- m_fileNameButton(nullptr),
- m_contentButton(nullptr),
- m_separator(nullptr),
- m_fromHereButton(nullptr),
- m_everywhereButton(nullptr),
- m_facetsWidget(nullptr),
- m_searchPath(),
- m_startSearchTimer(nullptr)
+DolphinSearchBox::DolphinSearchBox(QWidget *parent)
+ : QWidget(parent)
+ , m_startedSearching(false)
+ , m_active(true)
+ , m_topLayout(nullptr)
+ , m_searchInput(nullptr)
+ , m_saveSearchAction(nullptr)
+ , m_optionsScrollArea(nullptr)
+ , m_fileNameButton(nullptr)
+ , m_contentButton(nullptr)
+ , m_separator(nullptr)
+ , m_fromHereButton(nullptr)
+ , m_everywhereButton(nullptr)
+ , m_facetsWidget(nullptr)
+ , m_searchPath()
+ , m_startSearchTimer(nullptr)
{
}
saveSettings();
}
-void DolphinSearchBox::setText(const QString& text)
+void DolphinSearchBox::setText(const QString &text)
{
m_searchInput->setText(text);
}
return m_searchInput->text();
}
-void DolphinSearchBox::setSearchPath(const QUrl& url)
+void DolphinSearchBox::setSearchPath(const QUrl &url)
{
if (url == m_searchPath) {
return;
return url;
}
-void DolphinSearchBox::fromSearchUrl(const QUrl& url)
+void DolphinSearchBox::fromSearchUrl(const QUrl &url)
{
if (DolphinQuery::supportsScheme(url.scheme())) {
const DolphinQuery query = DolphinQuery::fromSearchUrl(url);
return m_active;
}
-bool DolphinSearchBox::event(QEvent* event)
+bool DolphinSearchBox::event(QEvent *event)
{
if (event->type() == QEvent::Polish) {
init();
return QWidget::event(event);
}
-void DolphinSearchBox::showEvent(QShowEvent* event)
+void DolphinSearchBox::showEvent(QShowEvent *event)
{
if (!event->spontaneous()) {
m_searchInput->setFocus();
}
}
-void DolphinSearchBox::hideEvent(QHideEvent* event)
+void DolphinSearchBox::hideEvent(QHideEvent *event)
{
Q_UNUSED(event)
m_startedSearching = false;
m_startSearchTimer->stop();
}
-void DolphinSearchBox::keyReleaseEvent(QKeyEvent* event)
+void DolphinSearchBox::keyReleaseEvent(QKeyEvent *event)
{
QWidget::keyReleaseEvent(event);
if (event->key() == Qt::Key_Escape) {
} else {
m_searchInput->clear();
}
- }
- else if (event->key() == Qt::Key_Down) {
+ } else if (event->key() == Qt::Key_Down) {
Q_EMIT focusViewRequest();
}
}
-bool DolphinSearchBox::eventFilter(QObject* obj, QEvent* event)
+bool DolphinSearchBox::eventFilter(QObject *obj, QEvent *event)
{
switch (event->type()) {
case QEvent::FocusIn:
}
}
-void DolphinSearchBox::slotSearchTextChanged(const QString& text)
+void DolphinSearchBox::slotSearchTextChanged(const QString &text)
{
-
if (text.isEmpty()) {
m_startSearchTimer->stop();
} else {
}
}
-void DolphinSearchBox::initButton(QToolButton* button)
+void DolphinSearchBox::initButton(QToolButton *button)
{
button->installEventFilter(this);
button->setAutoExclusive(true);
m_searchInput->installEventFilter(this);
m_searchInput->setClearButtonEnabled(true);
m_searchInput->setFont(QFontDatabase::systemFont(QFontDatabase::GeneralFont));
- connect(m_searchInput, &QLineEdit::returnPressed,
- this, &DolphinSearchBox::slotReturnPressed);
- connect(m_searchInput, &QLineEdit::textChanged,
- this, &DolphinSearchBox::slotSearchTextChanged);
+ connect(m_searchInput, &QLineEdit::returnPressed, this, &DolphinSearchBox::slotReturnPressed);
+ connect(m_searchInput, &QLineEdit::textChanged, this, &DolphinSearchBox::slotSearchTextChanged);
setFocusProxy(m_searchInput);
// Add "Save search" button inside search box
m_saveSearchAction = new QAction(this);
- m_saveSearchAction->setIcon (QIcon::fromTheme(QStringLiteral("document-save-symbolic")));
+ m_saveSearchAction->setIcon(QIcon::fromTheme(QStringLiteral("document-save-symbolic")));
m_saveSearchAction->setText(i18nc("action:button", "Save this search to quickly access it again in the future"));
m_saveSearchAction->setEnabled(false);
m_searchInput->addAction(m_saveSearchAction, QLineEdit::TrailingPosition);
connect(m_saveSearchAction, &QAction::triggered, this, &DolphinSearchBox::slotSearchSaved);
// Create close button
- QToolButton* closeButton = new QToolButton(this);
+ QToolButton *closeButton = new QToolButton(this);
closeButton->setAutoRaise(true);
closeButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close")));
closeButton->setToolTip(i18nc("@info:tooltip", "Quit searching"));
connect(closeButton, &QToolButton::clicked, this, &DolphinSearchBox::emitCloseRequest);
// Apply layout for the search input
- QHBoxLayout* searchInputLayout = new QHBoxLayout();
+ QHBoxLayout *searchInputLayout = new QHBoxLayout();
searchInputLayout->setContentsMargins(0, 0, 0, 0);
searchInputLayout->addWidget(m_searchInput);
searchInputLayout->addWidget(closeButton);
m_contentButton->setText(i18nc("action:button", "Content"));
initButton(m_contentButton);
- QButtonGroup* searchWhatGroup = new QButtonGroup(this);
+ QButtonGroup *searchWhatGroup = new QButtonGroup(this);
searchWhatGroup->addButton(m_fileNameButton);
searchWhatGroup->addButton(m_contentButton);
m_everywhereButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
initButton(m_everywhereButton);
- QButtonGroup* searchLocationGroup = new QButtonGroup(this);
+ QButtonGroup *searchLocationGroup = new QButtonGroup(this);
searchLocationGroup->addButton(m_fromHereButton);
searchLocationGroup->addButton(m_everywhereButton);
moreSearchToolsButton->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
moreSearchToolsButton->setText(i18n("More Search Tools"));
moreSearchToolsButton->setMenu(new QMenu(this));
- connect(moreSearchToolsButton->menu(), &QMenu::aboutToShow, moreSearchToolsButton->menu(), [this, moreSearchToolsButton]()
- {
+ connect(moreSearchToolsButton->menu(), &QMenu::aboutToShow, moreSearchToolsButton->menu(), [this, moreSearchToolsButton]() {
m_menuFactory.reset(new KMoreToolsMenuFactory("dolphin/search-tools"));
moreSearchToolsButton->menu()->clear();
- m_menuFactory->fillMenuFromGroupingNames(moreSearchToolsButton->menu(), { "files-find" }, this->m_searchPath);
- } );
+ m_menuFactory->fillMenuFromGroupingNames(moreSearchToolsButton->menu(), {"files-find"}, this->m_searchPath);
+ });
// Create "Facets" widget
m_facetsWidget = new DolphinFacetsWidget(this);
// Put the options into a QScrollArea. This prevents increasing the view width
// in case that not enough width for the options is available.
- QWidget* optionsContainer = new QWidget(this);
+ QWidget *optionsContainer = new QWidget(this);
// Apply layout for the options
- QHBoxLayout* optionsLayout = new QHBoxLayout(optionsContainer);
+ QHBoxLayout *optionsLayout = new QHBoxLayout(optionsContainer);
optionsLayout->setContentsMargins(0, 0, 0, 0);
optionsLayout->setSpacing(Dolphin::LAYOUT_SPACING_SMALL);
optionsLayout->addWidget(m_fileNameButton);
connect(m_startSearchTimer, &QTimer::timeout, this, &DolphinSearchBox::emitSearchRequest);
}
-QString DolphinSearchBox::queryTitle(const QString& text) const
+QString DolphinSearchBox::queryTitle(const QString &text) const
{
- return i18nc("@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.",
- "Query Results from '%1'", text);
+ return i18nc("@title UDS_DISPLAY_NAME for a KIO directory listing. %1 is the query the user entered.", "Query Results from '%1'", text);
}
QUrl DolphinSearchBox::balooUrlForSearching() const
#endif
}
-void DolphinSearchBox::updateFromQuery(const DolphinQuery& query)
+void DolphinSearchBox::updateFromQuery(const DolphinQuery &query)
{
// Block all signals to avoid unnecessary "searchRequest" signals
// while we adjust the search text and the facet widget.
if (query.hasContentSearch()) {
m_contentButton->setChecked(true);
- } else if (query.hasFileName()) {
+ } else if (query.hasFileName()) {
m_fileNameButton->setChecked(true);
}
m_facetsWidget->resetSearchTerms();
m_facetsWidget->setFacetType(query.type());
const QStringList searchTerms = query.searchTerms();
- for (const QString& searchTerm : searchTerms) {
+ for (const QString &searchTerm : searchTerms) {
m_facetsWidget->setSearchTerm(searchTerm);
}
* If Baloo is available and the current folder is indexed, further
* options are offered.
*/
-class DolphinSearchBox : public QWidget {
+class DolphinSearchBox : public QWidget
+{
Q_OBJECT
public:
- explicit DolphinSearchBox(QWidget* parent = nullptr);
+ explicit DolphinSearchBox(QWidget *parent = nullptr);
~DolphinSearchBox() override;
/**
* Sets the text that should be used as input for
* searching.
*/
- void setText(const QString& text);
+ void setText(const QString &text);
/**
* Returns the text that should be used as input
* Sets the current path that is used as root for searching files.
* If @url is the Home dir, "From Here" is selected instead.
*/
- void setSearchPath(const QUrl& url);
+ void setSearchPath(const QUrl &url);
QUrl searchPath() const;
/** @return URL that will start the searching of files. */
* Extracts information from the given search \a url to
* initialize the search box properly.
*/
- void fromSearchUrl(const QUrl& url);
+ void fromSearchUrl(const QUrl &url);
/**
* Selects the whole text of the search box.
bool isActive() const;
protected:
- bool event(QEvent* event) override;
- void showEvent(QShowEvent* event) override;
- void hideEvent(QHideEvent* event) override;
- void keyReleaseEvent(QKeyEvent* event) override;
- bool eventFilter(QObject* obj, QEvent* event) override;
+ bool event(QEvent *event) override;
+ void showEvent(QShowEvent *event) override;
+ void hideEvent(QHideEvent *event) override;
+ void keyReleaseEvent(QKeyEvent *event) override;
+ bool eventFilter(QObject *obj, QEvent *event) override;
Q_SIGNALS:
/**
* Is emitted when the user has changed a character of
* the text that should be used as input for searching.
*/
- void searchTextChanged(const QString& text);
+ void searchTextChanged(const QString &text);
/**
* Emitted as soon as the search box should get closed.
void emitSearchRequest();
void emitCloseRequest();
void slotConfigurationChanged();
- void slotSearchTextChanged(const QString& text);
+ void slotSearchTextChanged(const QString &text);
void slotReturnPressed();
void slotFacetChanged();
void slotSearchSaved();
private:
- void initButton(QToolButton* button);
+ void initButton(QToolButton *button);
void loadSettings();
void saveSettings();
void init();
/**
* Sets the searchbox UI with the parameters established by the \a query
*/
- void updateFromQuery(const DolphinQuery& query);
+ void updateFromQuery(const DolphinQuery &query);
void updateFacetsVisible();
bool isIndexingEnabled() const;
private:
- QString queryTitle(const QString& text) const;
+ QString queryTitle(const QString &text) const;
bool m_startedSearching;
bool m_active;
- QVBoxLayout* m_topLayout;
+ QVBoxLayout *m_topLayout;
- QLineEdit* m_searchInput;
- QAction* m_saveSearchAction;
- QScrollArea* m_optionsScrollArea;
- QToolButton* m_fileNameButton;
- QToolButton* m_contentButton;
- KSeparator* m_separator;
- QToolButton* m_fromHereButton;
- QToolButton* m_everywhereButton;
- DolphinFacetsWidget* m_facetsWidget;
+ QLineEdit *m_searchInput;
+ QAction *m_saveSearchAction;
+ QScrollArea *m_optionsScrollArea;
+ QToolButton *m_fileNameButton;
+ QToolButton *m_contentButton;
+ KSeparator *m_separator;
+ QToolButton *m_fromHereButton;
+ QToolButton *m_everywhereButton;
+ DolphinFacetsWidget *m_facetsWidget;
QUrl m_searchPath;
QScopedPointer<KMoreToolsMenuFactory> m_menuFactory;
- QTimer* m_startSearchTimer;
+ QTimer *m_startSearchTimer;
};
#endif
using namespace SelectionMode;
-ActionTextHelper::ActionTextHelper(QObject *parent) :
- QObject(parent)
-{ }
+ActionTextHelper::ActionTextHelper(QObject *parent)
+ : QObject(parent)
+{
+}
void ActionTextHelper::registerTextWhenNothingIsSelected(QAction *action, QString registeredText)
{
void textsWhenNothingIsSelectedEnabled(bool enabled);
private:
- enum TextState {
- TextWhenNothingIsSelected,
- TextWhenSomethingIsSelected
- };
+ enum TextState { TextWhenNothingIsSelected, TextWhenSomethingIsSelected };
/**
* Utility struct to allow switching back and forth between registered actions showing their
* An example is "Copy" or "Copy…". The latter one is used when nothing is selected and signifies
* that it will trigger SelectionMode so items can be selected and then copied.
*/
- struct RegisteredActionTextChange {
+ struct RegisteredActionTextChange {
QPointer<QAction> action;
QString registeredText;
TextState textStateOfRegisteredText;
- RegisteredActionTextChange(QAction *action, QString registeredText, TextState state) :
- action{action},
- registeredText{registeredText},
- textStateOfRegisteredText{state}
- { };
+ RegisteredActionTextChange(QAction *action, QString registeredText, TextState state)
+ : action{action}
+ , registeredText{registeredText}
+ , textStateOfRegisteredText{state} {};
};
/**
using namespace SelectionMode;
-ActionWithWidget::ActionWithWidget(QAction *action) :
- m_action{action}
-{ }
+ActionWithWidget::ActionWithWidget(QAction *action)
+ : m_action{action}
+{
+}
-ActionWithWidget::ActionWithWidget(QAction *action, QAbstractButton *button) :
- m_action{action},
- m_widget{button}
+ActionWithWidget::ActionWithWidget(QAction *action, QAbstractButton *button)
+ : m_action{action}
+ , m_widget{button}
{
copyActionDataToButton(button, action);
}
ActionWithWidget(QAction *action, QAbstractButton *button);
/** @returns the action of this object. */
- inline QAction *action() {
+ inline QAction *action()
+ {
Q_CHECK_PTR(m_action);
return m_action;
};
/** @returns the widget of this object. */
- inline QWidget *widget() {
+ inline QWidget *widget()
+ {
return m_widget;
}
QWidget *newWidget(QWidget *parent);
/** returns true if the widget exists and is visible. false otherwise. */
- inline bool isWidgetVisible() const {
+ inline bool isWidgetVisible() const
+ {
return m_widget && m_widget->isVisible();
};
return s_instance;
}
-
void setBackgroundColorForWidget(QWidget *widget, QColor color)
{
QPalette palette;
- palette.setBrush(QPalette::Active, QPalette::Window, color);
+ palette.setBrush(QPalette::Active, QPalette::Window, color);
palette.setBrush(QPalette::Inactive, QPalette::Window, color);
palette.setBrush(QPalette::Disabled, QPalette::Window, color);
widget->setAutoFillBackground(true);
{
setBackgroundColorForWidget(widget, m_backgroundColor);
- Q_ASSERT_X(std::find(m_colorControlledWidgets.begin(), m_colorControlledWidgets.end(), widget) == m_colorControlledWidgets.end(), "controlBackgroundColor",
+ Q_ASSERT_X(std::find(m_colorControlledWidgets.begin(), m_colorControlledWidgets.end(), widget) == m_colorControlledWidgets.end(),
+ "controlBackgroundColor",
"Duplicate insertion is not necessary because the background color should already automatically update itself on paletteChanged");
m_colorControlledWidgets.emplace_back(widget);
}
BackgroundColorHelper::BackgroundColorHelper()
{
updateBackgroundColor();
- QObject::connect(qApp, &QGuiApplication::paletteChanged, [=](){ slotPaletteChanged(); });
+ QObject::connect(qApp, &QGuiApplication::paletteChanged, [=]() {
+ slotPaletteChanged();
+ });
}
void BackgroundColorHelper::slotPaletteChanged()
if (std::abs(hueDifference) > 80) {
newHue = (activeBackgroundColor.hue() + positiveBackgroundColor.hue()) / 2;
} else {
- newHue = hueDifference > 0 ?
- activeBackgroundColor.hue() + 40 :
- activeBackgroundColor.hue() - 40;
+ newHue = hueDifference > 0 ? activeBackgroundColor.hue() + 40 : activeBackgroundColor.hue() - 40;
newHue %= 360; // hue needs to be between 0 and 359 per Qt documentation.
}
#include "bottombar.h"
-#include "bottombarcontentscontainer.h"
#include "backgroundcolorhelper.h"
+#include "bottombarcontentscontainer.h"
#include <QGridLayout>
#include <QResizeEvent>
using namespace SelectionMode;
-BottomBar::BottomBar(KActionCollection *actionCollection, QWidget *parent) :
- QWidget{parent}
+BottomBar::BottomBar(KActionCollection *actionCollection, QWidget *parent)
+ : QWidget{parent}
{
// Showing of this widget is normally animated. We hide it for now and make it small.
hide();
m_scrollArea->setWidget(m_contentsContainer);
m_contentsContainer->installEventFilter(this); // Adjusts the height of this bar to the height of the contentsContainer
connect(m_contentsContainer, &BottomBarContentsContainer::error, this, &BottomBar::error);
- connect(m_contentsContainer, &BottomBarContentsContainer::barVisibilityChangeRequested, this, [this](bool visible){
+ connect(m_contentsContainer, &BottomBarContentsContainer::barVisibilityChangeRequested, this, [this](bool visible) {
if (!m_allowedToBeVisible && visible) {
return;
}
m_heightAnimation->stop(); // deletes because of QAbstractAnimation::DeleteWhenStopped.
}
m_heightAnimation = new QPropertyAnimation(this, "maximumHeight");
- m_heightAnimation->setDuration(2 *
- style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) *
- GlobalConfig::animationDurationFactor());
+ m_heightAnimation->setDuration(2 * style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * GlobalConfig::animationDurationFactor());
m_heightAnimation->setStartValue(height());
m_heightAnimation->setEasingCurve(QEasingCurve::OutCubic);
if (visible) {
show();
m_heightAnimation->setEndValue(sizeHint().height());
- connect(m_heightAnimation, &QAbstractAnimation::finished,
- this, [this](){ setMaximumHeight(sizeHint().height()); });
+ connect(m_heightAnimation, &QAbstractAnimation::finished, this, [this]() {
+ setMaximumHeight(sizeHint().height());
+ });
} else {
m_heightAnimation->setEndValue(0);
- connect(m_heightAnimation, &QAbstractAnimation::finished,
- this, &QWidget::hide);
+ connect(m_heightAnimation, &QAbstractAnimation::finished, this, &QWidget::hide);
}
m_heightAnimation->start(QAbstractAnimation::DeleteWhenStopped);
namespace SelectionMode
{
- class BottomBarContentsContainer;
+class BottomBarContentsContainer;
/**
* @brief A bar used in selection mode that serves various purposes depending on what the user is currently trying to do.
using namespace SelectionMode;
-BottomBarContentsContainer::BottomBarContentsContainer(KActionCollection *actionCollection, QWidget *parent) :
- QWidget{parent},
- m_actionCollection{actionCollection}
+BottomBarContentsContainer::BottomBarContentsContainer(KActionCollection *actionCollection, QWidget *parent)
+ : QWidget{parent}
+ , m_actionCollection{actionCollection}
{
// We will mostly interact with m_layout when changing the contents and not care about the other internal hierarchy.
m_layout = new QHBoxLayout(this);
emptyBarContents();
// A label is added in many of the methods below. We only know its size a bit later and if it should be hidden.
- QTimer::singleShot(10, this, [this](){ updateExplanatoryLabelVisibility(); });
+ QTimer::singleShot(10, this, [this]() {
+ updateExplanatoryLabelVisibility();
+ });
Q_CHECK_PTR(m_actionCollection);
m_contents = contents;
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to copy files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Copying"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to copy the location of files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Copying"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
void BottomBarContentsContainer::addCopyToOtherViewContents()
{
+ // clang-format off
// i18n: "Copy over" refers to copying to the other split view area that is currently visible to the user.
m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be copied over."), this);
+ // clang-format on
m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to copy the location of files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Copying"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to cut files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Cutting"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
// Connect the cut action as a second step.
m_mainAction = ActionWithWidget(m_actionCollection->action(KStandardAction::name(KStandardAction::Cut)), cutButton);
// Finally connect the lambda that actually changes the contents to the PasteContents.
- connect(cutButton, &QAbstractButton::clicked, [this](){
+ connect(cutButton, &QAbstractButton::clicked, [this]() {
if (GeneralSettings::showPasteBarAfterCopying()) {
resetContents(BottomBar::Contents::PasteContents); // resetContents() needs to be connected last because
// it instantly deletes the button and then the other slots won't be called.
void BottomBarContentsContainer::addDeleteContents()
{
- m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be permanently deleted."), this);
+ m_explanatoryLabel =
+ new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be permanently deleted."), this);
m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to delete files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to duplicate files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Duplicating"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
void BottomBarContentsContainer::addGeneralContents()
{
if (!m_overflowButton) {
+ // clang-format off
// i18n: This button appears in a bar if there isn't enough horizontal space to fit all the other buttons so please keep it short.
// The small button opens a menu that contains the actions that didn't fit on the bar.
m_overflowButton = new QPushButton{QIcon::fromTheme(QStringLiteral("view-more-symbolic")), i18nc("@action keep short", "More"), this};
+ // clang-format on
m_overflowButton->setMenu(new QMenu{m_overflowButton});
m_overflowButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::MinimumExpanding); // Makes sure it has the same height as the labeled buttons.
m_layout->addWidget(m_overflowButton);
void BottomBarContentsContainer::addMoveToOtherViewContents()
{
+ // clang-format off
// i18n: "Move over" refers to moving to the other split view area that is currently visible to the user.
m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be moved over."), this);
+ // clang-format on
m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to copy the location of files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Moving"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
void BottomBarContentsContainer::addMoveToTrashContents()
{
- m_explanatoryLabel = new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be moved to the Trash."), this);
+ m_explanatoryLabel =
+ new QLabel(i18nc("@info explaining the next step in a process", "Select the files and folders that should be moved to the Trash."), this);
m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process of moving files to the trash by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
void BottomBarContentsContainer::addPasteContents()
{
m_explanatoryLabel = new QLabel(xi18n("<para>The selected files and folders were added to the Clipboard. "
- "Now the <emphasis>Paste</emphasis> action can be used to transfer them from the Clipboard "
- "to any other location. They can even be transferred to other applications by using their "
- "respective <emphasis>Paste</emphasis> actions.</para>"), this);
+ "Now the <emphasis>Paste</emphasis> action can be used to transfer them from the Clipboard "
+ "to any other location. They can even be transferred to other applications by using their "
+ "respective <emphasis>Paste</emphasis> actions.</para>"),
+ this);
m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
void BottomBarContentsContainer::addRenameContents()
{
- m_explanatoryLabel = new QLabel(i18nc("@info explains the next step in a process", "Select the file or folder that should be renamed.\nBulk renaming is possible when multiple items are selected."), this);
+ m_explanatoryLabel = new QLabel(i18nc("@info explains the next step in a process",
+ "Select the file or folder that should be renamed.\nBulk renaming is possible when multiple items are selected."),
+ this);
m_explanatoryLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_explanatoryLabel->setWordWrap(true);
m_layout->addWidget(m_explanatoryLabel);
+ // clang-format off
// i18n: Aborts the current step-by-step process to delete files by leaving the selection mode.
auto *cancelButton = new QPushButton(QIcon::fromTheme(QStringLiteral("dialog-cancel")), i18nc("@action:button", "Cancel Renaming"), this);
+ // clang-format on
connect(cancelButton, &QAbstractButton::clicked, this, &BottomBarContentsContainer::selectionModeLeavingRequested);
m_layout->addWidget(cancelButton);
QLayoutItem *grandChild;
while ((grandChild = childLayout->takeAt(0)) != nullptr) {
delete grandChild->widget(); // delete the widget
- delete grandChild; // delete the layout item
+ delete grandChild; // delete the layout item
}
}
delete child->widget(); // delete the widget
- delete child; // delete the layout item
+ delete child; // delete the layout item
}
}
-std::vector<QAction *> BottomBarContentsContainer::contextActionsFor(const KFileItemList& selectedItems, const QUrl& baseUrl)
+std::vector<QAction *> BottomBarContentsContainer::contextActionsFor(const KFileItemList &selectedItems, const QUrl &baseUrl)
{
if (selectedItems.isEmpty()) {
// There are no contextual actions to show for these items.
// KHamburgerMenu would only be visible if there is no menu available anywhere on the user interface. This might be useful for recovery from
// such a situation in theory but a bar with context dependent actions doesn't really seem like the right place for it.
- Q_ASSERT(internalContextMenuActions.first()->icon().name() == m_actionCollection->action(KStandardAction::name(KStandardAction::HamburgerMenu))->icon().name());
+ Q_ASSERT(internalContextMenuActions.first()->icon().name()
+ == m_actionCollection->action(KStandardAction::name(KStandardAction::HamburgerMenu))->icon().name());
internalContextMenuActions.removeFirst();
for (auto it = internalContextMenuActions.constBegin(); it != internalContextMenuActions.constEnd(); ++it) {
sumOfPreferredWidths += m_layout->itemAt(i)->sizeHint().width() + m_layout->spacing();
}
return m_barWidth - sumOfPreferredWidths - 20; // We consider all space used when there are only 20 pixels left
- // so there is some room to breath and not too much wonkyness while resizing.
+ // so there is some room to breath and not too much wonkyness while resizing.
}
void BottomBarContentsContainer::updateExplanatoryLabelVisibility()
m_explanatoryLabel->setVisible(unusedSpace() > m_explanatoryLabel->sizeHint().width() + 20);
}
}
-
+// clang-format off
void BottomBarContentsContainer::updateMainActionButton(const KFileItemList& selectedItems)
{
if (!m_mainAction.widget()) {
updateExplanatoryLabelVisibility();
}
}
+// clang-format on
return m_contents;
};
- inline bool hasSomethingToShow() {
+ inline bool hasSomethingToShow()
+ {
return contents() != BottomBar::GeneralContents || m_internalContextMenu;
}
class SingleClickSelectionProxyStyle : public QProxyStyle
{
public:
- inline int styleHint(StyleHint hint, const QStyleOption *option = nullptr,
- const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override
+ inline int
+ styleHint(StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override
{
if (hint == QStyle::SH_ItemView_ActivateItemOnSingleClick) {
return 0;
using namespace SelectionMode;
-TopBar::TopBar(QWidget *parent) :
- QWidget{parent}
+TopBar::TopBar(QWidget *parent)
+ : QWidget{parent}
{
// Showing of this widget is normally animated. We hide it for now and make it small.
hide();
setMaximumHeight(0);
setToolTip(KToolTipHelper::whatsThisHintOnly());
- setWhatsThis(xi18nc("@info:whatsthis", "<title>Selection Mode</title><para>Select files or folders to manage or manipulate them."
- "<list><item>Press on a file or folder to select it.</item><item>Press on an already selected file or folder to deselect it.</item>"
- "<item>Pressing an empty area does <emphasis>not</emphasis> clear the selection.</item>"
- "<item>Selection rectangles (created by dragging from an empty area) invert the selection status of items within.</item></list></para>"
- "<para>The available action buttons at the bottom change depending on the current selection.</para>"));
+ setWhatsThis(xi18nc("@info:whatsthis",
+ "<title>Selection Mode</title><para>Select files or folders to manage or manipulate them."
+ "<list><item>Press on a file or folder to select it.</item><item>Press on an already selected file or folder to deselect it.</item>"
+ "<item>Pressing an empty area does <emphasis>not</emphasis> clear the selection.</item>"
+ "<item>Selection rectangles (created by dragging from an empty area) invert the selection status of items within.</item></list></para>"
+ "<para>The available action buttons at the bottom change depending on the current selection.</para>"));
auto fillParentLayout = new QGridLayout(this);
fillParentLayout->setContentsMargins(0, 0, 0, 0);
setMinimumWidth(0);
- m_fullLabelString = i18nc("@info label above the view explaining the state",
- "Selection Mode: Click on files or folders to select or deselect them.");
- m_shortLabelString = i18nc("@info label above the view explaining the state",
- "Selection Mode");
+ m_fullLabelString = i18nc("@info label above the view explaining the state", "Selection Mode: Click on files or folders to select or deselect them.");
+ m_shortLabelString = i18nc("@info label above the view explaining the state", "Selection Mode");
m_label = new QLabel(contentsContainer);
m_label->setMinimumWidth(0);
BackgroundColorHelper::instance()->controlBackgroundColor(m_label);
m_closeButton = new QPushButton(QIcon::fromTheme(QStringLiteral("window-close-symbolic")), "", contentsContainer);
m_closeButton->setText(i18nc("@action:button", "Exit Selection Mode"));
m_closeButton->setFlat(true);
- connect(m_closeButton, &QAbstractButton::clicked,
- this, &TopBar::selectionModeLeavingRequested);
+ connect(m_closeButton, &QAbstractButton::clicked, this, &TopBar::selectionModeLeavingRequested);
QHBoxLayout *layout = new QHBoxLayout(contentsContainer);
auto contentsMargins = layout->contentsMargins();
m_heightAnimation->stop(); // deletes because of QAbstractAnimation::DeleteWhenStopped.
}
m_heightAnimation = new QPropertyAnimation(this, "maximumHeight");
- m_heightAnimation->setDuration(2 *
- style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) *
- GlobalConfig::animationDurationFactor());
+ m_heightAnimation->setDuration(2 * style()->styleHint(QStyle::SH_Widget_Animation_Duration, nullptr, this) * GlobalConfig::animationDurationFactor());
m_heightAnimation->setStartValue(height());
m_heightAnimation->setEasingCurve(QEasingCurve::OutCubic);
m_heightAnimation->setEndValue(m_preferredHeight);
} else {
m_heightAnimation->setEndValue(0);
- connect(m_heightAnimation, &QAbstractAnimation::finished,
- this, &QWidget::hide);
+ connect(m_heightAnimation, &QAbstractAnimation::finished, this, &QWidget::hide);
}
m_heightAnimation->start(QAbstractAnimation::DeleteWhenStopped);
void TopBar::updateLabelString()
{
QFontMetrics fontMetrics = m_label->fontMetrics();
- if (fontMetrics.horizontalAdvance(m_fullLabelString) + m_closeButton->sizeHint().width() + style()->pixelMetric(QStyle::PM_LayoutLeftMargin) * 2 + style()->pixelMetric(QStyle::PM_LayoutRightMargin) * 2 < width()) {
+ if (fontMetrics.horizontalAdvance(m_fullLabelString) + m_closeButton->sizeHint().width() + style()->pixelMetric(QStyle::PM_LayoutLeftMargin) * 2
+ + style()->pixelMetric(QStyle::PM_LayoutRightMargin) * 2
+ < width()) {
m_label->setText(m_fullLabelString);
} else {
m_label->setText(m_shortLabelString);
#include "views/viewproperties.h"
-ApplyViewPropsJob::ApplyViewPropsJob(const QUrl& dir,
- const ViewProperties& viewProps) :
- KIO::Job(),
- m_viewProps(nullptr),
- m_progress(0),
- m_dir(dir)
+ApplyViewPropsJob::ApplyViewPropsJob(const QUrl &dir, const ViewProperties &viewProps)
+ : KIO::Job()
+ , m_viewProps(nullptr)
+ , m_progress(0)
+ , m_dir(dir)
{
m_viewProps = new ViewProperties(dir);
m_viewProps->setViewMode(viewProps.viewMode());
m_viewProps->setSortRole(viewProps.sortRole());
m_viewProps->setSortOrder(viewProps.sortOrder());
- KIO::ListJob* listJob = KIO::listRecursive(dir, KIO::HideProgressInfo);
- connect(listJob, &KIO::ListJob::entries,
- this, &ApplyViewPropsJob::slotEntries);
+ KIO::ListJob *listJob = KIO::listRecursive(dir, KIO::HideProgressInfo);
+ connect(listJob, &KIO::ListJob::entries, this, &ApplyViewPropsJob::slotEntries);
addSubjob(listJob);
}
ApplyViewPropsJob::~ApplyViewPropsJob()
{
- delete m_viewProps; // the properties are written by the destructor
+ delete m_viewProps; // the properties are written by the destructor
m_viewProps = nullptr;
}
-void ApplyViewPropsJob::slotEntries(KIO::Job*, const KIO::UDSEntryList& list)
+void ApplyViewPropsJob::slotEntries(KIO::Job *, const KIO::UDSEntryList &list)
{
- for (const KIO::UDSEntry& entry : list) {
+ for (const KIO::UDSEntry &entry : list) {
const QString name = entry.stringValue(KIO::UDSEntry::UDS_NAME);
if (name != QLatin1Char('.') && name != QLatin1String("..") && entry.isDir()) {
++m_progress;
}
}
-void ApplyViewPropsJob::slotResult(KJob* job)
+void ApplyViewPropsJob::slotResult(KJob *job)
{
if (job->error()) {
setError(job->error());
}
emitResult();
}
-
* @param viewProps View properties for the directory \a dir including its
* sub directories.
*/
- ApplyViewPropsJob(const QUrl& dir, const ViewProperties& viewProps);
+ ApplyViewPropsJob(const QUrl &dir, const ViewProperties &viewProps);
~ApplyViewPropsJob() override;
int progress() const;
private Q_SLOTS:
- void slotResult(KJob* job) override;
- void slotEntries(KIO::Job*, const KIO::UDSEntryList&);
+ void slotResult(KJob *job) override;
+ void slotEntries(KIO::Job *, const KIO::UDSEntryList &);
private:
- ViewProperties* m_viewProps;
+ ViewProperties *m_viewProps;
int m_progress;
QUrl m_dir;
};
#include "contextmenusettingspage.h"
+#include "dolphin_contextmenusettings.h"
#include "dolphin_generalsettings.h"
#include "dolphin_versioncontrolsettings.h"
-#include "dolphin_contextmenusettings.h"
+#include "global.h"
#include "settings/serviceitemdelegate.h"
#include "settings/servicemodel.h"
-#include "global.h"
#include <KDesktopFile>
#include <KDesktopFileActions>
#include <kservice_export.h>
#include <kwidgetsaddons_version.h>
-#include <QtGlobal>
#include <KNSWidgets/Button>
+#include <QtGlobal>
+#include <QApplication>
#include <QGridLayout>
#include <QLabel>
+#include <QLineEdit>
#include <QListWidget>
#include <QScroller>
#include <QShowEvent>
#include <QSortFilterProxyModel>
-#include <QLineEdit>
-#include <QApplication>
namespace
{
- const bool ShowDeleteDefault = false;
- const char VersionControlServicePrefix[] = "_version_control_";
- const char DeleteService[] = "_delete";
- const char CopyToMoveToService[] ="_copy_to_move_to";
+const bool ShowDeleteDefault = false;
+const char VersionControlServicePrefix[] = "_version_control_";
+const char DeleteService[] = "_delete";
+const char CopyToMoveToService[] = "_copy_to_move_to";
- bool laterSelected = false;
+bool laterSelected = false;
}
-ContextMenuSettingsPage::ContextMenuSettingsPage(QWidget* parent,
- const KActionCollection* actions,
- const QStringList& actionIds) :
- SettingsPageBase(parent),
- m_initialized(false),
- m_serviceModel(nullptr),
- m_sortModel(nullptr),
- m_listView(nullptr),
- m_enabledVcsPlugins(),
- m_actions(actions),
- m_actionIds(actionIds)
+ContextMenuSettingsPage::ContextMenuSettingsPage(QWidget *parent, const KActionCollection *actions, const QStringList &actionIds)
+ : SettingsPageBase(parent)
+ , m_initialized(false)
+ , m_serviceModel(nullptr)
+ , m_sortModel(nullptr)
+ , m_listView(nullptr)
+ , m_enabledVcsPlugins()
+ , m_actions(actions)
+ , m_actionIds(actionIds)
{
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
- QLabel* label = new QLabel(i18nc("@label:textbox",
+ QLabel *label = new QLabel(i18nc("@label:textbox",
"Select which services should "
- "be shown in the context menu:"), this);
+ "be shown in the context menu:"),
+ this);
label->setWordWrap(true);
m_searchLineEdit = new QLineEdit(this);
m_searchLineEdit->setPlaceholderText(i18nc("@label:textbox", "Search..."));
- connect(m_searchLineEdit, &QLineEdit::textChanged, this, [this](const QString &filter){
+ connect(m_searchLineEdit, &QLineEdit::textChanged, this, [this](const QString &filter) {
m_sortModel->setFilterFixedString(filter);
});
#ifndef Q_OS_WIN
using NewStuffButton = KNSWidgets::Button;
- auto *downloadButton = new NewStuffButton(i18nc("@action:button", "Download New Services..."),
- QStringLiteral("servicemenu.knsrc"),
- this);
+ auto *downloadButton = new NewStuffButton(i18nc("@action:button", "Download New Services..."), QStringLiteral("servicemenu.knsrc"), this);
connect(downloadButton, &NewStuffButton::dialogFinished, this, [this](const auto &changedEntries) {
- if (!changedEntries.isEmpty()) {
- m_serviceModel->clear();
- loadServices();
- }
+ if (!changedEntries.isEmpty()) {
+ m_serviceModel->clear();
+ loadServices();
+ }
});
topLayout->addWidget(downloadButton);
#endif // Q_OS_WIN
std::sort(m_enabledVcsPlugins.begin(), m_enabledVcsPlugins.end());
}
-ContextMenuSettingsPage::~ContextMenuSettingsPage() {
+ContextMenuSettingsPage::~ContextMenuSettingsPage()
+{
}
-bool ContextMenuSettingsPage::entryVisible(const QString& id)
+bool ContextMenuSettingsPage::entryVisible(const QString &id)
{
if (id == "add_to_places") {
return ContextMenuSettings::showAddToPlaces();
return false;
}
-void ContextMenuSettingsPage::setEntryVisible(const QString& id, bool visible)
+void ContextMenuSettingsPage::setEntryVisible(const QString &id, bool visible)
{
if (id == "add_to_places") {
ContextMenuSettings::setShowAddToPlaces(visible);
if (!laterSelected) {
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- KMessageBox::ButtonCode promptRestart = KMessageBox::questionTwoActions(window(),
+ KMessageBox::ButtonCode promptRestart =
+ KMessageBox::questionTwoActions(window(),
#else
- KMessageBox::ButtonCode promptRestart = KMessageBox::questionYesNo(window(),
+ KMessageBox::ButtonCode promptRestart =
+ KMessageBox::questionYesNo(window(),
#endif
- i18nc("@info", "Dolphin must be restarted to apply the "
- "updated version control system settings."),
- i18nc("@info", "Restart now?"),
- KGuiItem(QApplication::translate("KStandardGuiItem", "&Restart"), QStringLiteral("dialog-restart")),
- KGuiItem(QApplication::translate("KStandardGuiItem", "&Later"), QStringLiteral("dialog-later"))
- );
+ i18nc("@info",
+ "Dolphin must be restarted to apply the "
+ "updated version control system settings."),
+ i18nc("@info", "Restart now?"),
+ KGuiItem(QApplication::translate("KStandardGuiItem", "&Restart"), QStringLiteral("dialog-restart")),
+ KGuiItem(QApplication::translate("KStandardGuiItem", "&Later"), QStringLiteral("dialog-later")));
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
if (promptRestart == KMessageBox::ButtonCode::PrimaryAction) {
#else
void ContextMenuSettingsPage::restoreDefaults()
{
- QAbstractItemModel* model = m_listView->model();
+ QAbstractItemModel *model = m_listView->model();
for (int i = 0; i < model->rowCount(); ++i) {
const QModelIndex index = model->index(i, 0);
const QString service = model->data(index, ServiceModel::DesktopEntryNameRole).toString();
- const bool checked = !service.startsWith(VersionControlServicePrefix)
- && service != QLatin1String(DeleteService)
- && service != QLatin1String(CopyToMoveToService);
+ const bool checked =
+ !service.startsWith(VersionControlServicePrefix) && service != QLatin1String(DeleteService) && service != QLatin1String(CopyToMoveToService);
model->setData(index, checked, Qt::CheckStateRole);
}
}
-void ContextMenuSettingsPage::showEvent(QShowEvent* event)
+void ContextMenuSettingsPage::showEvent(QShowEvent *event)
{
if (!event->spontaneous() && !m_initialized) {
loadServices();
// Add "Show 'Delete' command" as service
KSharedConfig::Ptr globalConfig = KSharedConfig::openConfig(QStringLiteral("kdeglobals"), KConfig::IncludeGlobals);
KConfigGroup configGroup(globalConfig, "KDE");
- addRow(QStringLiteral("edit-delete"),
- i18nc("@option:check", "Delete"),
- DeleteService,
- configGroup.readEntry("ShowDeleteCommand", ShowDeleteDefault));
+ addRow(QStringLiteral("edit-delete"), i18nc("@option:check", "Delete"), DeleteService, configGroup.readEntry("ShowDeleteCommand", ShowDeleteDefault));
// Add "Show 'Copy To' and 'Move To' commands" as service
addRow(QStringLiteral("edit-copy"),
CopyToMoveToService,
ContextMenuSettings::showCopyMoveMenu());
- if (m_actions){
+ if (m_actions) {
// Add other built-in actions
- for (const QString& id : m_actionIds) {
- const QAction* action = m_actions->action(id);
+ for (const QString &id : m_actionIds) {
+ const QAction *action = m_actions->action(id);
if (action) {
addRow(action->icon().name(), action->text(), id, entryVisible(id));
}
const bool addService = !action.noDisplay() && !action.isSeparator() && !isInServicesList(serviceName);
if (addService) {
- const QString itemName = subMenuName.isEmpty()
- ? action.text()
- : i18nc("@item:inmenu", "%1: %2", subMenuName, action.text());
+ const QString itemName = subMenuName.isEmpty() ? action.text() : i18nc("@item:inmenu", "%1: %2", subMenuName, action.text());
const bool checked = showGroup.readEntry(serviceName, true);
addRow(action.icon(), itemName, serviceName, checked);
}
const QVector<KPluginMetaData> plugins = KPluginMetaData::findPlugins(QStringLiteral("dolphin/vcs"));
for (const auto &plugin : plugins) {
const QString pluginName = plugin.name();
- addRow(QStringLiteral("code-class"),
- pluginName,
- VersionControlServicePrefix + pluginName,
- enabledPlugins.contains(pluginName));
+ addRow(QStringLiteral("code-class"), pluginName, VersionControlServicePrefix + pluginName, enabledPlugins.contains(pluginName));
loadedPlugins += pluginName;
}
return false;
}
-void ContextMenuSettingsPage::addRow(const QString &icon,
- const QString &text,
- const QString &value,
- bool checked)
+void ContextMenuSettingsPage::addRow(const QString &icon, const QString &text, const QString &value, bool checked)
{
m_serviceModel->insertRow(0);
Q_OBJECT
public:
- explicit ContextMenuSettingsPage(QWidget* parent,
- const KActionCollection* actions,
- const QStringList& actionIds);
+ explicit ContextMenuSettingsPage(QWidget *parent, const KActionCollection *actions, const QStringList &actionIds);
~ContextMenuSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
void restoreDefaults() override;
protected:
- void showEvent(QShowEvent* event) override;
+ void showEvent(QShowEvent *event) override;
private Q_SLOTS:
/**
/**
* Adds a row to the model of m_listView.
*/
- void addRow(const QString &icon,
- const QString &text,
- const QString &value,
- bool checked);
- bool entryVisible(const QString& id);
- void setEntryVisible(const QString& id, bool visible);
+ void addRow(const QString &icon, const QString &text, const QString &value, bool checked);
+ bool entryVisible(const QString &id);
+ void setEntryVisible(const QString &id, bool visible);
private:
bool m_initialized;
ServiceModel *m_serviceModel;
QSortFilterProxyModel *m_sortModel;
- QListView* m_listView;
+ QListView *m_listView;
QLineEdit *m_searchLineEdit;
QStringList m_enabledVcsPlugins;
- const KActionCollection* m_actions;
+ const KActionCollection *m_actions;
const QStringList m_actionIds;
};
* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
+#include <KLocalizedString>
+#include <KShell>
+#include <QCommandLineParser>
#include <QDebug>
-#include <QProcess>
-#include <QTimer>
-#include <QStandardPaths>
#include <QDir>
#include <QDirIterator>
-#include <QCommandLineParser>
+#include <QGuiApplication>
#include <QMimeDatabase>
+#include <QProcess>
+#include <QStandardPaths>
+#include <QTimer>
#include <QUrl>
-#include <QGuiApplication>
-#include <KLocalizedString>
-#include <KShell>
#include "../../../config-dolphin.h"
-Q_GLOBAL_STATIC_WITH_ARGS(QStringList, binaryPackages, ({QLatin1String("application/vnd.debian.binary-package"),
- QLatin1String("application/x-rpm"),
- QLatin1String("application/x-xz"),
- QLatin1String("application/zstd")}))
+Q_GLOBAL_STATIC_WITH_ARGS(QStringList,
+ binaryPackages,
+ ({QLatin1String("application/vnd.debian.binary-package"),
+ QLatin1String("application/x-rpm"),
+ QLatin1String("application/x-xz"),
+ QLatin1String("application/zstd")}))
-enum PackageOperation {
- Install,
- Uninstall
-};
+enum PackageOperation { Install, Uninstall };
#if HAVE_PACKAGEKIT
#include <PackageKit/Daemon>
Q_NORETURN void fail(const QString &str)
{
qCritical() << str;
- const QStringList args = {"--detailederror" ,i18n("Dolphin service menu installation failed"), str};
+ const QStringList args = {"--detailederror", i18n("Dolphin service menu installation failed"), str};
QProcess::startDetached("kdialog", args);
exit(1);
PackageKit::Transaction *transaction = PackageKit::Daemon::installFile(fileName, PackageKit::Transaction::TransactionFlagNone);
const auto exitWithError = [=](PackageKit::Transaction::Error, const QString &details) {
- fail(details);
+ fail(details);
};
- QObject::connect(transaction, &PackageKit::Transaction::finished,
- [=](PackageKit::Transaction::Exit status, uint) {
- if (status == PackageKit::Transaction::ExitSuccess) {
- exit(0);
- }
- // Fallback error handling
- QTimer::singleShot(500, [=](){
- fail(i18n("Failed to install \"%1\", exited with status \"%2\"",
- fileName, QVariant::fromValue(status).toString()));
- });
- });
+ QObject::connect(transaction, &PackageKit::Transaction::finished, [=](PackageKit::Transaction::Exit status, uint) {
+ if (status == PackageKit::Transaction::ExitSuccess) {
+ exit(0);
+ }
+ // Fallback error handling
+ QTimer::singleShot(500, [=]() {
+ fail(i18n("Failed to install \"%1\", exited with status \"%2\"", fileName, QVariant::fromValue(status).toString()));
+ });
+ });
QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError);
}
};
PackageKit::Transaction *transaction = PackageKit::Daemon::getDetailsLocal(fileName);
- QObject::connect(transaction, &PackageKit::Transaction::details,
- [=](const PackageKit::Details &details) {
- PackageKit::Transaction *transaction = PackageKit::Daemon::removePackage(details.packageId());
- QObject::connect(transaction, &PackageKit::Transaction::finished, uninstallLambda);
- QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError);
- });
+ QObject::connect(transaction, &PackageKit::Transaction::details, [=](const PackageKit::Details &details) {
+ PackageKit::Transaction *transaction = PackageKit::Daemon::removePackage(details.packageId());
+ QObject::connect(transaction, &PackageKit::Transaction::finished, uninstallLambda);
+ QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError);
+ });
QObject::connect(transaction, &PackageKit::Transaction::errorCode, exitWithError);
// Fallback error handling
- QObject::connect(transaction, &PackageKit::Transaction::finished,
- [=](PackageKit::Transaction::Exit status, uint) {
- if (status != PackageKit::Transaction::ExitSuccess) {
- QTimer::singleShot(500, [=]() {
- fail(i18n("Failed to uninstall \"%1\", exited with status \"%2\"",
- fileName, QVariant::fromValue(status).toString()));
- });
- }
- });
- }
+ QObject::connect(transaction, &PackageKit::Transaction::finished, [=](PackageKit::Transaction::Exit status, uint) {
+ if (status != PackageKit::Transaction::ExitSuccess) {
+ QTimer::singleShot(500, [=]() {
+ fail(i18n("Failed to uninstall \"%1\", exited with status \"%2\"", fileName, QVariant::fromValue(status).toString()));
+ });
+ }
+ });
+}
#endif
Q_NORETURN void packageKit(PackageOperation operation, const QString &fileName)
#endif
}
-struct UncompressCommand
-{
+struct UncompressCommand {
QString command;
QStringList args1;
QStringList args2;
};
-enum ScriptExecution{
- Process,
- Konsole
-};
+enum ScriptExecution { Process, Konsole };
void runUncompress(const QString &inputPath, const QString &outputPath)
{
QVector<QPair<QStringList, UncompressCommand>> mimeTypeToCommand;
- mimeTypeToCommand.append({{"application/x-tar", "application/tar", "application/x-gtar", "multipart/x-tar"},
- UncompressCommand({"tar", {"-xf"}, {"-C"}})});
- mimeTypeToCommand.append({{"application/x-gzip", "application/gzip",
- "application/x-gzip-compressed-tar", "application/gzip-compressed-tar",
- "application/x-gzip-compressed", "application/gzip-compressed",
- "application/tgz", "application/x-compressed-tar",
- "application/x-compressed-gtar", "file/tgz",
- "multipart/x-tar-gz", "application/x-gunzip", "application/gzipped",
+ mimeTypeToCommand.append({{"application/x-tar", "application/tar", "application/x-gtar", "multipart/x-tar"}, UncompressCommand({"tar", {"-xf"}, {"-C"}})});
+ mimeTypeToCommand.append({{"application/x-gzip",
+ "application/gzip",
+ "application/x-gzip-compressed-tar",
+ "application/gzip-compressed-tar",
+ "application/x-gzip-compressed",
+ "application/gzip-compressed",
+ "application/tgz",
+ "application/x-compressed-tar",
+ "application/x-compressed-gtar",
+ "file/tgz",
+ "multipart/x-tar-gz",
+ "application/x-gunzip",
+ "application/gzipped",
"gzip/document"},
UncompressCommand({"tar", {"-zxf"}, {"-C"}})});
- mimeTypeToCommand.append({{"application/bzip", "application/bzip2", "application/x-bzip",
- "application/x-bzip2", "application/bzip-compressed",
- "application/bzip2-compressed", "application/x-bzip-compressed",
- "application/x-bzip2-compressed", "application/bzip-compressed-tar",
- "application/bzip2-compressed-tar", "application/x-bzip-compressed-tar",
- "application/x-bzip2-compressed-tar", "application/x-bz2"},
+ mimeTypeToCommand.append({{"application/bzip",
+ "application/bzip2",
+ "application/x-bzip",
+ "application/x-bzip2",
+ "application/bzip-compressed",
+ "application/bzip2-compressed",
+ "application/x-bzip-compressed",
+ "application/x-bzip2-compressed",
+ "application/bzip-compressed-tar",
+ "application/bzip2-compressed-tar",
+ "application/x-bzip-compressed-tar",
+ "application/x-bzip2-compressed-tar",
+ "application/x-bz2"},
UncompressCommand({"tar", {"-jxf"}, {"-C"}})});
- mimeTypeToCommand.append({{"application/zip", "application/x-zip", "application/x-zip-compressed",
- "multipart/x-zip"},
- UncompressCommand({"unzip", {}, {"-d"}})});
+ mimeTypeToCommand.append(
+ {{"application/zip", "application/x-zip", "application/x-zip-compressed", "multipart/x-zip"}, UncompressCommand({"unzip", {}, {"-d"}})});
const auto mime = QMimeDatabase().mimeTypeForFile(inputPath).name();
}
QProcess process;
- process.start(
- command.command,
- QStringList() << command.args1 << inputPath << command.args2 << outputPath,
- QIODevice::NotOpen);
+ process.start(command.command, QStringList() << command.args1 << inputPath << command.args2 << outputPath, QIODevice::NotOpen);
if (!process.waitForStarted()) {
fail(i18n("Failed to run uncompressor command for %1", inputPath));
}
if (!process.waitForFinished()) {
- fail(
- i18n("Process did not finish in reasonable time: %1 %2", process.program(), process.arguments().join(" ")));
+ fail(i18n("Process did not finish in reasonable time: %1 %2", process.program(), process.arguments().join(" ")));
}
if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
bashCommand.append("|| $SHELL");
// If the install script fails a shell opens and the user can fix the problem
// without an error konsole closes
- process.start("konsole", QStringList() << "-e" << "bash" << "-c" << bashCommand, QIODevice::NotOpen);
+ process.start("konsole",
+ QStringList() << "-e"
+ << "bash"
+ << "-c" << bashCommand,
+ QIODevice::NotOpen);
} else {
process.start(path, args, QIODevice::NotOpen);
}
return true;
}
- errorText = i18nc(
- "%2 = comma separated list of arguments",
- "Installer script %1 failed, tried arguments \"%2\".", path, argVariants.join(i18nc("Separator between arguments", "\", \"")));
+ errorText = i18nc("%2 = comma separated list of arguments",
+ "Installer script %1 failed, tried arguments \"%2\".",
+ path,
+ argVariants.join(i18nc("Separator between arguments", "\", \"")));
return false;
}
} else {
// If "deinstall" is missing, try "install --uninstall"
QString installerPath;
- const QStringList basenames2 = {"install-it.sh", "install-it", "installKDE4.sh",
- "installKDE4", "install.sh", "install"};
+ const QStringList basenames2 = {"install-it.sh", "install-it", "installKDE4.sh", "installKDE4", "install.sh", "install"};
for (const auto &basename : basenames2) {
const auto path = findRecursive(dir, basename);
if (!path.isEmpty()) {
}
if (!installerPath.isEmpty()) {
- const bool ok = runScriptVariants(installerPath, true,
- {"--remove", "--delete", "--uninstall", "--deinstall"}, errorText);
+ const bool ok = runScriptVariants(installerPath, true, {"--remove", "--delete", "--uninstall", "--deinstall"}, errorText);
if (!ok) {
return ok;
}
#include "dolphinsettingsdialog.h"
+#include "config-dolphin.h"
+#include "contextmenu/contextmenusettingspage.h"
#include "dolphin_generalsettings.h"
#include "dolphinmainwindow.h"
#include "general/generalsettingspage.h"
#include "navigation/navigationsettingspage.h"
-#include "contextmenu/contextmenusettingspage.h"
#include "startup/startupsettingspage.h"
#include "trash/trashsettingspage.h"
#include "viewmodes/viewsettingspage.h"
-#include "config-dolphin.h"
#if HAVE_KUSERFEEDBACK
#include "userfeedback/dolphinfeedbackprovider.h"
#include "userfeedback/userfeedbacksettingspage.h"
#include <KAuthorized>
#include <KLocalizedString>
-#include <KWindowConfig>
#include <KMessageBox>
+#include <KWindowConfig>
#include <kwidgetsaddons_version.h>
#include <QCloseEvent>
#include <QPushButton>
-DolphinSettingsDialog::DolphinSettingsDialog(const QUrl& url, QWidget* parent, KActionCollection* actions) :
- KPageDialog(parent),
- m_pages(),
- m_unsavedChanges(false)
+DolphinSettingsDialog::DolphinSettingsDialog(const QUrl &url, QWidget *parent, KActionCollection *actions)
+ : KPageDialog(parent)
+ , m_pages()
+ , m_unsavedChanges(false)
{
const QSize minSize = minimumSize();
setFaceType(List);
setWindowTitle(i18nc("@title:window", "Configure"));
- QDialogButtonBox* box = new QDialogButtonBox(QDialogButtonBox::Ok
- | QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults);
+ QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults);
box->button(QDialogButtonBox::Apply)->setEnabled(false);
box->button(QDialogButtonBox::Ok)->setDefault(true);
setButtonBox(box);
connect(box->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, this, &DolphinSettingsDialog::restoreDefaults);
// General
- GeneralSettingsPage* generalSettingsPage = new GeneralSettingsPage(url, this);
- KPageWidgetItem* generalSettingsFrame = addPage(generalSettingsPage,
- i18nc("@title:group General settings", "General"));
+ GeneralSettingsPage *generalSettingsPage = new GeneralSettingsPage(url, this);
+ KPageWidgetItem *generalSettingsFrame = addPage(generalSettingsPage, i18nc("@title:group General settings", "General"));
generalSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("system-file-manager")));
connect(generalSettingsPage, &GeneralSettingsPage::changed, this, &DolphinSettingsDialog::enableApply);
// Startup
- StartupSettingsPage* startupSettingsPage = new StartupSettingsPage(url, this);
- KPageWidgetItem* startupSettingsFrame = addPage(startupSettingsPage,
- i18nc("@title:group", "Startup"));
+ StartupSettingsPage *startupSettingsPage = new StartupSettingsPage(url, this);
+ KPageWidgetItem *startupSettingsFrame = addPage(startupSettingsPage, i18nc("@title:group", "Startup"));
startupSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-launch-feedback")));
connect(startupSettingsPage, &StartupSettingsPage::changed, this, &DolphinSettingsDialog::enableApply);
// View Modes
- ViewSettingsPage* viewSettingsPage = new ViewSettingsPage(this);
- KPageWidgetItem* viewSettingsFrame = addPage(viewSettingsPage,
- i18nc("@title:group", "View Modes"));
+ ViewSettingsPage *viewSettingsPage = new ViewSettingsPage(this);
+ KPageWidgetItem *viewSettingsFrame = addPage(viewSettingsPage, i18nc("@title:group", "View Modes"));
viewSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-icons")));
connect(viewSettingsPage, &ViewSettingsPage::changed, this, &DolphinSettingsDialog::enableApply);
// Navigation
- NavigationSettingsPage* navigationSettingsPage = new NavigationSettingsPage(this);
- KPageWidgetItem* navigationSettingsFrame = addPage(navigationSettingsPage,
- i18nc("@title:group", "Navigation"));
+ NavigationSettingsPage *navigationSettingsPage = new NavigationSettingsPage(this);
+ KPageWidgetItem *navigationSettingsFrame = addPage(navigationSettingsPage, i18nc("@title:group", "Navigation"));
navigationSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-navigation")));
connect(navigationSettingsPage, &NavigationSettingsPage::changed, this, &DolphinSettingsDialog::enableApply);
// Context Menu
- auto contextMenuSettingsPage = new ContextMenuSettingsPage(this, actions, {
- QStringLiteral("add_to_places"),
- QStringLiteral("sort"),
- QStringLiteral("view_mode"),
- QStringLiteral("open_in_new_tab"),
- QStringLiteral("open_in_new_window"),
- QStringLiteral("copy_location"),
- QStringLiteral("duplicate"),
- QStringLiteral("open_terminal_here")
- });
- KPageWidgetItem* contextMenuSettingsFrame = addPage(contextMenuSettingsPage,
- i18nc("@title:group", "Context Menu"));
+ auto contextMenuSettingsPage = new ContextMenuSettingsPage(this,
+ actions,
+ {QStringLiteral("add_to_places"),
+ QStringLiteral("sort"),
+ QStringLiteral("view_mode"),
+ QStringLiteral("open_in_new_tab"),
+ QStringLiteral("open_in_new_window"),
+ QStringLiteral("copy_location"),
+ QStringLiteral("duplicate"),
+ QStringLiteral("open_terminal_here")});
+ KPageWidgetItem *contextMenuSettingsFrame = addPage(contextMenuSettingsPage, i18nc("@title:group", "Context Menu"));
contextMenuSettingsFrame->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-menu-edit")));
connect(contextMenuSettingsPage, &ContextMenuSettingsPage::changed, this, &DolphinSettingsDialog::enableApply);
// Trash
- SettingsPageBase* trashSettingsPage = nullptr;
+ SettingsPageBase *trashSettingsPage = nullptr;
#ifndef Q_OS_WIN
trashSettingsPage = createTrashSettingsPage(this);
#endif
if (trashSettingsPage) {
- trashSettings = addPage(trashSettingsPage,
- i18nc("@title:group", "Trash"));
+ trashSettings = addPage(trashSettingsPage, i18nc("@title:group", "Trash"));
trashSettings->setIcon(QIcon::fromTheme(QStringLiteral("user-trash")));
connect(trashSettingsPage, &TrashSettingsPage::changed, this, &DolphinSettingsDialog::enableApply);
}
#if HAVE_KUSERFEEDBACK
// User Feedback
- UserFeedbackSettingsPage* feedbackSettingsPage = nullptr;
+ UserFeedbackSettingsPage *feedbackSettingsPage = nullptr;
if (DolphinFeedbackProvider::instance()->isEnabled()) {
feedbackSettingsPage = new UserFeedbackSettingsPage(this);
auto feedbackSettingsFrame = addPage(feedbackSettingsPage, i18nc("@title:group", "User Feedback"));
void DolphinSettingsDialog::applySettings()
{
- for (SettingsPageBase* page : qAsConst(m_pages)) {
+ for (SettingsPageBase *page : qAsConst(m_pages)) {
page->applySettings();
}
Q_EMIT settingsChanged();
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
if (settings->modifiedStartupSettings()) {
// Reset the modified startup settings hint. The changed startup settings
// have been applied already due to emitting settingsChanged().
void DolphinSettingsDialog::restoreDefaults()
{
- for (SettingsPageBase* page : qAsConst(m_pages)) {
+ for (SettingsPageBase *page : qAsConst(m_pages)) {
page->restoreDefaults();
}
}
-void DolphinSettingsDialog::closeEvent(QCloseEvent* event)
+void DolphinSettingsDialog::closeEvent(QCloseEvent *event)
{
if (!m_unsavedChanges) {
event->accept();
#else
const auto response = KMessageBox::warningYesNoCancel(this,
#endif
- i18n("You have unsaved changes. Do you want to apply the changes or discard them?"),
- i18n("Warning"),
- KStandardGuiItem::save(),
- KStandardGuiItem::discard(),
- KStandardGuiItem::cancel());
+ i18n("You have unsaved changes. Do you want to apply the changes or discard them?"),
+ i18n("Warning"),
+ KStandardGuiItem::save(),
+ KStandardGuiItem::discard(),
+ KStandardGuiItem::cancel());
switch (response) {
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- case KMessageBox::PrimaryAction:
+ case KMessageBox::PrimaryAction:
#else
- case KMessageBox::Yes:
+ case KMessageBox::Yes:
#endif
- applySettings();
- Q_FALLTHROUGH();
+ applySettings();
+ Q_FALLTHROUGH();
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- case KMessageBox::SecondaryAction:
+ case KMessageBox::SecondaryAction:
#else
- case KMessageBox::No:
+ case KMessageBox::No:
#endif
- event->accept();
- break;
- case KMessageBox::Cancel:
- event->ignore();
- break;
- default:
- break;
+ event->accept();
+ break;
+ case KMessageBox::Cancel:
+ event->ignore();
+ break;
+ default:
+ break;
}
}
-
SettingsPageBase *DolphinSettingsDialog::createTrashSettingsPage(QWidget *parent)
{
if (!KAuthorized::authorizeControlModule(QStringLiteral("kcmtrash.desktop"))) {
#ifndef DOLPHINSETTINGSDIALOG_H
#define DOLPHINSETTINGSDIALOG_H
-#include <KPageDialog>
#include <KActionCollection>
+#include <KPageDialog>
class QUrl;
class SettingsPageBase;
Q_OBJECT
public:
- explicit DolphinSettingsDialog(const QUrl& url, QWidget* parent = nullptr, KActionCollection* actions = {});
+ explicit DolphinSettingsDialog(const QUrl &url, QWidget *parent = nullptr, KActionCollection *actions = {});
~DolphinSettingsDialog() override;
- KPageWidgetItem* trashSettings;
+ KPageWidgetItem *trashSettings;
Q_SIGNALS:
void settingsChanged();
void restoreDefaults();
protected:
- void closeEvent(QCloseEvent* event) override;
+ void closeEvent(QCloseEvent *event) override;
private:
static SettingsPageBase *createTrashSettingsPage(QWidget *parent);
- QList<SettingsPageBase*> m_pages;
+ QList<SettingsPageBase *> m_pages;
bool m_unsavedChanges;
};
#include <QRadioButton>
#include <QSpacerItem>
-BehaviorSettingsPage::BehaviorSettingsPage(const QUrl& url, QWidget* parent) :
- SettingsPageBase(parent),
- m_url(url),
- m_localViewProps(nullptr),
- m_globalViewProps(nullptr),
- m_showToolTips(nullptr),
- m_showSelectionToggle(nullptr),
- m_naturalSorting(nullptr),
- m_caseSensitiveSorting(nullptr),
- m_caseInsensitiveSorting(nullptr),
- m_renameInline(nullptr),
- m_useTabForSplitViewSwitch(nullptr)
+BehaviorSettingsPage::BehaviorSettingsPage(const QUrl &url, QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_url(url)
+ , m_localViewProps(nullptr)
+ , m_globalViewProps(nullptr)
+ , m_showToolTips(nullptr)
+ , m_showSelectionToggle(nullptr)
+ , m_naturalSorting(nullptr)
+ , m_caseSensitiveSorting(nullptr)
+ , m_caseInsensitiveSorting(nullptr)
+ , m_renameInline(nullptr)
+ , m_useTabForSplitViewSwitch(nullptr)
{
- QFormLayout* topLayout = new QFormLayout(this);
-
+ QFormLayout *topLayout = new QFormLayout(this);
// View properties
m_globalViewProps = new QRadioButton(i18nc("@option:radio", "Use common display style for all folders"));
m_localViewProps = new QRadioButton(i18nc("@option:radio", "Remember display style for each folder"));
m_localViewProps->setToolTip(i18nc("@info", "Dolphin will create a hidden .directory file in each folder you change view properties for."));
- QButtonGroup* viewGroup = new QButtonGroup(this);
+ QButtonGroup *viewGroup = new QButtonGroup(this);
viewGroup->addButton(m_globalViewProps);
viewGroup->addButton(m_localViewProps);
topLayout->addRow(i18nc("@title:group", "View: "), m_globalViewProps);
topLayout->addRow(QString(), m_localViewProps);
-
topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed));
-
// Sorting properties
m_naturalSorting = new QRadioButton(i18nc("option:radio", "Natural"));
m_caseInsensitiveSorting = new QRadioButton(i18nc("option:radio", "Alphabetical, case insensitive"));
m_caseSensitiveSorting = new QRadioButton(i18nc("option:radio", "Alphabetical, case sensitive"));
- QButtonGroup* sortingModeGroup = new QButtonGroup(this);
+ QButtonGroup *sortingModeGroup = new QButtonGroup(this);
sortingModeGroup->addButton(m_naturalSorting);
sortingModeGroup->addButton(m_caseInsensitiveSorting);
sortingModeGroup->addButton(m_caseSensitiveSorting);
topLayout->addRow(QString(), m_caseInsensitiveSorting);
topLayout->addRow(QString(), m_caseSensitiveSorting);
-
topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed));
-
#if HAVE_BALOO
// 'Show tooltips'
m_showToolTips = new QCheckBox(i18nc("@option:check", "Show tooltips"));
void BehaviorSettingsPage::applySettings()
{
- GeneralSettings* settings = GeneralSettings::self();
- ViewProperties props(m_url); // read current view properties
+ GeneralSettings *settings = GeneralSettings::self();
+ ViewProperties props(m_url); // read current view properties
const bool useGlobalViewProps = m_globalViewProps->isChecked();
settings->setGlobalViewProps(useGlobalViewProps);
void BehaviorSettingsPage::restoreDefaults()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->useDefaults(true);
loadSettings();
settings->useDefaults(false);
Q_OBJECT
public:
- BehaviorSettingsPage(const QUrl &url, QWidget* parent);
+ BehaviorSettingsPage(const QUrl &url, QWidget *parent);
~BehaviorSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
private:
void loadSettings();
- void setSortingChoiceValue(GeneralSettings* settings);
+ void setSortingChoiceValue(GeneralSettings *settings);
void loadSortingChoiceSettings();
private:
QUrl m_url;
- QRadioButton* m_localViewProps;
- QRadioButton* m_globalViewProps;
+ QRadioButton *m_localViewProps;
+ QRadioButton *m_globalViewProps;
- QCheckBox* m_showToolTips;
- QLabel* m_configureToolTips;
- QCheckBox* m_showSelectionToggle;
+ QCheckBox *m_showToolTips;
+ QLabel *m_configureToolTips;
+ QCheckBox *m_showSelectionToggle;
- QRadioButton* m_naturalSorting;
- QRadioButton* m_caseSensitiveSorting;
- QRadioButton* m_caseInsensitiveSorting;
+ QRadioButton *m_naturalSorting;
+ QRadioButton *m_caseSensitiveSorting;
+ QRadioButton *m_caseInsensitiveSorting;
- QCheckBox* m_renameInline;
- QCheckBox* m_useTabForSplitViewSwitch;
- QCheckBox* m_closeActiveSplitView;
+ QCheckBox *m_renameInline;
+ QCheckBox *m_useTabForSplitViewSwitch;
+ QCheckBox *m_closeActiveSplitView;
};
#endif
#include <QUrl>
#include <QVBoxLayout>
-ConfigurePreviewPluginDialog::ConfigurePreviewPluginDialog(const QString& pluginName,
- const QString& desktopEntryName,
- QWidget* parent) :
- QDialog(parent)
+ConfigurePreviewPluginDialog::ConfigurePreviewPluginDialog(const QString &pluginName, const QString &desktopEntryName, QWidget *parent)
+ : QDialog(parent)
{
QSharedPointer<ThumbCreator> previewPlugin;
const QString pluginPath = QPluginLoader(desktopEntryName).fileName();
if (!pluginPath.isEmpty()) {
newCreator create = (newCreator)QLibrary::resolve(pluginPath, "new_creator");
if (create) {
- previewPlugin.reset(dynamic_cast<ThumbCreator*>(create()));
+ previewPlugin.reset(dynamic_cast<ThumbCreator *>(create()));
}
}
* widget.
* @param parent Parent widget.
*/
- ConfigurePreviewPluginDialog(const QString& pluginName,
- const QString& desktopEntryName,
- QWidget* parent);
+ ConfigurePreviewPluginDialog(const QString &pluginName, const QString &desktopEntryName, QWidget *parent);
~ConfigurePreviewPluginDialog() override = default;
};
#endif // KIOWIDGETS_BUILD_DEPRECATED_SINCE
#include <QCheckBox>
#include <QComboBox>
-#include <QLabel>
#include <QHBoxLayout>
+#include <QLabel>
#include <QVBoxLayout>
-namespace {
- enum ScriptExecution
- {
- AlwaysAsk = 0,
- Open = 1,
- Execute = 2
- };
-
- const bool ConfirmEmptyTrash = true;
- const bool ConfirmTrash = false;
- const bool ConfirmDelete = true;
- const int ConfirmScriptExecution = ScriptExecution::AlwaysAsk;
+namespace
+{
+enum ScriptExecution { AlwaysAsk = 0, Open = 1, Execute = 2 };
+
+const bool ConfirmEmptyTrash = true;
+const bool ConfirmTrash = false;
+const bool ConfirmDelete = true;
+const int ConfirmScriptExecution = ScriptExecution::AlwaysAsk;
}
-ConfirmationsSettingsPage::ConfirmationsSettingsPage(QWidget* parent) :
- SettingsPageBase(parent),
- m_confirmMoveToTrash(nullptr),
- m_confirmEmptyTrash(nullptr),
- m_confirmDelete(nullptr),
+ConfirmationsSettingsPage::ConfirmationsSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_confirmMoveToTrash(nullptr)
+ , m_confirmEmptyTrash(nullptr)
+ , m_confirmDelete(nullptr)
+ ,
#if HAVE_TERMINAL
- m_confirmClosingTerminalRunningProgram(nullptr),
+ m_confirmClosingTerminalRunningProgram(nullptr)
+ ,
#endif
m_confirmClosingMultipleTabs(nullptr)
{
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
- QLabel* confirmLabelKde = new QLabel(i18nc("@title:group", "Ask for confirmation in all KDE applications when:"), this);
+ QLabel *confirmLabelKde = new QLabel(i18nc("@title:group", "Ask for confirmation in all KDE applications when:"), this);
confirmLabelKde->setWordWrap(true);
- m_confirmMoveToTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when",
- "Moving files or folders to trash"), this);
- m_confirmEmptyTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when",
- "Emptying trash"), this);
- m_confirmDelete = new QCheckBox(i18nc("@option:check Ask for confirmation when",
- "Deleting files or folders"), this);
+ m_confirmMoveToTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when", "Moving files or folders to trash"), this);
+ m_confirmEmptyTrash = new QCheckBox(i18nc("@option:check Ask for confirmation when", "Emptying trash"), this);
+ m_confirmDelete = new QCheckBox(i18nc("@option:check Ask for confirmation when", "Deleting files or folders"), this);
- QLabel* confirmLabelDolphin = new QLabel(i18nc("@title:group", "Ask for confirmation in Dolphin when:"), this);
+ QLabel *confirmLabelDolphin = new QLabel(i18nc("@title:group", "Ask for confirmation in Dolphin when:"), this);
confirmLabelDolphin->setWordWrap(true);
- m_confirmClosingMultipleTabs = new QCheckBox(i18nc("@option:check Ask for confirmation in Dolphin when",
- "Closing windows with multiple tabs"), this);
+ m_confirmClosingMultipleTabs = new QCheckBox(i18nc("@option:check Ask for confirmation in Dolphin when", "Closing windows with multiple tabs"), this);
#if HAVE_TERMINAL
- m_confirmClosingTerminalRunningProgram = new QCheckBox(i18nc("@option:check Ask for confirmation when",
- "Closing windows with a program running in the Terminal panel"), this);
+ m_confirmClosingTerminalRunningProgram =
+ new QCheckBox(i18nc("@option:check Ask for confirmation when", "Closing windows with a program running in the Terminal panel"), this);
#endif
- QHBoxLayout* executableScriptLayout = new QHBoxLayout();
- QLabel* executableScriptLabel = new QLabel(i18nc("@title:group", "When opening an executable file:"), this);
+ QHBoxLayout *executableScriptLayout = new QHBoxLayout();
+ QLabel *executableScriptLabel = new QLabel(i18nc("@title:group", "When opening an executable file:"), this);
confirmLabelKde->setWordWrap(true);
executableScriptLayout->addWidget(executableScriptLabel);
}
kioConfig->sync();
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->setConfirmClosingMultipleTabs(m_confirmClosingMultipleTabs->isChecked());
#if HAVE_TERMINAL
void ConfirmationsSettingsPage::restoreDefaults()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->useDefaults(true);
loadSettings();
settings->useDefaults(false);
m_confirmClosingTerminalRunningProgram->setChecked(GeneralSettings::confirmClosingTerminalRunningProgram());
#endif
}
-
Q_OBJECT
public:
- explicit ConfirmationsSettingsPage(QWidget* parent);
+ explicit ConfirmationsSettingsPage(QWidget *parent);
~ConfirmationsSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
void loadSettings();
private:
- QCheckBox* m_confirmMoveToTrash;
- QCheckBox* m_confirmEmptyTrash;
- QCheckBox* m_confirmDelete;
+ QCheckBox *m_confirmMoveToTrash;
+ QCheckBox *m_confirmEmptyTrash;
+ QCheckBox *m_confirmDelete;
#if HAVE_TERMINAL
- QCheckBox* m_confirmClosingTerminalRunningProgram;
+ QCheckBox *m_confirmClosingTerminalRunningProgram;
#endif
- QCheckBox* m_confirmClosingMultipleTabs;
- QComboBox* m_confirmScriptExecution;
+ QCheckBox *m_confirmClosingMultipleTabs;
+ QComboBox *m_confirmScriptExecution;
};
#endif
#include <QTabWidget>
#include <QVBoxLayout>
-GeneralSettingsPage::GeneralSettingsPage(const QUrl& url, QWidget* parent) :
- SettingsPageBase(parent),
- m_pages()
+GeneralSettingsPage::GeneralSettingsPage(const QUrl &url, QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_pages()
{
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
- QTabWidget* tabWidget = new QTabWidget(this);
+ QTabWidget *tabWidget = new QTabWidget(this);
// initialize 'Behavior' tab
- BehaviorSettingsPage* behaviorPage = new BehaviorSettingsPage(url, tabWidget);
+ BehaviorSettingsPage *behaviorPage = new BehaviorSettingsPage(url, tabWidget);
tabWidget->addTab(behaviorPage, i18nc("@title:tab Behavior settings", "Behavior"));
connect(behaviorPage, &BehaviorSettingsPage::changed, this, &GeneralSettingsPage::changed);
// initialize 'Previews' tab
- PreviewsSettingsPage* previewsPage = new PreviewsSettingsPage(tabWidget);
+ PreviewsSettingsPage *previewsPage = new PreviewsSettingsPage(tabWidget);
tabWidget->addTab(previewsPage, i18nc("@title:tab Previews settings", "Previews"));
connect(previewsPage, &PreviewsSettingsPage::changed, this, &GeneralSettingsPage::changed);
// initialize 'Context Menu' tab
- ConfirmationsSettingsPage* confirmationsPage = new ConfirmationsSettingsPage(tabWidget);
+ ConfirmationsSettingsPage *confirmationsPage = new ConfirmationsSettingsPage(tabWidget);
tabWidget->addTab(confirmationsPage, i18nc("@title:tab Confirmations settings", "Confirmations"));
connect(confirmationsPage, &ConfirmationsSettingsPage::changed, this, &GeneralSettingsPage::changed);
// initialize 'Status Bar' tab
- StatusBarSettingsPage* statusBarPage = new StatusBarSettingsPage(tabWidget);
+ StatusBarSettingsPage *statusBarPage = new StatusBarSettingsPage(tabWidget);
tabWidget->addTab(statusBarPage, i18nc("@title:tab Status Bar settings", "Status Bar"));
connect(statusBarPage, &StatusBarSettingsPage::changed, this, &GeneralSettingsPage::changed);
void GeneralSettingsPage::applySettings()
{
- for (SettingsPageBase* page : qAsConst(m_pages)) {
+ for (SettingsPageBase *page : qAsConst(m_pages)) {
page->applySettings();
}
}
void GeneralSettingsPage::restoreDefaults()
{
- for (SettingsPageBase* page : qAsConst(m_pages)) {
+ for (SettingsPageBase *page : qAsConst(m_pages)) {
page->restoreDefaults();
}
}
-
Q_OBJECT
public:
- GeneralSettingsPage(const QUrl& url, QWidget* parent);
+ GeneralSettingsPage(const QUrl &url, QWidget *parent);
~GeneralSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
void restoreDefaults() override;
private:
- QList<SettingsPageBase*> m_pages;
+ QList<SettingsPageBase *> m_pages;
};
#endif
#include "previewssettingspage.h"
-#include "dolphin_generalsettings.h"
#include "configurepreviewplugindialog.h"
+#include "dolphin_generalsettings.h"
#include "settings/serviceitemdelegate.h"
#include "settings/servicemodel.h"
#include <QSpinBox>
// default settings
-namespace {
- const int DefaultMaxLocalPreviewSize = 0; // 0 MB
- const int DefaultMaxRemotePreviewSize = 0; // 0 MB
+namespace
+{
+const int DefaultMaxLocalPreviewSize = 0; // 0 MB
+const int DefaultMaxRemotePreviewSize = 0; // 0 MB
}
-PreviewsSettingsPage::PreviewsSettingsPage(QWidget* parent) :
- SettingsPageBase(parent),
- m_initialized(false),
- m_listView(nullptr),
- m_enabledPreviewPlugins(),
- m_localFileSizeBox(nullptr),
- m_remoteFileSizeBox(nullptr)
+PreviewsSettingsPage::PreviewsSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_initialized(false)
+ , m_listView(nullptr)
+ , m_enabledPreviewPlugins()
+ , m_localFileSizeBox(nullptr)
+ , m_remoteFileSizeBox(nullptr)
{
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
- QLabel* showPreviewsLabel = new QLabel(i18nc("@title:group", "Show previews in the view for:"), this);
+ QLabel *showPreviewsLabel = new QLabel(i18nc("@title:group", "Show previews in the view for:"), this);
m_listView = new QListView(this);
QScroller::grabGesture(m_listView->viewport(), QScroller::TouchGesture);
#if KIOWIDGETS_BUILD_DEPRECATED_SINCE(5, 87)
- ServiceItemDelegate* delegate = new ServiceItemDelegate(m_listView, m_listView);
- connect(delegate, &ServiceItemDelegate::requestServiceConfiguration,
- this, &PreviewsSettingsPage::configureService);
+ ServiceItemDelegate *delegate = new ServiceItemDelegate(m_listView, m_listView);
+ connect(delegate, &ServiceItemDelegate::requestServiceConfiguration, this, &PreviewsSettingsPage::configureService);
m_listView->setItemDelegate(delegate);
#endif
- ServiceModel* serviceModel = new ServiceModel(this);
- QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this);
+ ServiceModel *serviceModel = new ServiceModel(this);
+ QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(serviceModel);
proxyModel->setSortRole(Qt::DisplayRole);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
m_listView->setVerticalScrollMode(QListView::ScrollPerPixel);
m_listView->setUniformItemSizes(true);
- QLabel* localFileSizeLabel = new QLabel(i18n("Skip previews for local files above:"), this);
+ QLabel *localFileSizeLabel = new QLabel(i18n("Skip previews for local files above:"), this);
m_localFileSizeBox = new QSpinBox(this);
m_localFileSizeBox->setSingleStep(1);
m_localFileSizeBox->setRange(0, 9999999); /* MB */
m_localFileSizeBox->setSpecialValueText(i18n("No limit"));
- QHBoxLayout* localFileSizeBoxLayout = new QHBoxLayout();
+ QHBoxLayout *localFileSizeBoxLayout = new QHBoxLayout();
localFileSizeBoxLayout->addWidget(localFileSizeLabel);
localFileSizeBoxLayout->addStretch(0);
localFileSizeBoxLayout->addWidget(m_localFileSizeBox);
- QLabel* remoteFileSizeLabel = new QLabel(i18nc("@label", "Skip previews for remote files above:"), this);
+ QLabel *remoteFileSizeLabel = new QLabel(i18nc("@label", "Skip previews for remote files above:"), this);
m_remoteFileSizeBox = new QSpinBox(this);
m_remoteFileSizeBox->setSingleStep(1);
m_remoteFileSizeBox->setRange(0, 9999999); /* MB */
m_remoteFileSizeBox->setSpecialValueText(i18n("No previews"));
- QHBoxLayout* remoteFileSizeBoxLayout = new QHBoxLayout();
+ QHBoxLayout *remoteFileSizeBoxLayout = new QHBoxLayout();
remoteFileSizeBoxLayout->addWidget(remoteFileSizeLabel);
remoteFileSizeBoxLayout->addStretch(0);
remoteFileSizeBoxLayout->addWidget(m_remoteFileSizeBox);
void PreviewsSettingsPage::applySettings()
{
- const QAbstractItemModel* model = m_listView->model();
+ const QAbstractItemModel *model = m_listView->model();
const int rowCount = model->rowCount();
if (rowCount > 0) {
m_enabledPreviewPlugins.clear();
globalConfig.deleteEntry("MaximumSize", KConfigBase::Normal | KConfigBase::Global);
} else {
const qulonglong maximumLocalSize = static_cast<qulonglong>(m_localFileSizeBox->value()) * 1024 * 1024;
- globalConfig.writeEntry("MaximumSize",
- maximumLocalSize,
- KConfigBase::Normal | KConfigBase::Global);
+ globalConfig.writeEntry("MaximumSize", maximumLocalSize, KConfigBase::Normal | KConfigBase::Global);
}
const qulonglong maximumRemoteSize = static_cast<qulonglong>(m_remoteFileSizeBox->value()) * 1024 * 1024;
- globalConfig.writeEntry("MaximumRemoteSize",
- maximumRemoteSize,
- KConfigBase::Normal | KConfigBase::Global);
+ globalConfig.writeEntry("MaximumRemoteSize", maximumRemoteSize, KConfigBase::Normal | KConfigBase::Global);
globalConfig.sync();
}
m_remoteFileSizeBox->setValue(DefaultMaxRemotePreviewSize);
}
-void PreviewsSettingsPage::showEvent(QShowEvent* event)
+void PreviewsSettingsPage::showEvent(QShowEvent *event)
{
if (!event->spontaneous() && !m_initialized) {
loadPreviewPlugins();
}
#if KIOWIDGETS_BUILD_DEPRECATED_SINCE(5, 87)
-void PreviewsSettingsPage::configureService(const QModelIndex& index)
+void PreviewsSettingsPage::configureService(const QModelIndex &index)
{
- const QAbstractItemModel* model = index.model();
+ const QAbstractItemModel *model = index.model();
const QString pluginName = model->data(index).toString();
const QString desktopEntryName = model->data(index, ServiceModel::DesktopEntryNameRole).toString();
- ConfigurePreviewPluginDialog* dialog = new ConfigurePreviewPluginDialog(pluginName, desktopEntryName, this);
+ ConfigurePreviewPluginDialog *dialog = new ConfigurePreviewPluginDialog(pluginName, desktopEntryName, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
}
void PreviewsSettingsPage::loadPreviewPlugins()
{
- QAbstractItemModel* model = m_listView->model();
+ QAbstractItemModel *model = m_listView->model();
const QVector<KPluginMetaData> plugins = KIO::PreviewJob::availableThumbnailerPlugins();
for (const KPluginMetaData &plugin : plugins) {
#ifndef PREVIEWSSETTINGSPAGE_H
#define PREVIEWSSETTINGSPAGE_H
-
#include <kiowidgets_export.h>
#include "settings/settingspagebase.h"
Q_OBJECT
public:
- explicit PreviewsSettingsPage(QWidget* parent);
+ explicit PreviewsSettingsPage(QWidget *parent);
~PreviewsSettingsPage() override;
/**
void restoreDefaults() override;
protected:
- void showEvent(QShowEvent* event) override;
+ void showEvent(QShowEvent *event) override;
private Q_SLOTS:
#if KIOWIDGETS_BUILD_DEPRECATED_SINCE(5, 87)
- void configureService(const QModelIndex& index);
+ void configureService(const QModelIndex &index);
#endif
private:
bool m_initialized;
QListView *m_listView;
QStringList m_enabledPreviewPlugins;
- QSpinBox* m_localFileSizeBox;
- QSpinBox* m_remoteFileSizeBox;
+ QSpinBox *m_localFileSizeBox;
+ QSpinBox *m_remoteFileSizeBox;
};
#endif
#include <QCheckBox>
#include <QVBoxLayout>
-StatusBarSettingsPage::StatusBarSettingsPage(QWidget* parent) :
- SettingsPageBase(parent),
- m_showStatusBar(nullptr),
- m_showZoomSlider(nullptr),
- m_showSpaceInfo(nullptr)
+StatusBarSettingsPage::StatusBarSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_showStatusBar(nullptr)
+ , m_showZoomSlider(nullptr)
+ , m_showSpaceInfo(nullptr)
{
m_showStatusBar = new QCheckBox(i18nc("@option:check", "Show status bar"), this);
m_showZoomSlider = new QCheckBox(i18nc("@option:check", "Show zoom slider"), this);
m_showSpaceInfo = new QCheckBox(i18nc("@option:check", "Show space information"), this);
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->addWidget(m_showStatusBar);
topLayout->addWidget(m_showZoomSlider);
topLayout->addWidget(m_showSpaceInfo);
void StatusBarSettingsPage::applySettings()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->setShowStatusBar(m_showStatusBar->isChecked());
settings->setShowZoomSlider(m_showZoomSlider->isChecked());
settings->setShowSpaceInfo(m_showSpaceInfo->isChecked());
void StatusBarSettingsPage::restoreDefaults()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->useDefaults(true);
loadSettings();
settings->useDefaults(false);
onShowStatusBarToggled();
}
-
Q_OBJECT
public:
- explicit StatusBarSettingsPage(QWidget* parent);
+ explicit StatusBarSettingsPage(QWidget *parent);
~StatusBarSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
void onShowStatusBarToggled();
private:
- QCheckBox* m_showStatusBar;
- QCheckBox* m_showZoomSlider;
- QCheckBox* m_showSpaceInfo;
+ QCheckBox *m_showStatusBar;
+ QCheckBox *m_showZoomSlider;
+ QCheckBox *m_showSpaceInfo;
};
#endif
#include "kcmdolphingeneral.h"
#include "settings/general/behaviorsettingspage.h"
-#include "settings/general/previewssettingspage.h"
#include "settings/general/confirmationssettingspage.h"
+#include "settings/general/previewssettingspage.h"
#include <KLocalizedString>
#include <KPluginFactory>
K_PLUGIN_CLASS_WITH_JSON(DolphinGeneralConfigModule, "kcmdolphingeneral.json")
-DolphinGeneralConfigModule::DolphinGeneralConfigModule(QWidget *parent, const QVariantList &args) :
- KCModule(parent, args),
- m_pages()
+DolphinGeneralConfigModule::DolphinGeneralConfigModule(QWidget *parent, const QVariantList &args)
+ : KCModule(parent, args)
+ , m_pages()
{
setButtons(KCModule::Default | KCModule::Help | KCModule::Apply);
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
- QTabWidget* tabWidget = new QTabWidget(this);
+ QTabWidget *tabWidget = new QTabWidget(this);
// initialize 'Behavior' tab
- BehaviorSettingsPage* behaviorPage = new BehaviorSettingsPage(QUrl::fromLocalFile(QDir::homePath()), tabWidget);
+ BehaviorSettingsPage *behaviorPage = new BehaviorSettingsPage(QUrl::fromLocalFile(QDir::homePath()), tabWidget);
tabWidget->addTab(behaviorPage, i18nc("@title:tab Behavior settings", "Behavior"));
connect(behaviorPage, &BehaviorSettingsPage::changed, this, &DolphinGeneralConfigModule::markAsChanged);
// initialize 'Previews' tab
- PreviewsSettingsPage* previewsPage = new PreviewsSettingsPage(tabWidget);
+ PreviewsSettingsPage *previewsPage = new PreviewsSettingsPage(tabWidget);
tabWidget->addTab(previewsPage, i18nc("@title:tab Previews settings", "Previews"));
connect(previewsPage, &PreviewsSettingsPage::changed, this, &DolphinGeneralConfigModule::markAsChanged);
// initialize 'Confirmations' tab
- ConfirmationsSettingsPage* confirmationsPage = new ConfirmationsSettingsPage(tabWidget);
- tabWidget->addTab(confirmationsPage, i18nc("@title:tab Confirmations settings", "Confirmations"));
+ ConfirmationsSettingsPage *confirmationsPage = new ConfirmationsSettingsPage(tabWidget);
+ tabWidget->addTab(confirmationsPage, i18nc("@title:tab Confirmations settings", "Confirmations"));
connect(confirmationsPage, &ConfirmationsSettingsPage::changed, this, &DolphinGeneralConfigModule::markAsChanged);
m_pages.append(behaviorPage);
m_pages.append(previewsPage);
void DolphinGeneralConfigModule::save()
{
- for (SettingsPageBase* page : qAsConst(m_pages)) {
+ for (SettingsPageBase *page : qAsConst(m_pages)) {
page->applySettings();
}
}
void DolphinGeneralConfigModule::defaults()
{
- for (SettingsPageBase* page : qAsConst(m_pages)) {
+ for (SettingsPageBase *page : qAsConst(m_pages)) {
page->applySettings();
}
}
void defaults() override;
private:
- QList<SettingsPageBase*> m_pages;
+ QList<SettingsPageBase *> m_pages;
};
#endif
K_PLUGIN_CLASS_WITH_JSON(DolphinNavigationConfigModule, "kcmdolphinnavigation.json")
-DolphinNavigationConfigModule::DolphinNavigationConfigModule(QWidget *parent, const QVariantList &args) :
- KCModule(parent, args),
- m_navigation(nullptr)
+DolphinNavigationConfigModule::DolphinNavigationConfigModule(QWidget *parent, const QVariantList &args)
+ : KCModule(parent, args)
+ , m_navigation(nullptr)
{
setButtons(KCModule::Default | KCModule::Help | KCModule::Apply);
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
m_navigation = new NavigationSettingsPage(this);
K_PLUGIN_CLASS_WITH_JSON(DolphinViewModesConfigModule, "kcmdolphinviewmodes.json")
-DolphinViewModesConfigModule::DolphinViewModesConfigModule(QWidget *parent, const QVariantList &args) :
- KCModule(parent, args),
- m_tabs()
+DolphinViewModesConfigModule::DolphinViewModesConfigModule(QWidget *parent, const QVariantList &args)
+ : KCModule(parent, args)
+ , m_tabs()
{
setButtons(KCModule::Default | KCModule::Help | KCModule::Apply);
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
- QTabWidget* tabWidget = new QTabWidget(this);
+ QTabWidget *tabWidget = new QTabWidget(this);
// Initialize 'Icons' tab
- ViewSettingsTab* iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget);
+ ViewSettingsTab *iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget);
tabWidget->addTab(iconsTab, QIcon::fromTheme(QStringLiteral("view-list-icons")), i18nc("@title:tab", "Icons"));
connect(iconsTab, &ViewSettingsTab::changed, this, &DolphinViewModesConfigModule::viewModeChanged);
// Initialize 'Compact' tab
- ViewSettingsTab* compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget);
+ ViewSettingsTab *compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget);
tabWidget->addTab(compactTab, QIcon::fromTheme(QStringLiteral("view-list-details")), i18nc("@title:tab", "Compact"));
connect(compactTab, &ViewSettingsTab::changed, this, &DolphinViewModesConfigModule::viewModeChanged);
// Initialize 'Details' tab
- ViewSettingsTab* detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget);
+ ViewSettingsTab *detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget);
tabWidget->addTab(detailsTab, QIcon::fromTheme(QStringLiteral("view-list-tree")), i18nc("@title:tab", "Details"));
connect(detailsTab, &ViewSettingsTab::changed, this, &DolphinViewModesConfigModule::viewModeChanged);
void DolphinViewModesConfigModule::reparseConfiguration()
{
- QDBusMessage message = QDBusMessage::createSignal(QStringLiteral("/KonqMain"),
- QStringLiteral("org.kde.Konqueror.Main"),
- QStringLiteral("reparseConfiguration"));
+ QDBusMessage message =
+ QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration"));
QDBusConnection::sessionBus().send(message);
}
void reparseConfiguration();
private Q_SLOTS:
- void viewModeChanged();
+ void viewModeChanged();
private:
- QList<ViewSettingsTab*> m_tabs;
+ QList<ViewSettingsTab *> m_tabs;
};
#endif
#include "navigationsettingspage.h"
-#include "global.h"
#include "dolphin_generalsettings.h"
+#include "global.h"
#include <KLocalizedString>
#include <QFormLayout>
#include <QRadioButton>
-NavigationSettingsPage::NavigationSettingsPage(QWidget* parent) :
- SettingsPageBase(parent),
- m_openArchivesAsFolder(nullptr),
- m_autoExpandFolders(nullptr),
- m_openNewTabAfterLastTab(nullptr),
- m_openNewTabAfterCurrentTab(nullptr)
+NavigationSettingsPage::NavigationSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_openArchivesAsFolder(nullptr)
+ , m_autoExpandFolders(nullptr)
+ , m_openNewTabAfterLastTab(nullptr)
+ , m_openNewTabAfterCurrentTab(nullptr)
{
- QFormLayout* topLayout = new QFormLayout(this);
+ QFormLayout *topLayout = new QFormLayout(this);
// Tabs properties
m_openNewTabAfterCurrentTab = new QRadioButton(i18nc("option:radio", "After current tab"));
m_openNewTabAfterLastTab = new QRadioButton(i18nc("option:radio", "At end of tab bar"));
- QButtonGroup* tabsBehaviorGroup = new QButtonGroup(this);
+ QButtonGroup *tabsBehaviorGroup = new QButtonGroup(this);
tabsBehaviorGroup->addButton(m_openNewTabAfterCurrentTab);
tabsBehaviorGroup->addButton(m_openNewTabAfterLastTab);
topLayout->addRow(i18nc("@title:group", "Open new tabs: "), m_openNewTabAfterCurrentTab);
void NavigationSettingsPage::applySettings()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->setBrowseThroughArchives(m_openArchivesAsFolder->isChecked());
settings->setAutoExpandFolders(m_autoExpandFolders->isChecked());
settings->setOpenNewTabAfterLastTab(m_openNewTabAfterLastTab->isChecked());
void NavigationSettingsPage::restoreDefaults()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->useDefaults(true);
loadSettings();
settings->useDefaults(false);
m_openNewTabAfterLastTab->setChecked(GeneralSettings::openNewTabAfterLastTab());
m_openNewTabAfterCurrentTab->setChecked(!m_openNewTabAfterLastTab->isChecked());
}
-
Q_OBJECT
public:
- explicit NavigationSettingsPage(QWidget* parent);
+ explicit NavigationSettingsPage(QWidget *parent);
~NavigationSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
void loadSettings();
private:
- QCheckBox* m_openArchivesAsFolder;
- QCheckBox* m_autoExpandFolders;
- QRadioButton* m_openNewTabAfterLastTab;
- QRadioButton* m_openNewTabAfterCurrentTab;
+ QCheckBox *m_openArchivesAsFolder;
+ QCheckBox *m_autoExpandFolders;
+ QRadioButton *m_openNewTabAfterLastTab;
+ QRadioButton *m_openNewTabAfterCurrentTab;
};
#endif
#include <QPainter>
#include <QPushButton>
-ServiceItemDelegate::ServiceItemDelegate(QAbstractItemView* itemView, QObject* parent) :
- KWidgetItemDelegate(itemView, parent)
+ServiceItemDelegate::ServiceItemDelegate(QAbstractItemView *itemView, QObject *parent)
+ : KWidgetItemDelegate(itemView, parent)
{
}
{
}
-QSize ServiceItemDelegate::sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const
+QSize ServiceItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index)
const QStyle *style = itemView()->style();
- const int buttonHeight = style->pixelMetric(QStyle::PM_ButtonMargin) * 2 +
- style->pixelMetric(QStyle::PM_ButtonIconSize);
+ const int buttonHeight = style->pixelMetric(QStyle::PM_ButtonMargin) * 2 + style->pixelMetric(QStyle::PM_ButtonIconSize);
const int fontHeight = option.fontMetrics.height();
return QSize(100, qMax(buttonHeight, fontHeight));
}
-void ServiceItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
- const QModelIndex& index) const
+void ServiceItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_UNUSED(index)
painter->save();
painter->restore();
}
-QList<QWidget*> ServiceItemDelegate::createItemWidgets(const QModelIndex&) const
+QList<QWidget *> ServiceItemDelegate::createItemWidgets(const QModelIndex &) const
{
- QCheckBox* checkBox = new QCheckBox();
+ QCheckBox *checkBox = new QCheckBox();
QPalette palette = checkBox->palette();
palette.setColor(QPalette::WindowText, palette.color(QPalette::Text));
checkBox->setPalette(palette);
connect(checkBox, &QCheckBox::clicked, this, &ServiceItemDelegate::slotCheckBoxClicked);
- QPushButton* configureButton = new QPushButton();
+ QPushButton *configureButton = new QPushButton();
connect(configureButton, &QPushButton::clicked, this, &ServiceItemDelegate::slotConfigureButtonClicked);
return {checkBox, configureButton};
}
-void ServiceItemDelegate::updateItemWidgets(const QList<QWidget*> widgets,
- const QStyleOptionViewItem& option,
- const QPersistentModelIndex& index) const
+void ServiceItemDelegate::updateItemWidgets(const QList<QWidget *> widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const
{
- QCheckBox* checkBox = static_cast<QCheckBox*>(widgets[0]);
- QPushButton *configureButton = static_cast<QPushButton*>(widgets[1]);
+ QCheckBox *checkBox = static_cast<QCheckBox *>(widgets[0]);
+ QPushButton *configureButton = static_cast<QPushButton *>(widgets[1]);
const int itemHeight = sizeHint(option, index).height();
// Update the checkbox showing the service name and icon
- const QAbstractItemModel* model = index.model();
+ const QAbstractItemModel *model = index.model();
checkBox->setText(model->data(index).toString());
const QString iconName = model->data(index, Qt::DecorationRole).toString();
if (!iconName.isEmpty()) {
configureButton->setEnabled(checkBox->isChecked());
configureButton->setIcon(QIcon::fromTheme(QStringLiteral("configure")));
configureButton->resize(configureButton->sizeHint());
- configureButton->move(option.rect.right() - configureButton->width(),
- (itemHeight - configureButton->height()) / 2);
+ configureButton->move(option.rect.right() - configureButton->width(), (itemHeight - configureButton->height()) / 2);
}
configureButton->setVisible(configurable);
}
void ServiceItemDelegate::slotCheckBoxClicked(bool checked)
{
- QAbstractItemModel* model = const_cast<QAbstractItemModel*>(focusedIndex().model());
+ QAbstractItemModel *model = const_cast<QAbstractItemModel *>(focusedIndex().model());
model->setData(focusedIndex(), checked, Qt::CheckStateRole);
}
{
Q_EMIT requestServiceConfiguration(focusedIndex());
}
-
Q_OBJECT
public:
- explicit ServiceItemDelegate(QAbstractItemView* itemView, QObject* parent = nullptr);
+ explicit ServiceItemDelegate(QAbstractItemView *itemView, QObject *parent = nullptr);
~ServiceItemDelegate() override;
- QSize sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const override;
+ QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;
- void paint(QPainter* painter, const QStyleOptionViewItem& option,
- const QModelIndex& index) const override;
+ void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
- QList<QWidget*> createItemWidgets(const QModelIndex&) const override;
+ QList<QWidget *> createItemWidgets(const QModelIndex &) const override;
- void updateItemWidgets(const QList<QWidget*> widgets,
- const QStyleOptionViewItem& option,
- const QPersistentModelIndex& index) const override;
+ void updateItemWidgets(const QList<QWidget *> widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const override;
Q_SIGNALS:
- void requestServiceConfiguration(const QModelIndex& index);
+ void requestServiceConfiguration(const QModelIndex &index);
private Q_SLOTS:
void slotCheckBoxClicked(bool checked);
#include "servicemodel.h"
-ServiceModel::ServiceModel(QObject* parent) :
- QAbstractListModel(parent),
- m_items()
+ServiceModel::ServiceModel(QObject *parent)
+ : QAbstractListModel(parent)
+ , m_items()
{
}
{
}
-bool ServiceModel::insertRows(int row, int count, const QModelIndex& parent)
+bool ServiceModel::insertRows(int row, int count, const QModelIndex &parent)
{
if (row > rowCount()) {
return false;
return true;
}
-bool ServiceModel::setData(const QModelIndex& index, const QVariant& value, int role)
+bool ServiceModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
const int row = index.row();
if (row >= rowCount()) {
return true;
}
-QVariant ServiceModel::data(const QModelIndex& index, int role) const
+QVariant ServiceModel::data(const QModelIndex &index, int role) const
{
const int row = index.row();
if (row < rowCount()) {
switch (role) {
- case ConfigurableRole: return m_items[row].configurable;
- case Qt::CheckStateRole: return m_items[row].checked;
- case Qt::DecorationRole: return m_items[row].icon;
- case Qt::DisplayRole: return m_items[row].text;
- case DesktopEntryNameRole: return m_items[row].desktopEntryName;
- default: break;
+ case ConfigurableRole:
+ return m_items[row].configurable;
+ case Qt::CheckStateRole:
+ return m_items[row].checked;
+ case Qt::DecorationRole:
+ return m_items[row].icon;
+ case Qt::DisplayRole:
+ return m_items[row].text;
+ case DesktopEntryNameRole:
+ return m_items[row].desktopEntryName;
+ default:
+ break;
}
}
return QVariant();
}
-int ServiceModel::rowCount(const QModelIndex& parent) const
+int ServiceModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_items.count();
m_items.clear();
endRemoveRows();
}
-
Q_OBJECT
public:
- enum Role
- {
- DesktopEntryNameRole = Qt::UserRole,
- ConfigurableRole
- };
+ enum Role { DesktopEntryNameRole = Qt::UserRole, ConfigurableRole };
- explicit ServiceModel(QObject* parent = nullptr);
+ explicit ServiceModel(QObject *parent = nullptr);
~ServiceModel() override;
- bool insertRows(int row, int count, const QModelIndex & parent = QModelIndex()) override;
- bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
- QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
- int rowCount(const QModelIndex& parent = QModelIndex()) const override;
+ bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override;
+ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const override;
void clear();
- private:
- struct ServiceItem
- {
+private:
+ struct ServiceItem {
bool checked;
bool configurable;
QString icon;
#include "settingspagebase.h"
-SettingsPageBase::SettingsPageBase(QWidget* parent) :
- QWidget(parent)
-{}
+SettingsPageBase::SettingsPageBase(QWidget *parent)
+ : QWidget(parent)
+{
+}
SettingsPageBase::~SettingsPageBase()
-{}
-
-
+{
+}
Q_OBJECT
public:
- explicit SettingsPageBase(QWidget* parent = nullptr);
+ explicit SettingsPageBase(QWidget *parent = nullptr);
~SettingsPageBase() override;
/**
#include <QButtonGroup>
#include <QCheckBox>
#include <QFileDialog>
-#include <QLineEdit>
-#include <QPushButton>
-#include <QRadioButton>
#include <QFormLayout>
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QRadioButton>
-StartupSettingsPage::StartupSettingsPage(const QUrl& url, QWidget* parent) :
- SettingsPageBase(parent),
- m_url(url),
- m_homeUrl(nullptr),
- m_homeUrlBoxLayoutContainer(nullptr),
- m_buttonBoxLayoutContainer(nullptr),
- m_rememberOpenedTabsRadioButton(nullptr),
- m_homeUrlRadioButton(nullptr),
- m_splitView(nullptr),
- m_editableUrl(nullptr),
- m_showFullPath(nullptr),
- m_filterBar(nullptr),
- m_showFullPathInTitlebar(nullptr),
- m_openExternallyCalledFolderInNewTab(nullptr)
+StartupSettingsPage::StartupSettingsPage(const QUrl &url, QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_url(url)
+ , m_homeUrl(nullptr)
+ , m_homeUrlBoxLayoutContainer(nullptr)
+ , m_buttonBoxLayoutContainer(nullptr)
+ , m_rememberOpenedTabsRadioButton(nullptr)
+ , m_homeUrlRadioButton(nullptr)
+ , m_splitView(nullptr)
+ , m_editableUrl(nullptr)
+ , m_showFullPath(nullptr)
+ , m_filterBar(nullptr)
+ , m_showFullPathInTitlebar(nullptr)
+ , m_openExternallyCalledFolderInNewTab(nullptr)
{
- QFormLayout* topLayout = new QFormLayout(this);
+ QFormLayout *topLayout = new QFormLayout(this);
m_rememberOpenedTabsRadioButton = new QRadioButton(i18nc("@option:radio Startup Settings", "Folders, tabs, and window state from last time"));
m_homeUrlRadioButton = new QRadioButton();
// HACK: otherwise the radio button has too much spacing in a grid layout
m_homeUrlRadioButton->setMaximumWidth(24);
- QButtonGroup* initialViewGroup = new QButtonGroup(this);
+ QButtonGroup *initialViewGroup = new QButtonGroup(this);
initialViewGroup->addButton(m_rememberOpenedTabsRadioButton);
initialViewGroup->addButton(m_homeUrlRadioButton);
-
// create 'Home URL' editor
m_homeUrlBoxLayoutContainer = new QWidget(this);
- QHBoxLayout* homeUrlBoxLayout = new QHBoxLayout(m_homeUrlBoxLayoutContainer);
+ QHBoxLayout *homeUrlBoxLayout = new QHBoxLayout(m_homeUrlBoxLayoutContainer);
homeUrlBoxLayout->setContentsMargins(0, 0, 0, 0);
m_homeUrl = new QLineEdit();
m_homeUrl->setClearButtonEnabled(true);
homeUrlBoxLayout->addWidget(m_homeUrl);
- QPushButton* selectHomeUrlButton = new QPushButton(QIcon::fromTheme(QStringLiteral("folder-open")), QString());
+ QPushButton *selectHomeUrlButton = new QPushButton(QIcon::fromTheme(QStringLiteral("folder-open")), QString());
homeUrlBoxLayout->addWidget(selectHomeUrlButton);
#ifndef QT_NO_ACCESSIBILITY
selectHomeUrlButton->setAccessibleName(i18nc("@action:button", "Select Home Location"));
#endif
- connect(selectHomeUrlButton, &QPushButton::clicked,
- this, &StartupSettingsPage::selectHomeUrl);
+ connect(selectHomeUrlButton, &QPushButton::clicked, this, &StartupSettingsPage::selectHomeUrl);
m_buttonBoxLayoutContainer = new QWidget(this);
- QHBoxLayout* buttonBoxLayout = new QHBoxLayout(m_buttonBoxLayoutContainer);
+ QHBoxLayout *buttonBoxLayout = new QHBoxLayout(m_buttonBoxLayoutContainer);
buttonBoxLayout->setContentsMargins(0, 0, 0, 0);
- QPushButton* useCurrentButton = new QPushButton(i18nc("@action:button", "Use Current Location"));
+ QPushButton *useCurrentButton = new QPushButton(i18nc("@action:button", "Use Current Location"));
buttonBoxLayout->addWidget(useCurrentButton);
- connect(useCurrentButton, &QPushButton::clicked,
- this, &StartupSettingsPage::useCurrentLocation);
- QPushButton* useDefaultButton = new QPushButton(i18nc("@action:button", "Use Default Location"));
+ connect(useCurrentButton, &QPushButton::clicked, this, &StartupSettingsPage::useCurrentLocation);
+ QPushButton *useDefaultButton = new QPushButton(i18nc("@action:button", "Use Default Location"));
buttonBoxLayout->addWidget(useDefaultButton);
- connect(useDefaultButton, &QPushButton::clicked,
- this, &StartupSettingsPage::useDefaultLocation);
+ connect(useDefaultButton, &QPushButton::clicked, this, &StartupSettingsPage::useDefaultLocation);
- QGridLayout* startInLocationLayout = new QGridLayout();
+ QGridLayout *startInLocationLayout = new QGridLayout();
startInLocationLayout->setHorizontalSpacing(0);
startInLocationLayout->setContentsMargins(0, 0, 0, 0);
startInLocationLayout->addWidget(m_homeUrlRadioButton, 0, 0);
topLayout->addRow(i18nc("@label:textbox", "Show on startup:"), m_rememberOpenedTabsRadioButton);
topLayout->addRow(QString(), startInLocationLayout);
-
topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed));
m_splitView = new QCheckBox(i18nc("@option:check Startup Settings", "Begin in split view mode"));
connect(m_rememberOpenedTabsRadioButton, &QRadioButton::toggled, this, &StartupSettingsPage::slotSettingsChanged);
connect(m_homeUrlRadioButton, &QRadioButton::toggled, this, &StartupSettingsPage::slotSettingsChanged);
- connect(m_splitView, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
- connect(m_editableUrl, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
- connect(m_filterBar, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
+ connect(m_splitView, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
+ connect(m_editableUrl, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
+ connect(m_filterBar, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
connect(m_openExternallyCalledFolderInNewTab, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
connect(m_showFullPath, &QCheckBox::toggled, this, &StartupSettingsPage::slotSettingsChanged);
void StartupSettingsPage::applySettings()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
const QUrl url(QUrl::fromUserInput(m_homeUrl->text(), QString(), QUrl::AssumeLocalFile));
if (url.isValid() && KProtocolManager::supportsListing(url)) {
- KIO::StatJob* job = KIO::statDetails(url, KIO::StatJob::SourceSide, KIO::StatDetail::StatBasic, KIO::JobFlag::HideProgressInfo);
- connect(job, &KJob::result, this, [this, settings, url](KJob* job) {
- if (job->error() == 0 && qobject_cast<KIO::StatJob*>(job)->statResult().isDir()) {
+ KIO::StatJob *job = KIO::statDetails(url, KIO::StatJob::SourceSide, KIO::StatDetail::StatBasic, KIO::JobFlag::HideProgressInfo);
+ connect(job, &KJob::result, this, [this, settings, url](KJob *job) {
+ if (job->error() == 0 && qobject_cast<KIO::StatJob *>(job)->statResult().isDir()) {
settings->setHomeUrl(url.toDisplayString(QUrl::PreferLocalFile));
} else {
showSetDefaultDirectoryError();
void StartupSettingsPage::restoreDefaults()
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->useDefaults(true);
loadSettings();
settings->useDefaults(false);
Q_OBJECT
public:
- StartupSettingsPage(const QUrl& url, QWidget* parent);
+ StartupSettingsPage(const QUrl &url, QWidget *parent);
~StartupSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
private:
QUrl m_url;
- QLineEdit* m_homeUrl;
- QWidget* m_homeUrlBoxLayoutContainer;
- QWidget* m_buttonBoxLayoutContainer;
- QRadioButton* m_rememberOpenedTabsRadioButton;
- QRadioButton* m_homeUrlRadioButton;
+ QLineEdit *m_homeUrl;
+ QWidget *m_homeUrlBoxLayoutContainer;
+ QWidget *m_buttonBoxLayoutContainer;
+ QRadioButton *m_rememberOpenedTabsRadioButton;
+ QRadioButton *m_homeUrlRadioButton;
- QCheckBox* m_splitView;
- QCheckBox* m_editableUrl;
- QCheckBox* m_showFullPath;
- QCheckBox* m_filterBar;
- QCheckBox* m_showFullPathInTitlebar;
- QCheckBox* m_openExternallyCalledFolderInNewTab;
+ QCheckBox *m_splitView;
+ QCheckBox *m_editableUrl;
+ QCheckBox *m_showFullPath;
+ QCheckBox *m_filterBar;
+ QCheckBox *m_showFullPathInTitlebar;
+ QCheckBox *m_openExternallyCalledFolderInNewTab;
};
#endif
#include <QFormLayout>
-TrashSettingsPage::TrashSettingsPage(QWidget* parent) :
- SettingsPageBase(parent)
+TrashSettingsPage::TrashSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
{
- QFormLayout* topLayout = new QFormLayout(this);
+ QFormLayout *topLayout = new QFormLayout(this);
m_proxy = new KCModuleProxy(KPluginMetaData(QStringLiteral("kcm_trash")));
topLayout->addRow(m_proxy);
{
m_proxy->load();
}
-
Q_OBJECT
public:
- explicit TrashSettingsPage(QWidget* parent);
+ explicit TrashSettingsPage(QWidget *parent);
~TrashSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
#include <QVBoxLayout>
-UserFeedbackSettingsPage::UserFeedbackSettingsPage(QWidget* parent) :
- SettingsPageBase(parent)
+UserFeedbackSettingsPage::UserFeedbackSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
{
auto layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
feedbackProvider->setTelemetryMode(KUserFeedback::Provider::NoTelemetry);
feedbackProvider->setSurveyInterval(-1);
}
-
-
#include "settings/settingspagebase.h"
-namespace KUserFeedback {
+namespace KUserFeedback
+{
class FeedbackConfigWidget;
}
Q_OBJECT
public:
- explicit UserFeedbackSettingsPage(QWidget* parent);
+ explicit UserFeedbackSettingsPage(QWidget *parent);
~UserFeedbackSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
#include <QHBoxLayout>
#include <QPushButton>
-DolphinFontRequester::DolphinFontRequester(QWidget* parent) :
- QWidget(parent),
- m_modeCombo(nullptr),
- m_chooseFontButton(nullptr),
- m_mode(SystemFont),
- m_customFont()
+DolphinFontRequester::DolphinFontRequester(QWidget *parent)
+ : QWidget(parent)
+ , m_modeCombo(nullptr)
+ , m_chooseFontButton(nullptr)
+ , m_mode(SystemFont)
+ , m_customFont()
{
- QHBoxLayout* topLayout = new QHBoxLayout(this);
+ QHBoxLayout *topLayout = new QHBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
m_modeCombo = new QComboBox(this);
m_modeCombo->addItem(i18nc("@item:inlistbox Font", "System Font"));
m_modeCombo->addItem(i18nc("@item:inlistbox Font", "Custom Font"));
- connect(m_modeCombo, &QComboBox::activated,
- this, &DolphinFontRequester::changeMode);
+ connect(m_modeCombo, &QComboBox::activated, this, &DolphinFontRequester::changeMode);
m_chooseFontButton = new QPushButton(i18nc("@action:button Choose font", "Choose..."), this);
- connect(m_chooseFontButton, &QPushButton::clicked,
- this, &DolphinFontRequester::openFontDialog);
+ connect(m_chooseFontButton, &QPushButton::clicked, this, &DolphinFontRequester::openFontDialog);
changeMode(m_modeCombo->currentIndex());
return (m_mode == CustomFont) ? m_customFont : QFontDatabase::systemFont(QFontDatabase::GeneralFont);
}
-void DolphinFontRequester::setCustomFont(const QFont& font)
+void DolphinFontRequester::setCustomFont(const QFont &font)
{
m_customFont = font;
}
setMode((index == CustomFont) ? CustomFont : SystemFont);
Q_EMIT changed();
}
-
Q_OBJECT
public:
- enum Mode
- {
- SystemFont = 0,
- CustomFont = 1
- };
+ enum Mode { SystemFont = 0, CustomFont = 1 };
- explicit DolphinFontRequester(QWidget* parent);
+ explicit DolphinFontRequester(QWidget *parent);
~DolphinFontRequester() override;
void setMode(Mode mode);
*/
QFont currentFont() const;
- void setCustomFont(const QFont& font);
+ void setCustomFont(const QFont &font);
QFont customFont() const;
Q_SIGNALS:
void changeMode(int index);
private:
- QComboBox* m_modeCombo;
- QPushButton* m_chooseFontButton;
+ QComboBox *m_modeCombo;
+ QPushButton *m_chooseFontButton;
Mode m_mode;
QFont m_customFont;
: ViewModeSettings()
{
switch (mode) {
- case DolphinView::IconsView: m_viewModeSettingsVariant = IconsModeSettings::self(); return;
- case DolphinView::CompactView: m_viewModeSettingsVariant = CompactModeSettings::self(); return;
- case DolphinView::DetailsView: m_viewModeSettingsVariant = DetailsModeSettings::self(); return;
+ case DolphinView::IconsView:
+ m_viewModeSettingsVariant = IconsModeSettings::self();
+ return;
+ case DolphinView::CompactView:
+ m_viewModeSettingsVariant = CompactModeSettings::self();
+ return;
+ case DolphinView::DetailsView:
+ m_viewModeSettingsVariant = DetailsModeSettings::self();
+ return;
default:
Q_UNREACHABLE();
}
: ViewModeSettings()
{
switch (mode) {
- case ViewSettingsTab::IconsMode: m_viewModeSettingsVariant = IconsModeSettings::self(); return;
- case ViewSettingsTab::CompactMode: m_viewModeSettingsVariant = CompactModeSettings::self(); return;
- case ViewSettingsTab::DetailsMode: m_viewModeSettingsVariant = DetailsModeSettings::self(); return;
+ case ViewSettingsTab::IconsMode:
+ m_viewModeSettingsVariant = IconsModeSettings::self();
+ return;
+ case ViewSettingsTab::CompactMode:
+ m_viewModeSettingsVariant = CompactModeSettings::self();
+ return;
+ case ViewSettingsTab::DetailsMode:
+ m_viewModeSettingsVariant = DetailsModeSettings::self();
+ return;
default:
Q_UNREACHABLE();
}
: ViewModeSettings()
{
switch (itemLayout) {
- case KStandardItemListView::IconsLayout: m_viewModeSettingsVariant = IconsModeSettings::self(); return;
- case KStandardItemListView::CompactLayout: m_viewModeSettingsVariant = CompactModeSettings::self(); return;
- case KStandardItemListView::DetailsLayout: m_viewModeSettingsVariant = DetailsModeSettings::self(); return;
+ case KStandardItemListView::IconsLayout:
+ m_viewModeSettingsVariant = IconsModeSettings::self();
+ return;
+ case KStandardItemListView::CompactLayout:
+ m_viewModeSettingsVariant = CompactModeSettings::self();
+ return;
+ case KStandardItemListView::DetailsLayout:
+ m_viewModeSettingsVariant = DetailsModeSettings::self();
+ return;
default:
Q_UNREACHABLE();
}
void ViewModeSettings::setIconSize(int iconSize)
{
- std::visit([iconSize](auto &&v) {
- v->setIconSize(iconSize);
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [iconSize](auto &&v) {
+ v->setIconSize(iconSize);
+ },
+ m_viewModeSettingsVariant);
}
int ViewModeSettings::iconSize() const
{
- return std::visit([](auto &&v) {
- return v->iconSize();
- }, m_viewModeSettingsVariant);
+ return std::visit(
+ [](auto &&v) {
+ return v->iconSize();
+ },
+ m_viewModeSettingsVariant);
}
void ViewModeSettings::setPreviewSize(int previewSize)
{
- std::visit([previewSize](auto &&v) {
- v->setPreviewSize(previewSize);
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [previewSize](auto &&v) {
+ v->setPreviewSize(previewSize);
+ },
+ m_viewModeSettingsVariant);
}
int ViewModeSettings::previewSize() const
{
- return std::visit([](auto &&v) {
- return v->previewSize();
- }, m_viewModeSettingsVariant);
+ return std::visit(
+ [](auto &&v) {
+ return v->previewSize();
+ },
+ m_viewModeSettingsVariant);
}
void ViewModeSettings::setUseSystemFont(bool useSystemFont)
{
- std::visit([useSystemFont](auto &&v) {
- v->setUseSystemFont(useSystemFont);
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [useSystemFont](auto &&v) {
+ v->setUseSystemFont(useSystemFont);
+ },
+ m_viewModeSettingsVariant);
}
bool ViewModeSettings::useSystemFont() const
{
- return std::visit([](auto &&v) {
- return v->useSystemFont();
- }, m_viewModeSettingsVariant);
+ return std::visit(
+ [](auto &&v) {
+ return v->useSystemFont();
+ },
+ m_viewModeSettingsVariant);
}
void ViewModeSettings::setViewFont(const QFont &font)
{
- std::visit([&font](auto &&v) {
- v->setViewFont(font);
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [&font](auto &&v) {
+ v->setViewFont(font);
+ },
+ m_viewModeSettingsVariant);
}
QFont ViewModeSettings::viewFont() const
{
- return std::visit([](auto &&v) {
- return v->viewFont();
- }, m_viewModeSettingsVariant);
+ return std::visit(
+ [](auto &&v) {
+ return v->viewFont();
+ },
+ m_viewModeSettingsVariant);
}
void ViewModeSettings::useDefaults(bool useDefaults)
{
- std::visit([useDefaults](auto &&v) {
- v->useDefaults(useDefaults);
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [useDefaults](auto &&v) {
+ v->useDefaults(useDefaults);
+ },
+ m_viewModeSettingsVariant);
}
void ViewModeSettings::readConfig()
{
- std::visit([](auto &&v) {
- v->load();
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [](auto &&v) {
+ v->load();
+ },
+ m_viewModeSettingsVariant);
}
void ViewModeSettings::save()
{
- std::visit([](auto &&v) {
- return v->save();
- }, m_viewModeSettingsVariant);
+ std::visit(
+ [](auto &&v) {
+ return v->save();
+ },
+ m_viewModeSettingsVariant);
}
#define VIEWMODESETTINGS_H
#include "kitemviews/kstandarditemlistview.h"
-#include "viewsettingstab.h"
#include "views/dolphinview.h"
+#include "viewsettingstab.h"
#include <variant>
#include <QTabWidget>
#include <QVBoxLayout>
-ViewSettingsPage::ViewSettingsPage(QWidget* parent) :
- SettingsPageBase(parent),
- m_tabs()
+ViewSettingsPage::ViewSettingsPage(QWidget *parent)
+ : SettingsPageBase(parent)
+ , m_tabs()
{
- QVBoxLayout* topLayout = new QVBoxLayout(this);
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
topLayout->setContentsMargins(0, 0, 0, 0);
- QTabWidget* tabWidget = new QTabWidget(this);
+ QTabWidget *tabWidget = new QTabWidget(this);
// Initialize 'Icons' tab
- ViewSettingsTab* iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget);
+ ViewSettingsTab *iconsTab = new ViewSettingsTab(ViewSettingsTab::IconsMode, tabWidget);
tabWidget->addTab(iconsTab, QIcon::fromTheme(QStringLiteral("view-list-icons")), i18nc("@title:tab", "Icons"));
connect(iconsTab, &ViewSettingsTab::changed, this, &ViewSettingsPage::changed);
// Initialize 'Compact' tab
- ViewSettingsTab* compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget);
+ ViewSettingsTab *compactTab = new ViewSettingsTab(ViewSettingsTab::CompactMode, tabWidget);
tabWidget->addTab(compactTab, QIcon::fromTheme(QStringLiteral("view-list-details")), i18nc("@title:tab", "Compact"));
connect(compactTab, &ViewSettingsTab::changed, this, &ViewSettingsPage::changed);
// Initialize 'Details' tab
- ViewSettingsTab* detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget);
+ ViewSettingsTab *detailsTab = new ViewSettingsTab(ViewSettingsTab::DetailsMode, tabWidget);
tabWidget->addTab(detailsTab, QIcon::fromTheme(QStringLiteral("view-list-tree")), i18nc("@title:tab", "Details"));
connect(detailsTab, &ViewSettingsTab::changed, this, &ViewSettingsPage::changed);
void ViewSettingsPage::applySettings()
{
- for (ViewSettingsTab* tab : qAsConst(m_tabs)) {
+ for (ViewSettingsTab *tab : qAsConst(m_tabs)) {
tab->applySettings();
}
}
void ViewSettingsPage::restoreDefaults()
{
- for (ViewSettingsTab* tab : qAsConst(m_tabs)) {
+ for (ViewSettingsTab *tab : qAsConst(m_tabs)) {
tab->restoreDefaultSettings();
}
}
-
Q_OBJECT
public:
- explicit ViewSettingsPage(QWidget* parent);
+ explicit ViewSettingsPage(QWidget *parent);
~ViewSettingsPage() override;
/** @see SettingsPageBase::applySettings() */
void restoreDefaults() override;
private:
- QList<ViewSettingsTab*> m_tabs;
+ QList<ViewSettingsTab *> m_tabs;
};
#endif
#include "settings/viewmodes/viewmodesettings.h"
#include "views/zoomlevelinfo.h"
-#include <KLocalizedString>
#include <KFormat>
+#include <KLocalizedString>
#include <QApplication>
#include <QButtonGroup>
#include <QRadioButton>
#include <QSpinBox>
-ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget* parent) :
- QWidget(parent),
- m_mode(mode),
- m_defaultSizeSlider(nullptr),
- m_previewSizeSlider(nullptr),
- m_fontRequester(nullptr),
- m_widthBox(nullptr),
- m_maxLinesBox(nullptr),
- m_expandableFolders(nullptr),
- m_recursiveDirectorySizeLimit(nullptr),
- m_useRelatetiveDates(nullptr),
- m_useShortDates(nullptr)
+ViewSettingsTab::ViewSettingsTab(Mode mode, QWidget *parent)
+ : QWidget(parent)
+ , m_mode(mode)
+ , m_defaultSizeSlider(nullptr)
+ , m_previewSizeSlider(nullptr)
+ , m_fontRequester(nullptr)
+ , m_widthBox(nullptr)
+ , m_maxLinesBox(nullptr)
+ , m_expandableFolders(nullptr)
+ , m_recursiveDirectorySizeLimit(nullptr)
+ , m_useRelatetiveDates(nullptr)
+ , m_useShortDates(nullptr)
{
- QFormLayout* topLayout = new QFormLayout(this);
+ QFormLayout *topLayout = new QFormLayout(this);
// Create "Icon Size" section
const int minRange = ZoomLevelInfo::minimumLevel();
m_defaultSizeSlider->setPageStep(1);
m_defaultSizeSlider->setTickPosition(QSlider::TicksBelow);
m_defaultSizeSlider->setRange(minRange, maxRange);
- connect(m_defaultSizeSlider, &QSlider::valueChanged,
- this, &ViewSettingsTab::slotDefaultSliderMoved);
+ connect(m_defaultSizeSlider, &QSlider::valueChanged, this, &ViewSettingsTab::slotDefaultSliderMoved);
topLayout->addRow(i18nc("@label:listbox", "Default icon size:"), m_defaultSizeSlider);
m_previewSizeSlider = new QSlider(Qt::Horizontal);
m_previewSizeSlider->setPageStep(1);
m_previewSizeSlider->setTickPosition(QSlider::TicksBelow);
m_previewSizeSlider->setRange(minRange, maxRange);
- connect(m_previewSizeSlider, &QSlider::valueChanged,
- this, &ViewSettingsTab::slotPreviewSliderMoved);
+ connect(m_previewSizeSlider, &QSlider::valueChanged, this, &ViewSettingsTab::slotPreviewSliderMoved);
topLayout->addRow(i18nc("@label:listbox", "Preview icon size:"), m_previewSizeSlider);
-
topLayout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed));
-
// Create "Label" section
m_fontRequester = new DolphinFontRequester(this);
topLayout->addRow(i18nc("@label:listbox", "Label font:"), m_fontRequester);
itemActivationAreaGroup->addButton(m_entireRow);
itemActivationAreaGroup->addButton(m_iconAndNameOnly);
+ // clang-format off
// i18n: Users can choose here if items are opened by clicking on their name/icon or by clicking in the row.
topLayout->addRow(i18nc("@title:group", "Open files and folders:"), m_entireRow);
+ // clang-format on
topLayout->addRow(QString(), m_iconAndNameOnly);
-
#ifndef Q_OS_WIN
// Sorting properties
m_numberOfItems = new QRadioButton(i18nc("option:radio", "Number of items"));
m_sizeOfContents = new QRadioButton(i18nc("option:radio", "Size of contents, up to "));
- QButtonGroup* sortingModeGroup = new QButtonGroup(this);
+ QButtonGroup *sortingModeGroup = new QButtonGroup(this);
sortingModeGroup->addButton(m_numberOfItems);
sortingModeGroup->addButton(m_sizeOfContents);
QLocale local;
KFormat formatter(local);
- m_useRelatetiveDates = new QRadioButton(i18nc(
- "option:radio as in relative date", "Relative (e.g. '%1')", formatter.formatRelativeDateTime(thirtyMinutesAgo, QLocale::ShortFormat))
- );
- m_useShortDates = new QRadioButton(
- i18nc("option:radio as in absolute date", "Absolute (e.g. '%1')", local.toString(thirtyMinutesAgo, QLocale::ShortFormat))
- );
+ m_useRelatetiveDates = new QRadioButton(
+ i18nc("option:radio as in relative date", "Relative (e.g. '%1')", formatter.formatRelativeDateTime(thirtyMinutesAgo, QLocale::ShortFormat)));
+ m_useShortDates =
+ new QRadioButton(i18nc("option:radio as in absolute date", "Absolute (e.g. '%1')", local.toString(thirtyMinutesAgo, QLocale::ShortFormat)));
- QButtonGroup* dateFormatGroup = new QButtonGroup(this);
+ QButtonGroup *dateFormatGroup = new QButtonGroup(this);
dateFormatGroup->addButton(m_useRelatetiveDates);
dateFormatGroup->addButton(m_useShortDates);
m_entireRow->setChecked(DetailsModeSettings::highlightEntireRow());
m_iconAndNameOnly->setChecked(!m_entireRow->isChecked());
m_expandableFolders->setChecked(DetailsModeSettings::expandableFolders());
- #ifndef Q_OS_WIN
- if (DetailsModeSettings::directorySizeCount()) {
- m_numberOfItems->setChecked(true);
- m_recursiveDirectorySizeLimit->setEnabled(false);
- } else {
- m_sizeOfContents->setChecked(true);
- m_recursiveDirectorySizeLimit->setEnabled(true);
- }
- m_recursiveDirectorySizeLimit->setValue(DetailsModeSettings::recursiveDirectorySizeLimit());
- #endif
+#ifndef Q_OS_WIN
+ if (DetailsModeSettings::directorySizeCount()) {
+ m_numberOfItems->setChecked(true);
+ m_recursiveDirectorySizeLimit->setEnabled(false);
+ } else {
+ m_sizeOfContents->setChecked(true);
+ m_recursiveDirectorySizeLimit->setEnabled(true);
+ }
+ m_recursiveDirectorySizeLimit->setValue(DetailsModeSettings::recursiveDirectorySizeLimit());
+#endif
m_useRelatetiveDates->setChecked(DetailsModeSettings::useShortRelativeDates());
m_useShortDates->setChecked(!DetailsModeSettings::useShortRelativeDates());
break;
const QSize previewSize(settings.previewSize(), settings.previewSize());
m_previewSizeSlider->setValue(ZoomLevelInfo::zoomLevelForIconSize(previewSize));
- m_fontRequester->setMode(settings.useSystemFont()
- ? DolphinFontRequester::SystemFont
- : DolphinFontRequester::CustomFont);
+ m_fontRequester->setMode(settings.useSystemFont() ? DolphinFontRequester::SystemFont : DolphinFontRequester::CustomFont);
QFont font(settings.viewFont());
m_fontRequester->setCustomFont(font);
showToolTip(m_previewSizeSlider, value);
}
-void ViewSettingsTab::showToolTip(QSlider* slider, int value)
+void ViewSettingsTab::showToolTip(QSlider *slider, int value)
{
const int size = ZoomLevelInfo::iconSizeForZoomLevel(value);
slider->setToolTip(i18ncp("@info:tooltip", "Size: 1 pixel", "Size: %1 pixels", size));
QHelpEvent toolTipEvent(QEvent::ToolTip, QPoint(0, 0), slider->mapToGlobal(global));
QApplication::sendEvent(slider, &toolTipEvent);
}
-
Q_OBJECT
public:
- enum Mode
- {
- IconsMode,
- CompactMode,
- DetailsMode
- };
+ enum Mode { IconsMode, CompactMode, DetailsMode };
- explicit ViewSettingsTab(Mode mode, QWidget* parent = nullptr);
+ explicit ViewSettingsTab(Mode mode, QWidget *parent = nullptr);
~ViewSettingsTab() override;
void applySettings();
void slotDefaultSliderMoved(int value);
void slotPreviewSliderMoved(int value);
+
private:
void loadSettings();
- void showToolTip(QSlider* slider, int value);
+ void showToolTip(QSlider *slider, int value);
private:
Mode m_mode;
- QSlider* m_defaultSizeSlider;
- QSlider* m_previewSizeSlider;
+ QSlider *m_defaultSizeSlider;
+ QSlider *m_previewSizeSlider;
- DolphinFontRequester* m_fontRequester;
- QComboBox* m_widthBox;
- QComboBox* m_maxLinesBox;
- QRadioButton* m_entireRow;
- QRadioButton* m_iconAndNameOnly;
- QCheckBox* m_expandableFolders;
- QRadioButton* m_numberOfItems;
- QRadioButton* m_sizeOfContents;
- QSpinBox* m_recursiveDirectorySizeLimit;
- QRadioButton* m_useRelatetiveDates;
- QRadioButton* m_useShortDates;
+ DolphinFontRequester *m_fontRequester;
+ QComboBox *m_widthBox;
+ QComboBox *m_maxLinesBox;
+ QRadioButton *m_entireRow;
+ QRadioButton *m_iconAndNameOnly;
+ QCheckBox *m_expandableFolders;
+ QRadioButton *m_numberOfItems;
+ QRadioButton *m_sizeOfContents;
+ QSpinBox *m_recursiveDirectorySizeLimit;
+ QRadioButton *m_useRelatetiveDates;
+ QRadioButton *m_useShortDates;
};
#endif
#include <kwidgetsaddons_version.h>
#if HAVE_BALOO
- #include <Baloo/IndexerConfig>
+#include <Baloo/IndexerConfig>
#endif
#include <QButtonGroup>
#include <views/viewproperties.h>
-ViewPropertiesDialog::ViewPropertiesDialog(DolphinView* dolphinView) :
- QDialog(dolphinView),
- m_isDirty(false),
- m_dolphinView(dolphinView),
- m_viewProps(nullptr),
- m_viewMode(nullptr),
- m_sortOrder(nullptr),
- m_sorting(nullptr),
- m_sortFoldersFirst(nullptr),
- m_sortHiddenLast(nullptr),
- m_previewsShown(nullptr),
- m_showInGroups(nullptr),
- m_showHiddenFiles(nullptr),
- m_applyToCurrentFolder(nullptr),
- m_applyToSubFolders(nullptr),
- m_applyToAllFolders(nullptr),
- m_useAsDefault(nullptr)
+ViewPropertiesDialog::ViewPropertiesDialog(DolphinView *dolphinView)
+ : QDialog(dolphinView)
+ , m_isDirty(false)
+ , m_dolphinView(dolphinView)
+ , m_viewProps(nullptr)
+ , m_viewMode(nullptr)
+ , m_sortOrder(nullptr)
+ , m_sorting(nullptr)
+ , m_sortFoldersFirst(nullptr)
+ , m_sortHiddenLast(nullptr)
+ , m_previewsShown(nullptr)
+ , m_showInGroups(nullptr)
+ , m_showHiddenFiles(nullptr)
+ , m_applyToCurrentFolder(nullptr)
+ , m_applyToSubFolders(nullptr)
+ , m_applyToAllFolders(nullptr)
+ , m_useAsDefault(nullptr)
{
Q_ASSERT(dolphinView);
const bool useGlobalViewProps = GeneralSettings::globalViewProps();
setWindowTitle(i18nc("@title:window", "View Display Style"));
- const QUrl& url = dolphinView->url();
+ const QUrl &url = dolphinView->url();
m_viewProps = new ViewProperties(url);
m_viewProps->setAutoSaveEnabled(false);
m_sorting = new QComboBox();
const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
- for (const KFileItemModel::RoleInfo& info : rolesInfo) {
+ for (const KFileItemModel::RoleInfo &info : rolesInfo) {
m_sorting->addItem(info.translation, info.role);
}
connect(m_listWidget, &QListWidget::itemChanged, this, &ViewPropertiesDialog::slotItemChanged);
m_listWidget->setSelectionMode(QAbstractItemView::NoSelection);
const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
- for (const KFileItemModel::RoleInfo& info : rolesInfo) {
- QListWidgetItem* item = new QListWidgetItem(info.translation, m_listWidget);
+ for (const KFileItemModel::RoleInfo &info : rolesInfo) {
+ QListWidgetItem *item = new QListWidgetItem(info.translation, m_listWidget);
item->setCheckState(visibleRoles.contains(info.role) ? Qt::Checked : Qt::Unchecked);
- const bool enable = ((!info.requiresBaloo && !info.requiresIndexer) ||
- (info.requiresBaloo) ||
- (info.requiresIndexer && indexingEnabled)) && info.role != "text";
+ const bool enable =
+ ((!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled)) && info.role != "text";
if (!enable) {
item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
}
}
- QLabel* additionalViewOptionsLabel = new QLabel(i18n("Choose what to see on each file or folder:"));
+ QLabel *additionalViewOptionsLabel = new QLabel(i18n("Choose what to see on each file or folder:"));
innerLayout->addWidget(additionalViewOptionsLabel);
innerLayout->addWidget(m_listWidget);
}
- QHBoxLayout* sortingLayout = new QHBoxLayout();
+ QHBoxLayout *sortingLayout = new QHBoxLayout();
sortingLayout->setContentsMargins(0, 0, 0, 0);
sortingLayout->addWidget(m_sortOrder);
sortingLayout->addWidget(m_sorting);
layout->addRow(QString(), m_showHiddenFiles);
layout->addRow(QString(), m_sortHiddenLast);
- connect(m_viewMode, &QComboBox::currentIndexChanged,
- this, &ViewPropertiesDialog::slotViewModeChanged);
- connect(m_sorting, &QComboBox::currentIndexChanged,
- this, &ViewPropertiesDialog::slotSortingChanged);
- connect(m_sortOrder, &QComboBox::currentIndexChanged,
- this, &ViewPropertiesDialog::slotSortOrderChanged);
- connect(m_sortFoldersFirst, &QCheckBox::clicked,
- this, &ViewPropertiesDialog::slotSortFoldersFirstChanged);
- connect(m_sortHiddenLast, &QCheckBox::clicked,
- this, &ViewPropertiesDialog::slotSortHiddenLastChanged);
- connect(m_previewsShown, &QCheckBox::clicked,
- this, &ViewPropertiesDialog::slotShowPreviewChanged);
- connect(m_showInGroups, &QCheckBox::clicked,
- this, &ViewPropertiesDialog::slotGroupedSortingChanged);
- connect(m_showHiddenFiles, &QCheckBox::clicked,
- this, &ViewPropertiesDialog::slotShowHiddenFilesChanged);
+ connect(m_viewMode, &QComboBox::currentIndexChanged, this, &ViewPropertiesDialog::slotViewModeChanged);
+ connect(m_sorting, &QComboBox::currentIndexChanged, this, &ViewPropertiesDialog::slotSortingChanged);
+ connect(m_sortOrder, &QComboBox::currentIndexChanged, this, &ViewPropertiesDialog::slotSortOrderChanged);
+ connect(m_sortFoldersFirst, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotSortFoldersFirstChanged);
+ connect(m_sortHiddenLast, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotSortHiddenLastChanged);
+ connect(m_previewsShown, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotShowPreviewChanged);
+ connect(m_showInGroups, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotGroupedSortingChanged);
+ connect(m_showHiddenFiles, &QCheckBox::clicked, this, &ViewPropertiesDialog::slotShowHiddenFilesChanged);
// Only show the following settings if the view properties are remembered
// for each directory:
if (!useGlobalViewProps) {
// create 'Apply View Properties To' group
- m_applyToCurrentFolder = new QRadioButton(i18nc("@option:radio Apply View Properties To",
- "Current folder"));
+ m_applyToCurrentFolder = new QRadioButton(i18nc("@option:radio Apply View Properties To", "Current folder"));
m_applyToCurrentFolder->setChecked(true);
- m_applyToSubFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To",
- "Current folder and sub-folders"));
- m_applyToAllFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To",
- "All folders"));
+ m_applyToSubFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To", "Current folder and sub-folders"));
+ m_applyToAllFolders = new QRadioButton(i18nc("@option:radio Apply View Properties To", "All folders"));
- QButtonGroup* applyGroup = new QButtonGroup(this);
+ QButtonGroup *applyGroup = new QButtonGroup(this);
applyGroup->addButton(m_applyToCurrentFolder);
applyGroup->addButton(m_applyToSubFolders);
applyGroup->addButton(m_applyToAllFolders);
m_useAsDefault = new QCheckBox(i18nc("@option:check", "Use as default view settings"), this);
layout->addRow(QString(), m_useAsDefault);
- connect(m_applyToCurrentFolder, &QRadioButton::clicked,
- this, &ViewPropertiesDialog::markAsDirty);
- connect(m_applyToSubFolders, &QRadioButton::clicked,
- this, &ViewPropertiesDialog::markAsDirty);
- connect(m_applyToAllFolders, &QRadioButton::clicked,
- this, &ViewPropertiesDialog::markAsDirty);
- connect(m_useAsDefault, &QCheckBox::clicked,
- this, &ViewPropertiesDialog::markAsDirty);
+ connect(m_applyToCurrentFolder, &QRadioButton::clicked, this, &ViewPropertiesDialog::markAsDirty);
+ connect(m_applyToSubFolders, &QRadioButton::clicked, this, &ViewPropertiesDialog::markAsDirty);
+ connect(m_applyToAllFolders, &QRadioButton::clicked, this, &ViewPropertiesDialog::markAsDirty);
+ connect(m_useAsDefault, &QCheckBox::clicked, this, &ViewPropertiesDialog::markAsDirty);
}
layout->addItem(new QSpacerItem(0, Dolphin::VERTICAL_SPACER_HEIGHT, QSizePolicy::Fixed, QSizePolicy::Fixed));
QList<QByteArray> visibleRoles;
int index = 0;
const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
- for (const KFileItemModel::RoleInfo& info : rolesInfo) {
- const QListWidgetItem* item = m_listWidget->item(index);
- if (item->checkState() == Qt::Checked) {
+ for (const KFileItemModel::RoleInfo &info : rolesInfo) {
+ const QListWidgetItem *item = m_listWidget->item(index);
+ if (item->checkState() == Qt::Checked) {
visibleRoles.append(info.role);
}
++index;
if (applyToSubFolders) {
const QString text(i18nc("@info", "The view properties of all sub-folders will be changed. Do you want to continue?"));
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- if (KMessageBox::questionTwoActions(this, text, {},
- KStandardGuiItem::cont(),
- KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) {
+ if (KMessageBox::questionTwoActions(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) {
#else
- if (KMessageBox::questionYesNo(this, text, {},
- KStandardGuiItem::cont(),
- KStandardGuiItem::cancel()) == KMessageBox::No) {
+ if (KMessageBox::questionYesNo(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::No) {
#endif
return;
}
- ViewPropsProgressInfo* info = new ViewPropsProgressInfo(m_dolphinView,
- m_dolphinView->url(),
- *m_viewProps);
+ ViewPropsProgressInfo *info = new ViewPropsProgressInfo(m_dolphinView, m_dolphinView->url(), *m_viewProps);
info->setAttribute(Qt::WA_DeleteOnClose);
info->setWindowModality(Qt::NonModal);
info->show();
if (applyToAllFolders) {
const QString text(i18nc("@info", "The view properties of all folders will be changed. Do you want to continue?"));
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- if (KMessageBox::questionTwoActions(this, text, {},
- KStandardGuiItem::cont(),
- KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) {
+ if (KMessageBox::questionTwoActions(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::SecondaryAction) {
#else
- if (KMessageBox::questionYesNo(this, text, {},
- KStandardGuiItem::cont(),
- KStandardGuiItem::cancel()) == KMessageBox::No) {
+ if (KMessageBox::questionYesNo(this, text, {}, KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::No) {
#endif
return;
}
// Updating the global view properties time stamp in the general settings makes
// all existing viewproperties invalid, as they have a smaller time stamp.
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
settings->setViewPropsTimestamp(QDateTime::currentDateTime());
settings->save();
}
{
// Load view mode
switch (m_viewProps->viewMode()) {
- case DolphinView::IconsView: m_viewMode->setCurrentIndex(0); break;
- case DolphinView::CompactView: m_viewMode->setCurrentIndex(1); break;
- case DolphinView::DetailsView: m_viewMode->setCurrentIndex(2); break;
- default: break;
+ case DolphinView::IconsView:
+ m_viewMode->setCurrentIndex(0);
+ break;
+ case DolphinView::CompactView:
+ m_viewMode->setCurrentIndex(1);
+ break;
+ case DolphinView::DetailsView:
+ m_viewMode->setCurrentIndex(2);
+ break;
+ default:
+ break;
}
// Load sort order and sorting
m_showHiddenFiles->setChecked(m_viewProps->hiddenFilesShown());
markAsDirty(false);
}
-
Q_OBJECT
public:
- explicit ViewPropertiesDialog(DolphinView* dolphinView);
+ explicit ViewPropertiesDialog(DolphinView *dolphinView);
~ViewPropertiesDialog() override;
public Q_SLOTS:
private:
bool m_isDirty;
- DolphinView* m_dolphinView;
- ViewProperties* m_viewProps;
+ DolphinView *m_dolphinView;
+ ViewProperties *m_viewProps;
- QComboBox* m_viewMode;
- QComboBox* m_sortOrder;
- QComboBox* m_sorting;
- QCheckBox* m_sortFoldersFirst;
- QCheckBox* m_sortHiddenLast;
- QCheckBox* m_previewsShown;
- QCheckBox* m_showInGroups;
- QCheckBox* m_showHiddenFiles;
- QRadioButton* m_applyToCurrentFolder;
- QRadioButton* m_applyToSubFolders;
- QRadioButton* m_applyToAllFolders;
- QCheckBox* m_useAsDefault;
- QListWidget* m_listWidget;
+ QComboBox *m_viewMode;
+ QComboBox *m_sortOrder;
+ QComboBox *m_sorting;
+ QCheckBox *m_sortFoldersFirst;
+ QCheckBox *m_sortHiddenLast;
+ QCheckBox *m_previewsShown;
+ QCheckBox *m_showInGroups;
+ QCheckBox *m_showHiddenFiles;
+ QRadioButton *m_applyToCurrentFolder;
+ QRadioButton *m_applyToSubFolders;
+ QRadioButton *m_applyToAllFolders;
+ QCheckBox *m_useAsDefault;
+ QListWidget *m_listWidget;
};
#endif
#include <QTimer>
#include <QVBoxLayout>
-ViewPropsProgressInfo::ViewPropsProgressInfo(QWidget* parent,
- const QUrl& dir,
- const ViewProperties& viewProps) :
- QDialog(parent),
- m_dir(dir),
- m_viewProps(nullptr),
- m_label(nullptr),
- m_progressBar(nullptr),
- m_dirSizeJob(nullptr),
- m_applyViewPropsJob(nullptr),
- m_timer(nullptr)
+ViewPropsProgressInfo::ViewPropsProgressInfo(QWidget *parent, const QUrl &dir, const ViewProperties &viewProps)
+ : QDialog(parent)
+ , m_dir(dir)
+ , m_viewProps(nullptr)
+ , m_label(nullptr)
+ , m_progressBar(nullptr)
+ , m_dirSizeJob(nullptr)
+ , m_applyViewPropsJob(nullptr)
+ , m_timer(nullptr)
{
const QSize minSize = minimumSize();
setMinimumSize(QSize(320, minSize.height()));
// allows to give a progress indication for the user when applying the view
// properties later.
m_dirSizeJob = KIO::directorySize(dir);
- connect(m_dirSizeJob, &KIO::DirectorySizeJob::result,
- this, &ViewPropsProgressInfo::applyViewProperties);
+ connect(m_dirSizeJob, &KIO::DirectorySizeJob::result, this, &ViewPropsProgressInfo::applyViewProperties);
// The directory size job cannot emit any progress signal, as it is not aware
// about the total number of directories. Therefor a timer is triggered, which
// periodically updates the current directory count.
m_timer = new QTimer(this);
- connect(m_timer, &QTimer::timeout,
- this, &ViewPropsProgressInfo::updateProgress);
+ connect(m_timer, &QTimer::timeout, this, &ViewPropsProgressInfo::updateProgress);
m_timer->start(300);
}
m_viewProps = nullptr;
}
-void ViewPropsProgressInfo::closeEvent(QCloseEvent* event)
+void ViewPropsProgressInfo::closeEvent(QCloseEvent *event)
{
m_timer->stop();
m_applyViewPropsJob = nullptr;
m_dirSizeJob = nullptr;
m_applyViewPropsJob = new ApplyViewPropsJob(m_dir, *m_viewProps);
- connect(m_applyViewPropsJob, &ApplyViewPropsJob::result,
- this, &ViewPropsProgressInfo::close);
+ connect(m_applyViewPropsJob, &ApplyViewPropsJob::result, this, &ViewPropsProgressInfo::close);
}
-
* @param viewProps View properties for the directory \a dir including its
* sub directories.
*/
- ViewPropsProgressInfo(QWidget* parent,
- const QUrl& dir,
- const ViewProperties& viewProps);
+ ViewPropsProgressInfo(QWidget *parent, const QUrl &dir, const ViewProperties &viewProps);
~ViewPropsProgressInfo() override;
protected:
- void closeEvent(QCloseEvent* event) override;
+ void closeEvent(QCloseEvent *event) override;
public Q_SLOTS:
void reject() override;
private:
QUrl m_dir;
- ViewProperties* m_viewProps;
+ ViewProperties *m_viewProps;
- QLabel* m_label;
- QProgressBar* m_progressBar;
+ QLabel *m_label;
+ QProgressBar *m_progressBar;
- KIO::DirectorySizeJob* m_dirSizeJob;
- ApplyViewPropsJob* m_applyViewPropsJob;
- QTimer* m_timer;
+ KIO::DirectorySizeJob *m_dirSizeJob;
+ ApplyViewPropsJob *m_applyViewPropsJob;
+ QTimer *m_timer;
};
#endif
#include <QTimer>
#include <QToolButton>
-namespace {
- const int UpdateDelay = 50;
+namespace
+{
+const int UpdateDelay = 50;
}
-DolphinStatusBar::DolphinStatusBar(QWidget* parent) :
- QWidget(parent),
- m_text(),
- m_defaultText(),
- m_label(nullptr),
- m_zoomLabel(nullptr),
- m_spaceInfo(nullptr),
- m_zoomSlider(nullptr),
- m_progressBar(nullptr),
- m_stopButton(nullptr),
- m_progress(100),
- m_showProgressBarTimer(nullptr),
- m_delayUpdateTimer(nullptr),
- m_textTimestamp()
+DolphinStatusBar::DolphinStatusBar(QWidget *parent)
+ : QWidget(parent)
+ , m_text()
+ , m_defaultText()
+ , m_label(nullptr)
+ , m_zoomLabel(nullptr)
+ , m_spaceInfo(nullptr)
+ , m_zoomSlider(nullptr)
+ , m_progressBar(nullptr)
+ , m_stopButton(nullptr)
+ , m_progress(100)
+ , m_showProgressBarTimer(nullptr)
+ , m_delayUpdateTimer(nullptr)
+ , m_textTimestamp()
{
// Initialize text label
m_label = new KSqueezedTextLabel(m_text, this);
m_label->setTextFormat(Qt::PlainText);
// Initialize zoom slider's explanatory label
- m_zoomLabel = new QLabel(i18nc("Used as a noun, i.e. 'Here is the zoom level:'","Zoom:"), this);
+ m_zoomLabel = new QLabel(i18nc("Used as a noun, i.e. 'Here is the zoom level:'", "Zoom:"), this);
// Initialize zoom widget
m_zoomSlider = new QSlider(Qt::Horizontal, this);
m_delayUpdateTimer = new QTimer(this);
m_delayUpdateTimer->setInterval(UpdateDelay);
m_delayUpdateTimer->setSingleShot(true);
- connect(m_delayUpdateTimer, &QTimer::timeout,
- this, &DolphinStatusBar::updateLabelText);
+ connect(m_delayUpdateTimer, &QTimer::timeout, this, &DolphinStatusBar::updateLabelText);
// Initialize top layout and size policies
const int fontHeight = QFontMetrics(m_label->font()).height();
m_progressBar->setFixedHeight(zoomSliderHeight);
m_progressBar->setMaximumWidth(fontMetrics.averageCharWidth() * 20);
- QHBoxLayout* topLayout = new QHBoxLayout(this);
+ QHBoxLayout *topLayout = new QHBoxLayout(this);
topLayout->setContentsMargins(2, 0, 2, 0);
topLayout->setSpacing(4);
topLayout->addWidget(m_label, 1);
setVisible(GeneralSettings::showStatusBar());
setExtensionsVisible(true);
- setWhatsThis(xi18nc("@info:whatsthis Statusbar", "<para>This is "
- "the <emphasis>Statusbar</emphasis>. It contains three elements "
- "by default (left to right):<list><item>A <emphasis>text field"
- "</emphasis> that displays the size of selected items. If only "
- "one item is selected the name and type is shown as well.</item>"
- "<item>A <emphasis>zoom slider</emphasis> that allows you "
- "to adjust the size of the icons in the view.</item>"
- "<item><emphasis>Space information</emphasis> about the "
- "current storage device.</item></list></para>"));
+ setWhatsThis(xi18nc("@info:whatsthis Statusbar",
+ "<para>This is "
+ "the <emphasis>Statusbar</emphasis>. It contains three elements "
+ "by default (left to right):<list><item>A <emphasis>text field"
+ "</emphasis> that displays the size of selected items. If only "
+ "one item is selected the name and type is shown as well.</item>"
+ "<item>A <emphasis>zoom slider</emphasis> that allows you "
+ "to adjust the size of the icons in the view.</item>"
+ "<item><emphasis>Space information</emphasis> about the "
+ "current storage device.</item></list></para>"));
}
DolphinStatusBar::~DolphinStatusBar()
{
}
-void DolphinStatusBar::setText(const QString& text)
+void DolphinStatusBar::setText(const QString &text)
{
if (m_text == text) {
return;
return m_text;
}
-void DolphinStatusBar::setProgressText(const QString& text)
+void DolphinStatusBar::setProgressText(const QString &text)
{
m_progressTextLabel->setText(text);
}
}
}
-void DolphinStatusBar::setDefaultText(const QString& text)
+void DolphinStatusBar::setDefaultText(const QString &text)
{
m_defaultText = text;
updateLabelText();
return m_defaultText;
}
-void DolphinStatusBar::setUrl(const QUrl& url)
+void DolphinStatusBar::setUrl(const QUrl &url)
{
if (GeneralSettings::showSpaceInfo()) {
m_spaceInfo->setUrl(url);
m_spaceInfo->update();
}
-void DolphinStatusBar::contextMenuEvent(QContextMenuEvent* event)
+void DolphinStatusBar::contextMenuEvent(QContextMenuEvent *event)
{
Q_UNUSED(event)
QMenu menu(this);
- QAction* showZoomSliderAction = menu.addAction(i18nc("@action:inmenu", "Show Zoom Slider"));
+ QAction *showZoomSliderAction = menu.addAction(i18nc("@action:inmenu", "Show Zoom Slider"));
showZoomSliderAction->setCheckable(true);
showZoomSliderAction->setChecked(GeneralSettings::showZoomSlider());
- QAction* showSpaceInfoAction = menu.addAction(i18nc("@action:inmenu", "Show Space Information"));
+ QAction *showSpaceInfoAction = menu.addAction(i18nc("@action:inmenu", "Show Space Information"));
showSpaceInfoAction->setCheckable(true);
showSpaceInfoAction->setChecked(GeneralSettings::showSpaceInfo());
- const QAction* action = menu.exec(QCursor::pos());
+ const QAction *action = menu.exec(QCursor::pos());
if (action == showZoomSliderAction) {
const bool visible = showZoomSliderAction->isChecked();
GeneralSettings::setShowZoomSlider(visible);
m_zoomSlider->setVisible(showZoomSlider);
m_zoomLabel->setVisible(showZoomSlider);
}
-
Q_OBJECT
public:
- explicit DolphinStatusBar(QWidget* parent);
+ explicit DolphinStatusBar(QWidget *parent);
~DolphinStatusBar() override;
QString text() const;
* DolphinStatusBar::setProgress() should be invoked
* afterwards each time the progress changes.
*/
- void setProgressText(const QString& text);
+ void setProgressText(const QString &text);
QString progressText() const;
/**
* Sets the default text, which is shown if the status bar
* is rest by DolphinStatusBar::resetToDefaultText().
*/
- void setDefaultText(const QString& text);
+ void setDefaultText(const QString &text);
QString defaultText() const;
QUrl url() const;
void updateSpaceInfo();
public Q_SLOTS:
- void setText(const QString& text);
- void setUrl(const QUrl& url);
+ void setText(const QString &text);
+ void setUrl(const QUrl &url);
void setZoomLevel(int zoomLevel);
Q_SIGNALS:
void zoomLevelChanged(int zoomLevel);
protected:
- void contextMenuEvent(QContextMenuEvent* event) override;
+ void contextMenuEvent(QContextMenuEvent *event) override;
private Q_SLOTS:
void showZoomSliderToolTip(int zoomLevel);
private:
QString m_text;
QString m_defaultText;
- KSqueezedTextLabel* m_label;
- QLabel* m_zoomLabel;
- StatusBarSpaceInfo* m_spaceInfo;
+ KSqueezedTextLabel *m_label;
+ QLabel *m_zoomLabel;
+ StatusBarSpaceInfo *m_spaceInfo;
- QSlider* m_zoomSlider;
+ QSlider *m_zoomSlider;
- QLabel* m_progressTextLabel;
- QProgressBar* m_progressBar;
- QToolButton* m_stopButton;
+ QLabel *m_progressTextLabel;
+ QProgressBar *m_progressBar;
+ QToolButton *m_stopButton;
int m_progress;
- QTimer* m_showProgressBarTimer;
+ QTimer *m_showProgressBarTimer;
- QTimer* m_delayUpdateTimer;
+ QTimer *m_delayUpdateTimer;
QTime m_textTimestamp;
};
#include <KIO/FileSystemFreeSpaceJob>
-MountPointObserver::MountPointObserver(const QUrl& url, QObject* parent) :
- QObject(parent),
- m_url(url),
- m_referenceCount(0)
+MountPointObserver::MountPointObserver(const QUrl &url, QObject *parent)
+ : QObject(parent)
+ , m_url(url)
+ , m_referenceCount(0)
{
}
-MountPointObserver* MountPointObserver::observerForUrl(const QUrl& url)
+MountPointObserver *MountPointObserver::observerForUrl(const QUrl &url)
{
- MountPointObserver* observer = MountPointObserverCache::instance()->observerForUrl(url);
+ MountPointObserver *observer = MountPointObserverCache::instance()->observerForUrl(url);
return observer;
}
if (m_referenceCount == 0) {
delete this;
} else {
- KIO::FileSystemFreeSpaceJob* job = KIO::fileSystemFreeSpace(m_url);
+ KIO::FileSystemFreeSpaceJob *job = KIO::fileSystemFreeSpace(m_url);
connect(job, &KIO::FileSystemFreeSpaceJob::result, this, &MountPointObserver::freeSpaceResult);
}
}
-void MountPointObserver::freeSpaceResult(KIO::Job* job, KIO::filesize_t size, KIO::filesize_t available)
+void MountPointObserver::freeSpaceResult(KIO::Job *job, KIO::filesize_t size, KIO::filesize_t available)
{
if (!job->error()) {
Q_EMIT spaceInfoChanged(size, available);
{
Q_OBJECT
- explicit MountPointObserver(const QUrl& url, QObject* parent = nullptr);
- ~MountPointObserver() override {}
+ explicit MountPointObserver(const QUrl &url, QObject *parent = nullptr);
+ ~MountPointObserver() override
+ {
+ }
public:
/**
* internal reference count is increased then. When the observer is not needed any more,
* deref() should be called, which decreases the reference count again.
*/
- void ref() { ++m_referenceCount; }
+ void ref()
+ {
+ ++m_referenceCount;
+ }
/**
* This function can be used to indicate that the caller does not need this MountPointObserver
* Returns a MountPointObserver for the given \a url. If the caller intends to continue using
* the returned object, it must call its ref() method.
*/
- static MountPointObserver* observerForUrl(const QUrl& url);
+ static MountPointObserver *observerForUrl(const QUrl &url);
Q_SIGNALS:
/**
void update();
private Q_SLOTS:
- void freeSpaceResult(KIO::Job* job, KIO::filesize_t size, KIO::filesize_t available);
+ void freeSpaceResult(KIO::Job *job, KIO::filesize_t size, KIO::filesize_t available);
private:
const QUrl m_url;
};
Q_GLOBAL_STATIC(MountPointObserverCacheSingleton, s_MountPointObserverCache)
-
-MountPointObserverCache::MountPointObserverCache() :
- m_observerForMountPoint(),
- m_mountPointForObserver(),
- m_updateTimer(nullptr)
+MountPointObserverCache::MountPointObserverCache()
+ : m_observerForMountPoint()
+ , m_mountPointForObserver()
+ , m_updateTimer(nullptr)
{
m_updateTimer = new QTimer(this);
}
{
}
-MountPointObserverCache* MountPointObserverCache::instance()
+MountPointObserverCache *MountPointObserverCache::instance()
{
return &s_MountPointObserverCache->instance;
}
-MountPointObserver* MountPointObserverCache::observerForUrl(const QUrl& url)
+MountPointObserver *MountPointObserverCache::observerForUrl(const QUrl &url)
{
QUrl cachedObserverUrl;
// If the url is a local path we can extract the root dir by checking the mount points.
cachedObserverUrl = url;
}
- MountPointObserver* observer = m_observerForMountPoint.value(cachedObserverUrl);
+ MountPointObserver *observer = m_observerForMountPoint.value(cachedObserverUrl);
if (!observer) {
observer = new MountPointObserver(cachedObserverUrl, this);
m_observerForMountPoint.insert(cachedObserverUrl, observer);
return observer;
}
-void MountPointObserverCache::slotObserverDestroyed(QObject* observer)
+void MountPointObserverCache::slotObserverDestroyed(QObject *observer)
{
Q_ASSERT(m_mountPointForObserver.contains(observer));
- const QUrl& url = m_mountPointForObserver.value(observer);
+ const QUrl &url = m_mountPointForObserver.value(observer);
Q_ASSERT(m_observerForMountPoint.contains(url));
m_observerForMountPoint.remove(url);
m_mountPointForObserver.remove(observer);
~MountPointObserverCache() override;
public:
- static MountPointObserverCache* instance();
+ static MountPointObserverCache *instance();
/**
* Returns a MountPointObserver for the given \a url. A new observer is created if necessary.
*/
- MountPointObserver* observerForUrl(const QUrl& url);
+ MountPointObserver *observerForUrl(const QUrl &url);
private Q_SLOTS:
/**
* Removes the given \a observer from the cache.
*/
- void slotObserverDestroyed(QObject* observer);
+ void slotObserverDestroyed(QObject *observer);
private:
- QHash<QUrl, MountPointObserver*> m_observerForMountPoint;
- QHash<QObject*, QUrl> m_mountPointForObserver;
- QTimer* m_updateTimer;
+ QHash<QUrl, MountPointObserver *> m_observerForMountPoint;
+ QHash<QObject *, QUrl> m_mountPointForObserver;
+ QTimer *m_updateTimer;
friend class MountPointObserverCacheSingleton;
};
#include "mountpointobserver.h"
-SpaceInfoObserver::SpaceInfoObserver(const QUrl& url, QObject* parent) :
- QObject(parent),
- m_mountPointObserver(nullptr),
- m_hasData(false),
- m_dataSize(0),
- m_dataAvailable(0)
+SpaceInfoObserver::SpaceInfoObserver(const QUrl &url, QObject *parent)
+ : QObject(parent)
+ , m_mountPointObserver(nullptr)
+ , m_hasData(false)
+ , m_dataSize(0)
+ , m_dataAvailable(0)
{
m_mountPointObserver = MountPointObserver::observerForUrl(url);
m_mountPointObserver->ref();
return m_dataAvailable;
}
-void SpaceInfoObserver::setUrl(const QUrl& url)
+void SpaceInfoObserver::setUrl(const QUrl &url)
{
- MountPointObserver* newObserver = MountPointObserver::observerForUrl(url);
+ MountPointObserver *newObserver = MountPointObserver::observerForUrl(url);
if (newObserver != m_mountPointObserver) {
if (m_mountPointObserver) {
disconnect(m_mountPointObserver, &MountPointObserver::spaceInfoChanged, this, &SpaceInfoObserver::spaceInfoChanged);
m_mountPointObserver->ref();
connect(m_mountPointObserver, &MountPointObserver::spaceInfoChanged, this, &SpaceInfoObserver::spaceInfoChanged);
- // If newObserver is cached it won't call update until the next timer update,
+ // If newObserver is cached it won't call update until the next timer update,
// so update the observer now.
m_mountPointObserver->update();
}
Q_OBJECT
public:
- explicit SpaceInfoObserver(const QUrl& url, QObject* parent = nullptr);
+ explicit SpaceInfoObserver(const QUrl &url, QObject *parent = nullptr);
~SpaceInfoObserver() override;
quint64 size() const;
quint64 available() const;
- void setUrl(const QUrl& url);
+ void setUrl(const QUrl &url);
public Q_SLOTS:
void update();
void spaceInfoChanged(quint64 size, quint64 available);
private:
- MountPointObserver* m_mountPointObserver;
+ MountPointObserver *m_mountPointObserver;
- bool m_hasData;
+ bool m_hasData;
quint64 m_dataSize;
quint64 m_dataAvailable;
};
#include <KIO/Global>
#include <QMouseEvent>
-StatusBarSpaceInfo::StatusBarSpaceInfo(QWidget* parent) :
- KCapacityBar(KCapacityBar::DrawTextInline, parent),
- m_observer(nullptr)
+StatusBarSpaceInfo::StatusBarSpaceInfo(QWidget *parent)
+ : KCapacityBar(KCapacityBar::DrawTextInline, parent)
+ , m_observer(nullptr)
{
setCursor(Qt::PointingHandCursor);
}
}
}
-void StatusBarSpaceInfo::setUrl(const QUrl& url)
+void StatusBarSpaceInfo::setUrl(const QUrl &url)
{
if (m_url != url) {
m_url = url;
}
}
-void StatusBarSpaceInfo::showEvent(QShowEvent* event)
+void StatusBarSpaceInfo::showEvent(QShowEvent *event)
{
if (m_shown) {
if (m_ready) {
}
}
-void StatusBarSpaceInfo::hideEvent(QHideEvent* event)
+void StatusBarSpaceInfo::hideEvent(QHideEvent *event)
{
if (m_ready) {
m_observer.reset();
KCapacityBar::hideEvent(event);
}
-void StatusBarSpaceInfo::mousePressEvent(QMouseEvent* event)
+void StatusBarSpaceInfo::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
// Creates a menu with tools that help to find out more about free
// the "Configure..." dialog
KMoreToolsMenuFactory menuFactory(QStringLiteral("dolphin/statusbar-diskspace-menu"));
menuFactory.setParentWidget(this);
- auto menu = menuFactory.createMenuFromGroupingNames(
- { "disk-usage", "more:", "disk-partitions" }, m_url);
+ auto menu = menuFactory.createMenuFromGroupingNames({"disk-usage", "more:", "disk-partitions"}, m_url);
menu->exec(QCursor::pos());
}
update();
}
}
-
Q_OBJECT
public:
- explicit StatusBarSpaceInfo(QWidget* parent = nullptr);
+ explicit StatusBarSpaceInfo(QWidget *parent = nullptr);
~StatusBarSpaceInfo() override;
/**
* Use this to set the widget visibility as it can hide itself
*/
void setShown(bool);
- void setUrl(const QUrl& url);
+ void setUrl(const QUrl &url);
QUrl url() const;
void update();
protected:
- void showEvent(QShowEvent* event) override;
- void hideEvent(QHideEvent* event) override;
- void mousePressEvent(QMouseEvent* event) override;
+ void showEvent(QShowEvent *event) override;
+ void hideEvent(QHideEvent *event) override;
+ void mousePressEvent(QMouseEvent *event) override;
private Q_SLOTS:
void slotValuesChanged();
void testGoActions();
void cleanupTestCase();
-
private:
QScopedPointer<DolphinMainWindow> m_mainWindow;
};
// See https://bugs.kde.org/show_bug.cgi?id=379135
void DolphinMainWindowTest::testClosingTabsWithSearchBoxVisible()
{
- m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false);
+ m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false);
m_mainWindow->show();
// Without this call the searchbox doesn't get FocusIn events.
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
- auto tabWidget = m_mainWindow->findChild<DolphinTabWidget*>("tabWidget");
+ auto tabWidget = m_mainWindow->findChild<DolphinTabWidget *>("tabWidget");
QVERIFY(tabWidget);
// Show search box on first tab.
void DolphinMainWindowTest::testActiveViewAfterClosingSplitView()
{
- m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false);
+ m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false);
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
- auto tabWidget = m_mainWindow->findChild<DolphinTabWidget*>("tabWidget");
+ auto tabWidget = m_mainWindow->findChild<DolphinTabWidget *>("tabWidget");
QVERIFY(tabWidget);
QVERIFY(tabWidget->currentTabPage()->primaryViewContainer());
QVERIFY(!tabWidget->currentTabPage()->secondaryViewContainer());
// Test case for bug #385111
void DolphinMainWindowTest::testUpdateWindowTitleAfterClosingSplitView()
{
- m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false);
+ m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false);
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
- auto tabWidget = m_mainWindow->findChild<DolphinTabWidget*>("tabWidget");
+ auto tabWidget = m_mainWindow->findChild<DolphinTabWidget *>("tabWidget");
QVERIFY(tabWidget);
QVERIFY(tabWidget->currentTabPage()->primaryViewContainer());
QVERIFY(!tabWidget->currentTabPage()->secondaryViewContainer());
// Test case for bug #402641
void DolphinMainWindowTest::testUpdateWindowTitleAfterChangingSplitView()
{
- m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false);
+ m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false);
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
- auto tabWidget = m_mainWindow->findChild<DolphinTabWidget*>("tabWidget");
+ auto tabWidget = m_mainWindow->findChild<DolphinTabWidget *>("tabWidget");
QVERIFY(tabWidget);
// Open split view.
// Test case for bug #397910
void DolphinMainWindowTest::testOpenInNewTabTitle()
{
- m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false);
+ m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false);
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
- auto tabWidget = m_mainWindow->findChild<DolphinTabWidget*>("tabWidget");
+ auto tabWidget = m_mainWindow->findChild<DolphinTabWidget *>("tabWidget");
QVERIFY(tabWidget);
tabWidget->openNewTab(QUrl::fromLocalFile(QDir::tempPath()));
void DolphinMainWindowTest::testNewFileMenuEnabled()
{
QFETCH(QUrl, activeViewUrl);
- m_mainWindow->openDirectories({ activeViewUrl }, false);
+ m_mainWindow->openDirectories({activeViewUrl}, false);
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
- auto newFileMenu = m_mainWindow->findChild<DolphinNewFileMenu*>("new_menu");
+ auto newFileMenu = m_mainWindow->findChild<DolphinNewFileMenu *>("new_menu");
QVERIFY(newFileMenu);
QFETCH(bool, expectedEnabled);
void DolphinMainWindowTest::testWindowTitle()
{
QFETCH(QUrl, activeViewUrl);
- m_mainWindow->openDirectories({ activeViewUrl }, false);
+ m_mainWindow->openDirectories({activeViewUrl}, false);
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
*/
void DolphinMainWindowTest::testPlacesPanelWidthResistance()
{
- m_mainWindow->openDirectories({ QUrl::fromLocalFile(QDir::homePath()) }, false);
+ m_mainWindow->openDirectories({QUrl::fromLocalFile(QDir::homePath())}, false);
m_mainWindow->show();
m_mainWindow->resize(800, m_mainWindow->height()); // make sure the size is sufficient so a places panel resize shouldn't be necessary.
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
QWidget *placesPanel = reinterpret_cast<QWidget *>(m_mainWindow->m_placesPanel);
- QVERIFY2(QTest::qWaitFor([&](){ return placesPanel && placesPanel->isVisible() && placesPanel->width() > 0; }, 5000), "The test couldn't be initialised properly. The places panel should be visible.");
+ QVERIFY2(QTest::qWaitFor(
+ [&]() {
+ return placesPanel && placesPanel->isVisible() && placesPanel->width() > 0;
+ },
+ 5000),
+ "The test couldn't be initialised properly. The places panel should be visible.");
QTest::qWait(100);
const int initialPlacesPanelWidth = placesPanel->width();
// Make all selection mode bars appear and test for each that this doesn't affect the places panel's width.
// One of the bottom bars (SelectionMode::BottomBar::GeneralContents) only shows up when at least one item is selected so we do that before we begin iterating.
m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::SelectAll))->trigger();
- for (int selectionModeStates = SelectionMode::BottomBar::CopyContents; selectionModeStates != SelectionMode::BottomBar::RenameContents; selectionModeStates++) {
+ for (int selectionModeStates = SelectionMode::BottomBar::CopyContents; selectionModeStates != SelectionMode::BottomBar::RenameContents;
+ selectionModeStates++) {
const auto contents = static_cast<SelectionMode::BottomBar::Contents>(selectionModeStates);
m_mainWindow->slotSetSelectionMode(true, contents);
QTest::qWait(20); // give time for a paint/resize
testDir->createFile("b/b-2");
testDir->createDir("c");
QUrl childDirUrl(QDir::cleanPath(testDir->url().toString() + "/b"));
- m_mainWindow->openDirectories({ childDirUrl }, false); // Open "b" dir
+ m_mainWindow->openDirectories({childDirUrl}, false); // Open "b" dir
m_mainWindow->show();
QVERIFY(QTest::qWaitForWindowExposed(m_mainWindow.data()));
QVERIFY(m_mainWindow->isVisible());
*/
QSignalSpy spyDirectoryLoadingCompleted(m_mainWindow->m_activeViewContainer->view(), &DolphinView::directoryLoadingCompleted);
QVERIFY(spyDirectoryLoadingCompleted.wait());
- QVERIFY(QTest::qWaitFor([&](){ return !m_mainWindow->actionCollection()->action(QStringLiteral("stop"))->isEnabled(); })); // "Stop" command should be disabled because it finished loading
+ QVERIFY(QTest::qWaitFor([&]() {
+ return !m_mainWindow->actionCollection()->action(QStringLiteral("stop"))->isEnabled();
+ })); // "Stop" command should be disabled because it finished loading
QTest::qWait(500); // Somehow the item we emerged from doesn't have keyboard focus yet if we don't wait a split second.
const QUrl parentDirUrl = m_mainWindow->activeViewContainer()->url();
QVERIFY(parentDirUrl != childDirUrl);
m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Quit))->trigger();
}
-
QTEST_MAIN(DolphinMainWindowTest)
#include "dolphinmainwindowtest.moc"
#include <QJsonDocument>
#include <QJsonObject>
-#include <QStringList>
#include <QStandardPaths>
+#include <QStringList>
#include <QUrl>
#include <QUrlQuery>
/**
* Helper function to compose the baloo query URL used for searching
*/
-QUrl balooQueryUrl(const QString& searchString)
+QUrl balooQueryUrl(const QString &searchString)
{
- const QJsonObject jsonObject {
- {"searchString", searchString}
- };
+ const QJsonObject jsonObject{{"searchString", searchString}};
const QJsonDocument doc(jsonObject);
const QString queryString = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
*/
void DolphinQueryTest::testBalooSearchParsing_data()
{
-
QTest::addColumn<QUrl>("searchUrl");
QTest::addColumn<QString>("expectedText");
QTest::addColumn<QStringList>("expectedTerms");
const QString modified = QStringLiteral("modified>=2019-08-07");
const QString tag = QStringLiteral("tag:tagA");
- const QString tagS = QStringLiteral("tag:\"tagB with spaces\""); // in search url
- const QString tagR = QStringLiteral("tag:tagB with spaces"); // in result term
+ const QString tagS = QStringLiteral("tag:\"tagB with spaces\""); // in search url
+ const QString tagR = QStringLiteral("tag:tagB with spaces"); // in result term
// Test for "Content"
- QTest::newRow("content") << balooQueryUrl(text) << text << QStringList() << true << false;
- QTest::newRow("content/space") << balooQueryUrl(textS) << textS << QStringList() << true << false;
- QTest::newRow("content/quoted") << balooQueryUrl(textQ) << textS << QStringList() << true << false;
- QTest::newRow("content/empty") << balooQueryUrl("") << "" << QStringList() << false << false;
- QTest::newRow("content/single_quote") << balooQueryUrl("\"") << "\"" << QStringList() << true << false;
- QTest::newRow("content/double_quote") << balooQueryUrl("\"\"") << "" << QStringList() << false << false;
+ QTest::newRow("content") << balooQueryUrl(text) << text << QStringList() << true << false;
+ QTest::newRow("content/space") << balooQueryUrl(textS) << textS << QStringList() << true << false;
+ QTest::newRow("content/quoted") << balooQueryUrl(textQ) << textS << QStringList() << true << false;
+ QTest::newRow("content/empty") << balooQueryUrl("") << "" << QStringList() << false << false;
+ QTest::newRow("content/single_quote") << balooQueryUrl("\"") << "\"" << QStringList() << true << false;
+ QTest::newRow("content/double_quote") << balooQueryUrl("\"\"") << "" << QStringList() << false << false;
// Test for "FileName"
- QTest::newRow("filename") << balooQueryUrl(filename) << text << QStringList() << false << true;
- QTest::newRow("filename/space") << balooQueryUrl(filenameS) << textS << QStringList() << false << true;
- QTest::newRow("filename/quoted") << balooQueryUrl(filenameQ) << textQ << QStringList() << false << true;
- QTest::newRow("filename/mixed") << balooQueryUrl(filenameM) << textM << QStringList() << false << true;
- QTest::newRow("filename/empty") << balooQueryUrl("filename:") << "" << QStringList() << false << false;
- QTest::newRow("filename/single_quote") << balooQueryUrl("filename:\"") << "\"" << QStringList() << false << true;
- QTest::newRow("filename/double_quote") << balooQueryUrl("filename:\"\"") << "" << QStringList() << false << false;
+ QTest::newRow("filename") << balooQueryUrl(filename) << text << QStringList() << false << true;
+ QTest::newRow("filename/space") << balooQueryUrl(filenameS) << textS << QStringList() << false << true;
+ QTest::newRow("filename/quoted") << balooQueryUrl(filenameQ) << textQ << QStringList() << false << true;
+ QTest::newRow("filename/mixed") << balooQueryUrl(filenameM) << textM << QStringList() << false << true;
+ QTest::newRow("filename/empty") << balooQueryUrl("filename:") << "" << QStringList() << false << false;
+ QTest::newRow("filename/single_quote") << balooQueryUrl("filename:\"") << "\"" << QStringList() << false << true;
+ QTest::newRow("filename/double_quote") << balooQueryUrl("filename:\"\"") << "" << QStringList() << false << false;
// Combined content and filename search
- QTest::newRow("content+filename")
- << balooQueryUrl(text + " " + filename)
- << text + " " + filename << QStringList() << true << true;
+ QTest::newRow("content+filename") << balooQueryUrl(text + " " + filename) << text + " " + filename << QStringList() << true << true;
- QTest::newRow("content+filename/quoted")
- << balooQueryUrl(textQ + " " + filenameQ)
- << textS + " " + filenameQ << QStringList() << true << true;
+ QTest::newRow("content+filename/quoted") << balooQueryUrl(textQ + " " + filenameQ) << textS + " " + filenameQ << QStringList() << true << true;
// Test for rating
- QTest::newRow("rating") << balooQueryUrl(rating) << "" << QStringList({rating}) << false << false;
- QTest::newRow("rating+content") << balooQueryUrl(rating + " " + text) << text << QStringList({rating}) << true << false;
+ QTest::newRow("rating") << balooQueryUrl(rating) << "" << QStringList({rating}) << false << false;
+ QTest::newRow("rating+content") << balooQueryUrl(rating + " " + text) << text << QStringList({rating}) << true << false;
QTest::newRow("rating+filename") << balooQueryUrl(rating + " " + filename) << text << QStringList({rating}) << false << true;
// Test for modified date
- QTest::newRow("modified") << balooQueryUrl(modified) << "" << QStringList({modified}) << false << false;
- QTest::newRow("modified+content") << balooQueryUrl(modified + " " + text) << text << QStringList({modified}) << true << false;
+ QTest::newRow("modified") << balooQueryUrl(modified) << "" << QStringList({modified}) << false << false;
+ QTest::newRow("modified+content") << balooQueryUrl(modified + " " + text) << text << QStringList({modified}) << true << false;
QTest::newRow("modified+filename") << balooQueryUrl(modified + " " + filename) << text << QStringList({modified}) << false << true;
// Test for tags
- QTest::newRow("tag") << balooQueryUrl(tag) << "" << QStringList({tag}) << false << false;
- QTest::newRow("tag/space" ) << balooQueryUrl(tagS) << "" << QStringList({tagR}) << false << false;
- QTest::newRow("tag/double") << balooQueryUrl(tag + " " + tagS) << "" << QStringList({tag, tagR}) << false << false;
- QTest::newRow("tag+content") << balooQueryUrl(tag + " " + text) << text << QStringList({tag}) << true << false;
- QTest::newRow("tag+filename") << balooQueryUrl(tag + " " + filename) << text << QStringList({tag}) << false << true;
+ QTest::newRow("tag") << balooQueryUrl(tag) << "" << QStringList({tag}) << false << false;
+ QTest::newRow("tag/space") << balooQueryUrl(tagS) << "" << QStringList({tagR}) << false << false;
+ QTest::newRow("tag/double") << balooQueryUrl(tag + " " + tagS) << "" << QStringList({tag, tagR}) << false << false;
+ QTest::newRow("tag+content") << balooQueryUrl(tag + " " + text) << text << QStringList({tag}) << true << false;
+ QTest::newRow("tag+filename") << balooQueryUrl(tag + " " + filename) << text << QStringList({tag}) << false << true;
// Combined search terms
- QTest::newRow("searchTerms")
- << balooQueryUrl(rating + " AND " + modified + " AND " + tag + " AND " + tagS)
- << "" << QStringList({modified, rating, tag, tagR}) << false << false;
+ QTest::newRow("searchTerms") << balooQueryUrl(rating + " AND " + modified + " AND " + tag + " AND " + tagS) << ""
+ << QStringList({modified, rating, tag, tagR}) << false << false;
- QTest::newRow("searchTerms+content")
- << balooQueryUrl(rating + " AND " + modified + " " + text + " " + tag + " AND " + tagS)
- << text << QStringList({modified, rating, tag, tagR}) << true << false;
+ QTest::newRow("searchTerms+content") << balooQueryUrl(rating + " AND " + modified + " " + text + " " + tag + " AND " + tagS) << text
+ << QStringList({modified, rating, tag, tagR}) << true << false;
- QTest::newRow("searchTerms+filename")
- << balooQueryUrl(rating + " AND " + modified + " " + filename + " " + tag + " AND " + tagS)
- << text << QStringList({modified, rating, tag, tagR}) << false << true;
+ QTest::newRow("searchTerms+filename") << balooQueryUrl(rating + " AND " + modified + " " + filename + " " + tag + " AND " + tagS) << text
+ << QStringList({modified, rating, tag, tagR}) << false << true;
- QTest::newRow("allTerms")
- << balooQueryUrl(text + " " + filename + " " + rating + " AND " + modified + " AND " + tag)
- << text + " " + filename << QStringList({modified, rating, tag}) << true << true;
+ QTest::newRow("allTerms") << balooQueryUrl(text + " " + filename + " " + rating + " AND " + modified + " AND " + tag) << text + " " + filename
+ << QStringList({modified, rating, tag}) << true << true;
- QTest::newRow("allTerms/space")
- << balooQueryUrl(textS + " " + filenameS + " " + rating + " AND " + modified + " AND " + tagS)
- << textS + " " + filenameS << QStringList({modified, rating, tagR}) << true << true;
+ QTest::newRow("allTerms/space") << balooQueryUrl(textS + " " + filenameS + " " + rating + " AND " + modified + " AND " + tagS) << textS + " " + filenameS
+ << QStringList({modified, rating, tagR}) << true << true;
// Test tags:/ URL scheme
- const auto tagUrl = [](const QString &tag) { return QUrl(QStringLiteral("tags:/%1/").arg(tag)); };
- const auto tagTerms = [](const QString &tag) { return QStringList{QStringLiteral("tag:%1").arg(tag)}; };
+ const auto tagUrl = [](const QString &tag) {
+ return QUrl(QStringLiteral("tags:/%1/").arg(tag));
+ };
+ const auto tagTerms = [](const QString &tag) {
+ return QStringList{QStringLiteral("tag:%1").arg(tag)};
+ };
- QTest::newRow("tagsUrl") << tagUrl("tagA") << "" << tagTerms("tagA") << false << false;
+ QTest::newRow("tagsUrl") << tagUrl("tagA") << "" << tagTerms("tagA") << false << false;
QTest::newRow("tagsUrl/space") << tagUrl("tagB with spaces") << "" << tagTerms("tagB with spaces") << false << false;
- QTest::newRow("tagsUrl/hash") << tagUrl("tagC#hash") << "" << tagTerms("tagC#hash") << false << false;
- QTest::newRow("tagsUrl/slash") << tagUrl("tagD/with/slash") << "" << tagTerms("tagD/with/slash") << false << false;
+ QTest::newRow("tagsUrl/hash") << tagUrl("tagC#hash") << "" << tagTerms("tagC#hash") << false << false;
+ QTest::newRow("tagsUrl/slash") << tagUrl("tagD/with/slash") << "" << tagTerms("tagD/with/slash") << false << false;
}
/**
void testTextClearing();
private:
- DolphinSearchBox* m_searchBox;
+ DolphinSearchBox *m_searchBox;
};
void DolphinSearchBoxTest::initTestCase()
QTest::addColumn<QUrl>("url");
QTest::addColumn<bool>("expected");
- QTest::newRow("test_equal")
- << QList<QUrl> {QUrl::fromLocalFile("/root")}
- << QUrl::fromLocalFile("/root")
- << true;
+ QTest::newRow("test_equal") << QList<QUrl>{QUrl::fromLocalFile("/root")} << QUrl::fromLocalFile("/root") << true;
- QTest::newRow("test_trailing_slash")
- << QList<QUrl> {QUrl::fromLocalFile("/root/")}
- << QUrl::fromLocalFile("/root")
- << true;
+ QTest::newRow("test_trailing_slash") << QList<QUrl>{QUrl::fromLocalFile("/root/")} << QUrl::fromLocalFile("/root") << true;
- QTest::newRow("test_ftp_scheme")
- << QList<QUrl> {QUrl("ftp://server:2211/dir")}
- << QUrl("ftp://server:2211/dir")
- << true;
+ QTest::newRow("test_ftp_scheme") << QList<QUrl>{QUrl("ftp://server:2211/dir")} << QUrl("ftp://server:2211/dir") << true;
- QTest::newRow("test_not_matched")
- << QList<QUrl> {QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")}
- << QUrl::fromLocalFile("/usr/bin")
- << false;
+ QTest::newRow("test_not_matched") << QList<QUrl>{QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")}
+ << QUrl::fromLocalFile("/usr/bin") << false;
- QTest::newRow("test_empty_target")
- << QList<QUrl> {QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")}
- << QUrl()
- << false;
+ QTest::newRow("test_empty_target") << QList<QUrl>{QUrl::fromLocalFile("/usr/share"), QUrl::fromLocalFile("/usr/local/bin")} << QUrl() << false;
- QTest::newRow("test_empty_list")
- << QList<QUrl>()
- << QUrl::fromLocalFile("/usr/bin")
- << false;
+ QTest::newRow("test_empty_list") << QList<QUrl>() << QUrl::fromLocalFile("/usr/bin") << false;
}
void DragAndDropHelperTest::testUrlListMatchesUrl()
QCOMPARE(DragAndDropHelper::urlListMatchesUrl(urlList, url), expected);
}
-
QTEST_MAIN(DragAndDropHelperTest)
#include "draganddrophelpertest.moc"
#include <KDirLister>
#include <QGraphicsView>
-#include <QTest>
#include <QSignalSpy>
#include <QStandardPaths>
+#include <QTest>
class KFileItemListViewTest : public QObject
{
void testGroupedItemChanges();
private:
- KFileItemListView* m_listView;
- KFileItemModel* m_model;
- TestDir* m_testDir;
- QGraphicsView* m_graphicsView;
+ KFileItemListView *m_listView;
+ KFileItemModel *m_model;
+ TestDir *m_testDir;
+ QGraphicsView *m_graphicsView;
};
void KFileItemListViewTest::initTestCase()
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-#include <QTest>
#include <QSignalSpy>
#include <QStandardPaths>
+#include <QTest>
#include <random>
#include "kitemviews/kfileitemmodel.h"
#include "kitemviews/private/kfileitemmodelsortalgorithm.h"
-void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
+void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
Q_UNUSED(context)
fprintf(stderr, "Fatal: %s\n", msg.toLocal8Bit().data());
abort();
default:
- break;
+ break;
}
}
void insertAndRemoveManyItems();
private:
- static KFileItemList createFileItemList(const QStringList& fileNames, const QString& urlPrefix = QLatin1String("file:///"));
+ static KFileItemList createFileItemList(const QStringList &fileNames, const QString &urlPrefix = QLatin1String("file:///"));
};
KFileItemModelBenchmark::KFileItemModelBenchmark()
}
}
-KFileItemList KFileItemModelBenchmark::createFileItemList(const QStringList& fileNames, const QString& prefix)
+KFileItemList KFileItemModelBenchmark::createFileItemList(const QStringList &fileNames, const QString &prefix)
{
// Suppress 'file does not exist anymore' messages from KFileItemPrivate::init().
qInstallMessageHandler(myMessageOutput);
KFileItemList result;
- for (const QString& name : fileNames) {
+ for (const QString &name : fileNames) {
const KFileItem item(QUrl::fromLocalFile(prefix + name), QString(), KFileItem::Unknown);
result << item;
}
* SPDX-License-Identifier: GPL-2.0-or-later
*/
+#include <QMimeData>
#include <QRandomGenerator>
-#include <QTest>
#include <QSignalSpy>
#include <QStandardPaths>
+#include <QTest>
#include <QTimer>
-#include <QMimeData>
#include <KDirLister>
#include <kio/job.h>
#include <kio_version.h>
-
#include "kitemviews/kfileitemmodel.h"
#include "testdir.h"
-void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
+void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
Q_UNUSED(context)
fprintf(stderr, "Fatal: %s\n", msg.toLocal8Bit().data());
abort();
default:
- break;
+ break;
}
}
QStringList itemsInModel() const;
private:
- KFileItemModel* m_model;
- TestDir* m_testDir;
+ KFileItemModel *m_model;
+ TestDir *m_testDir;
};
void KFileItemModelTest::initTestCase()
// Index 2 = rating 6
QTest::newRow("Index 0: Rating 3") << 0 << 3 << false << 3 << 4 << 6;
- QTest::newRow("Index 0: Rating 5") << 0 << 5 << true << 4 << 5 << 6;
- QTest::newRow("Index 0: Rating 8") << 0 << 8 << true << 4 << 6 << 8;
+ QTest::newRow("Index 0: Rating 5") << 0 << 5 << true << 4 << 5 << 6;
+ QTest::newRow("Index 0: Rating 8") << 0 << 8 << true << 4 << 6 << 8;
- QTest::newRow("Index 2: Rating 1") << 2 << 1 << true << 1 << 2 << 4;
- QTest::newRow("Index 2: Rating 3") << 2 << 3 << true << 2 << 3 << 4;
+ QTest::newRow("Index 2: Rating 1") << 2 << 1 << true << 1 << 2 << 4;
+ QTest::newRow("Index 2: Rating 3") << 2 << 3 << true << 2 << 3 << 4;
QTest::newRow("Index 2: Rating 5") << 2 << 5 << false << 2 << 4 << 5;
}
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.jpg" << "c.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.jpg"
+ << "c.txt");
// Simulate that KFileItemModelRolesUpdater determines the mime type.
// Resorting the files by 'type' will only work immediately if their
// The actual order of the files might depend on the translation of the
// result of KFileItem::mimeComment() in the user's language.
QStringList version1;
- version1 << "b.jpg" << "a.txt" << "c.txt";
+ version1 << "b.jpg"
+ << "a.txt"
+ << "c.txt";
QStringList version2;
- version2 << "a.txt" << "c.txt" << "b.jpg";
+ version2 << "a.txt"
+ << "c.txt"
+ << "b.jpg";
const bool ok1 = (itemsInModel() == version1);
const bool ok2 = (itemsInModel() == version2);
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.txt");
// We rename a.txt to d.txt. Even though the size has not changed at all,
// the model must re-sort the items.
m_model->setData(0, data);
QVERIFY(itemsMovedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "c.txt" << "d.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "b.txt"
+ << "c.txt"
+ << "d.txt");
// We rename d.txt back to a.txt using the dir lister's refreshItems() signal.
const KFileItem fileItemD = m_model->fileItem(2);
m_model->slotRefreshItems({qMakePair(fileItemD, fileItemA)});
QVERIFY(itemsMovedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.txt");
}
void KFileItemModelTest::testModelConsistencyWhenInsertingItems()
// first three characters.
QSet<QByteArray> originalModelRoles = m_model->roles();
QSet<QByteArray> modelRoles = originalModelRoles;
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a/a/1", "a/a-1/1"});
// Store the URLs of all folders in a set.
QSet<QUrl> allFolders;
- allFolders << QUrl::fromLocalFile(m_testDir->path() + "/a")
- << QUrl::fromLocalFile(m_testDir->path() + "/a/a")
+ allFolders << QUrl::fromLocalFile(m_testDir->path() + "/a") << QUrl::fromLocalFile(m_testDir->path() + "/a/a")
<< QUrl::fromLocalFile(m_testDir->path() + "/a/a-1");
m_model->loadDirectory(m_testDir->url());
m_model->setExpanded(1, true);
QVERIFY(m_model->isExpanded(1));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(m_model->count(), 4); // 4 items: "a/", "a/a/", "a/a/1", "a/a-1/"
- QCOMPARE(m_model->expandedDirectories(), QSet<QUrl>() << QUrl::fromLocalFile(m_testDir->path() + "/a")
- << QUrl::fromLocalFile(m_testDir->path() + "/a/a"));
+ QCOMPARE(m_model->count(), 4); // 4 items: "a/", "a/a/", "a/a/1", "a/a-1/"
+ QCOMPARE(m_model->expandedDirectories(), QSet<QUrl>() << QUrl::fromLocalFile(m_testDir->path() + "/a") << QUrl::fromLocalFile(m_testDir->path() + "/a/a"));
QCOMPARE(itemsInsertedSpy.count(), 1);
itemRangeList = itemsInsertedSpy.takeFirst().at(0).value<KItemRangeList>();
m_model->setExpanded(3, true);
QVERIFY(m_model->isExpanded(3));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1"
+ QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1"
QCOMPARE(m_model->expandedDirectories(), allFolders);
QCOMPARE(itemsInsertedSpy.count(), 1);
m_model->loadDirectory(m_testDir->url());
m_model->restoreExpandedDirectories(allFolders);
QVERIFY(loadingCompletedSpy.wait());
- QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1"
+ QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1"
QVERIFY(m_model->isExpanded(0));
QVERIFY(m_model->isExpanded(1));
QVERIFY(!m_model->isExpanded(2));
// This is how DolphinView restores the expanded folders when navigating in history.
m_model->loadDirectory(QUrl::fromLocalFile(m_testDir->path() + "/a/a/"));
QVERIFY(loadingCompletedSpy.wait());
- QCOMPARE(m_model->count(), 1); // 1 item: "1"
+ QCOMPARE(m_model->count(), 1); // 1 item: "1"
m_model->restoreExpandedDirectories(allFolders);
m_model->loadDirectory(m_testDir->url());
QVERIFY(loadingCompletedSpy.wait());
- QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1"
+ QCOMPARE(m_model->count(), 5); // 5 items: "a/", "a/a/", "a/a/1", "a/a-1/", "a/a-1/1"
QCOMPARE(m_model->expandedDirectories(), allFolders);
// Remove all expanded items by changing the roles
// a2/b2/c2/
// a2/b2/c2/d2/
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a 1/b1/c1/file.txt", "a2/b2/c2/d2/file.txt"});
QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"1a/2a/3a", "1a/2a/3b", "1a/2b", "1b"});
const QUrl oldUrl = QUrl::fromLocalFile(m_model->fileItem(0).url().path() + "/2a");
const QUrl newUrl = QUrl::fromLocalFile(m_model->fileItem(0).url().path() + "/.2a");
- KIO::SimpleJob* job = KIO::rename(oldUrl, newUrl, KIO::HideProgressInfo);
+ KIO::SimpleJob *job = KIO::rename(oldUrl, newUrl, KIO::HideProgressInfo);
bool ok = job->exec();
QVERIFY(ok);
QVERIFY(itemsRemovedSpy.wait());
m_model->setExpanded(0, false);
QCOMPARE(m_model->count(), 2);
-
}
void KFileItemModelTest::testRemoveFilteredExpandedItems()
QSet<QByteArray> originalModelRoles = m_model->roles();
QSet<QByteArray> modelRoles = originalModelRoles;
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"folder/child", "file"});
QVERIFY(!m_model->isExpandable(1));
QVERIFY(!m_model->isExpanded(0));
QVERIFY(!m_model->isExpanded(1));
- QCOMPARE(itemsInModel(), QStringList() << "folder" << "file");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "folder"
+ << "file");
// Expand "folder" -> "folder/child" becomes visible.
m_model->setExpanded(0, true);
QVERIFY(m_model->isExpanded(0));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "folder" << "child" << "file");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "folder"
+ << "child"
+ << "file");
// Add a name filter.
m_model->setNameFilter("f");
- QCOMPARE(itemsInModel(), QStringList() << "folder" << "file");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "folder"
+ << "file");
m_model->setNameFilter("fo");
QCOMPARE(itemsInModel(), QStringList() << "folder");
// Remove the name filter and verify that "folder/child" does not reappear.
m_model->setNameFilter(QString());
- QCOMPARE(itemsInModel(), QStringList() << "folder" << "file");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "folder"
+ << "file");
}
void KFileItemModelTest::testSorting()
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
QVERIFY(m_model->sortDirectoriesFirst());
QVERIFY(!m_model->showHiddenFiles());
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "d" << "e");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "a"
+ << "b"
+ << "d"
+ << "e");
// Sort by Name, ascending, 'Sort Folders First' disabled
m_model->setSortDirectoriesFirst(false);
QCOMPARE(m_model->sortRole(), QByteArray("text"));
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c" << "c-1" << "c-2" << "c-3" << "d" << "e");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "c"
+ << "c-1"
+ << "c-2"
+ << "c-3"
+ << "d"
+ << "e");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(0, 6));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 2 << 4 << 5 << 3 << 0 << 1);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 2 << 4 << 5 << 3 << 0 << 1);
// Sort by Name, descending
m_model->setSortDirectoriesFirst(true);
m_model->setSortOrder(Qt::DescendingOrder);
QCOMPARE(m_model->sortRole(), QByteArray("text"));
QCOMPARE(m_model->sortOrder(), Qt::DescendingOrder);
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "e" << "d" << "b" << "a");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "e"
+ << "d"
+ << "b"
+ << "a");
QCOMPARE(itemsMovedSpy.count(), 2);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(0, 6));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 4 << 5 << 0 << 3 << 1 << 2);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 4 << 5 << 0 << 3 << 1 << 2);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 4));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 7 << 6 << 5 << 4);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 7 << 6 << 5 << 4);
// Sort by Date, descending
m_model->setSortDirectoriesFirst(true);
m_model->setSortRole("modificationtime");
QCOMPARE(m_model->sortRole(), QByteArray("modificationtime"));
QCOMPARE(m_model->sortOrder(), Qt::DescendingOrder);
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "b" << "d" << "a" << "e");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "b"
+ << "d"
+ << "a"
+ << "e");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 4));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 7 << 5 << 4 << 6);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 7 << 5 << 4 << 6);
// Sort by Date, ascending
m_model->setSortOrder(Qt::AscendingOrder);
QCOMPARE(m_model->sortRole(), QByteArray("modificationtime"));
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "e" << "a" << "d" << "b");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "e"
+ << "a"
+ << "d"
+ << "b");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 4));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 7 << 6 << 5 << 4);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 7 << 6 << 5 << 4);
// Sort by Date, ascending, 'Sort Folders First' disabled
m_model->setSortDirectoriesFirst(false);
QCOMPARE(m_model->sortRole(), QByteArray("modificationtime"));
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
QVERIFY(!m_model->sortDirectoriesFirst());
- QCOMPARE(itemsInModel(), QStringList() << "e" << "a" << "c" << "c-1" << "c-2" << "c-3" << "d" << "b");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "e"
+ << "a"
+ << "c"
+ << "c-1"
+ << "c-2"
+ << "c-3"
+ << "d"
+ << "b");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(0, 6));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 2 << 4 << 5 << 3 << 0 << 1);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 2 << 4 << 5 << 3 << 0 << 1);
// Sort by Name, ascending, 'Sort Folders First' disabled
m_model->setSortRole("text");
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
QVERIFY(!m_model->sortDirectoriesFirst());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c" << "c-1" << "c-2" << "c-3" << "d" << "e");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "c"
+ << "c-1"
+ << "c-2"
+ << "c-3"
+ << "d"
+ << "e");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(0, 8));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 7 << 0 << 2 << 3 << 4 << 5 << 6 << 1);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 7 << 0 << 2 << 3 << 4 << 5 << 6 << 1);
// Sort by Size, ascending, 'Sort Folders First' disabled
m_model->setSortRole("size");
QCOMPARE(m_model->sortRole(), QByteArray("size"));
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
QVERIFY(!m_model->sortDirectoriesFirst());
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "e" << "d");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "a"
+ << "b"
+ << "e"
+ << "d");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(0, 8));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 4 << 5 << 0 << 3 << 1 << 2 << 7 << 6);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 4 << 5 << 0 << 3 << 1 << 2 << 7 << 6);
// In 'Sort by Size' mode, folders are always first -> changing 'Sort Folders First' does not resort the model
m_model->setSortDirectoriesFirst(true);
QCOMPARE(m_model->sortRole(), QByteArray("size"));
QCOMPARE(m_model->sortOrder(), Qt::AscendingOrder);
QVERIFY(m_model->sortDirectoriesFirst());
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "e" << "d");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "a"
+ << "b"
+ << "e"
+ << "d");
QCOMPARE(itemsMovedSpy.count(), 0);
// Sort by Size, descending, 'Sort Folders First' enabled
QCOMPARE(m_model->sortRole(), QByteArray("size"));
QCOMPARE(m_model->sortOrder(), Qt::DescendingOrder);
QVERIFY(m_model->sortDirectoriesFirst());
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "d" << "e" << "b" << "a");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "d"
+ << "e"
+ << "b"
+ << "a");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 4));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 7 << 6 << 5 << 4);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 7 << 6 << 5 << 4);
// 'Show Hidden Files' enabled
m_model->setShowHiddenFiles(true);
QVERIFY(m_model->showHiddenFiles());
QVERIFY(!m_model->sortHiddenLast());
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << ".g" << "d" << "e" << "b" << "a" << ".f");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << ".g"
+ << "d"
+ << "e"
+ << "b"
+ << "a"
+ << ".f");
QCOMPARE(itemsMovedSpy.count(), 0);
QCOMPARE(itemsInsertedSpy.count(), 1);
QCOMPARE(itemsInsertedSpy.takeFirst().at(0).value<KItemRangeList>(), KItemRangeList() << KItemRange(4, 1) << KItemRange(8, 1));
// 'Sort Hidden Files Last' enabled
m_model->setSortHiddenLast(true);
QVERIFY(m_model->sortHiddenLast());
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "d" << "e" << "b" << "a" << ".g" << ".f");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "d"
+ << "e"
+ << "b"
+ << "a"
+ << ".g"
+ << ".f");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsInsertedSpy.count(), 0);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 5));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 8 << 4 << 5 << 6 << 7);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 8 << 4 << 5 << 6 << 7);
// Sort by Name
m_model->setSortRole("text");
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "e" << "d" << "b" << "a" << ".g" << ".f");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "e"
+ << "d"
+ << "b"
+ << "a"
+ << ".g"
+ << ".f");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 2));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 5 << 4);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 5 << 4);
// Sort ascending
m_model->setSortOrder(Qt::AscendingOrder);
- QCOMPARE(itemsInModel(), QStringList() << "c" << "c-2" << "c-3" << "c-1" << "a" << "b" << "d" << "e" << ".g" << ".f");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "c-2"
+ << "c-3"
+ << "c-1"
+ << "a"
+ << "b"
+ << "d"
+ << "e"
+ << ".g"
+ << ".f");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(4, 4));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 7 << 6 << 5 << 4);
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 7 << 6 << 5 << 4);
// 'Sort Folders First' disabled
m_model->setSortDirectoriesFirst(false);
QVERIFY(!m_model->sortDirectoriesFirst());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c" << "c-1" << "c-2" << "c-3" << "d" << "e" << ".f" << ".g");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "c"
+ << "c-1"
+ << "c-2"
+ << "c-3"
+ << "d"
+ << "e"
+ << ".f"
+ << ".g");
QCOMPARE(itemsMovedSpy.count(), 1);
QCOMPARE(itemsMovedSpy.first().at(0).value<KItemRange>(), KItemRange(0, 10));
- QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int> >(), QList<int>() << 2 << 4 << 5 << 3 << 0 << 1 << 6 << 7 << 9 << 8);
-
+ QCOMPARE(itemsMovedSpy.takeFirst().at(1).value<QList<int>>(), QList<int>() << 2 << 4 << 5 << 3 << 0 << 1 << 6 << 7 << 9 << 8);
}
void KFileItemModelTest::testIndexForKeyboardSearch()
QVERIFY(itemsChangedSpy.isValid());
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a/1", "a/2", "3", "4"});
QSignalSpy fileItemsChangedSpy(m_model, &KFileItemModel::fileItemsChanged);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFile("a/b/file");
// Expand "a/".
m_model->setExpanded(0, true);
- QVERIFY(itemsInsertedSpy.wait());
+ QVERIFY(itemsInsertedSpy.wait());
// Expand "a/b/".
m_model->setExpanded(1, true);
// Entire parental chain should now be shown
QCOMPARE(m_model->count(), 3); // 3 items: "a/", "a/b/", "a/b/newItem.txt"
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "newItem.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "newItem.txt");
// Items should be indented in hierarchy
QCOMPARE(m_model->expandedParentsCount(0), 0);
{
QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted);
QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved);
-
+
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFile("a/b/file");
// Expand "a/".
m_model->setExpanded(0, true);
- QVERIFY(itemsInsertedSpy.wait());
+ QVERIFY(itemsInsertedSpy.wait());
// Expand "a/b/".
m_model->setExpanded(1, true);
// Set a filter that matches ".txt" extension
m_model->setNameFilter("*.txt");
QCOMPARE(m_model->count(), 3); // Still all items are shown
- QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "c.txt" << "d.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "b.txt"
+ << "c.txt"
+ << "d.txt");
// Objects used to rename
const KFileItem fileItemC_txt = m_model->fileItem(1);
QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(1, 1));
// Re-sorting is done asynchronously:
- QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "a.txt"); // Files should still be in the incorrect order
+ QCOMPARE(itemsInModel(),
+ QStringList() << "b.txt"
+ << "a.txt"); // Files should still be in the incorrect order
QVERIFY(itemsMovedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt"); // Files were re-sorted and should now be in the correct order
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"); // Files were re-sorted and should now be in the correct order
}
-
/**
* Verifies that parental chains are hidden and shown as needed while their children get filtered/unfiltered due to renaming.
* Also verifies that the "isExpanded" and "expandedParentsCount" values are kept for expanded folders that get refreshed.
*/
-void KFileItemModelTest::testRefreshExpandedFolderWithFilter() {
+void KFileItemModelTest::testRefreshExpandedFolderWithFilter()
+{
QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted);
QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFile("a/b/someFolder/someFile");
// Expand "a/".
m_model->setExpanded(0, true);
- QVERIFY(itemsInsertedSpy.wait());
+ QVERIFY(itemsInsertedSpy.wait());
// Expand "a/b/".
m_model->setExpanded(1, true);
// Objects used to rename
const KFileItem fileItemA = m_model->fileItem(0);
KFileItem fileItemARenamed = fileItemA;
- fileItemARenamed.setUrl(QUrl("a_renamed"));
+ fileItemARenamed.setUrl(QUrl("a_renamed"));
const KFileItem fileItemSomeFolder = m_model->fileItem(2);
KFileItem fileItemRenamedFolder = fileItemSomeFolder;
// This way we test if the algorithm is sane as to NOT hide "a_renamed" since it will have visible children
m_model->slotRefreshItems({qMakePair(fileItemA, fileItemARenamed)});
QCOMPARE(m_model->count(), 3); // Entire parental chain must still be shown
- QCOMPARE(itemsInModel(), QStringList() << "a_renamed" << "b" << "someFolder");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a_renamed"
+ << "b"
+ << "someFolder");
// Rename "a_renamed" back to "a"; and "someFolder" to "renamedFolder"
m_model->slotRefreshItems({qMakePair(fileItemARenamed, fileItemA), qMakePair(fileItemSomeFolder, fileItemRenamedFolder)});
// Rename "renamedFolder" back to "someFolder". Filter is passing again
m_model->slotRefreshItems({qMakePair(fileItemRenamedFolder, fileItemSomeFolder)});
QCOMPARE(m_model->count(), 3); // Entire parental chain is shown again
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "someFolder");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "someFolder");
// slotRefreshItems() should preserve "isExpanded" and "expandedParentsCount" values explicitly in this case
QCOMPARE(m_model->m_itemData.at(2)->values.value("isExpanded").toBool(), true);
m_model->setShowHiddenFiles(true);
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << ".a" << ".b" << "c" << "d" <<".f" << ".g" << "h" << "i");
+ QCOMPARE(itemsInModel(),
+ QStringList() << ".a"
+ << ".b"
+ << "c"
+ << "d"
+ << ".f"
+ << ".g"
+ << "h"
+ << "i");
QCOMPARE(itemsInsertedSpy.count(), 1);
QCOMPARE(itemsRemovedSpy.count(), 0);
KItemRangeList itemRangeList = itemsInsertedSpy.takeFirst().at(0).value<KItemRangeList>();
QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(0, 8));
m_model->setShowHiddenFiles(false);
- QCOMPARE(itemsInModel(), QStringList() << "c" << "d" << "h" << "i");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c"
+ << "d"
+ << "h"
+ << "i");
QCOMPARE(itemsInsertedSpy.count(), 0);
QCOMPARE(itemsRemovedSpy.count(), 1);
itemRangeList = itemsRemovedSpy.takeFirst().at(0).value<KItemRangeList>();
QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(0, 2) << KItemRange(4, 2));
m_model->setShowHiddenFiles(true);
- QCOMPARE(itemsInModel(), QStringList() << ".a" << ".b" << "c" << "d" <<".f" << ".g" << "h" << "i");
+ QCOMPARE(itemsInModel(),
+ QStringList() << ".a"
+ << ".b"
+ << "c"
+ << "d"
+ << ".f"
+ << ".g"
+ << "h"
+ << "i");
QCOMPARE(itemsInsertedSpy.count(), 1);
QCOMPARE(itemsRemovedSpy.count(), 0);
itemRangeList = itemsInsertedSpy.takeFirst().at(0).value<KItemRangeList>();
QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a/1", "a/b/1", "a/b/c/1", "a/b/c/d/1"});
QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a/1", "a/b/1", "a/b/c/1", "a/b/c/d/1"});
m_model->setNameFilter("c");
QCOMPARE(itemsRemovedSpy.count(), 1); // nothing was removed, itemsRemovedSpy count will remain the same:
QCOMPARE(m_model->count(), 3);
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "c");
// Simulate the deletion of the directory "a/b/".
m_model->slotItemsDeleted(KFileItemList() << m_model->fileItem(1));
// Remove the filter -> only the file "a/1" should appear.
m_model->setNameFilter(QString());
QCOMPARE(m_model->count(), 2);
- QCOMPARE(itemsInModel(), QStringList() << "a" << "1");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "1");
}
/**
QSignalSpy itemsRemovedSpy(m_model, &KFileItemModel::itemsRemoved);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"parent1/realChild1/realGrandChild1", "parent2/realChild2/realGrandChild2"});
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "parent2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "parent2");
// Expand all folders.
m_model->setExpanded(0, true);
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "parent2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "parent2");
m_model->setExpanded(1, true);
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "parent2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "realGrandChild1"
+ << "parent2");
m_model->setExpanded(3, true);
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "parent2" << "realChild2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "realGrandChild1"
+ << "parent2"
+ << "realChild2");
m_model->setExpanded(4, true);
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "parent2" << "realChild2" << "realGrandChild2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "realGrandChild1"
+ << "parent2"
+ << "realChild2"
+ << "realGrandChild2");
// Add some more children and grand-children.
const QUrl parent1 = m_model->fileItem(0).url();
m_model->slotItemsAdded(parent1, KFileItemList() << KFileItem(QUrl("child1"), QString(), KFileItem::Unknown));
m_model->slotCompleted();
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "realGrandChild2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "realGrandChild1"
+ << "child1"
+ << "parent2"
+ << "realChild2"
+ << "realGrandChild2");
m_model->slotItemsAdded(parent2, KFileItemList() << KFileItem(QUrl("child2"), QString(), KFileItem::Unknown));
m_model->slotCompleted();
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "realGrandChild2" << "child2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "realGrandChild1"
+ << "child1"
+ << "parent2"
+ << "realChild2"
+ << "realGrandChild2"
+ << "child2");
m_model->slotItemsAdded(realChild1, KFileItemList() << KFileItem(QUrl("grandChild1"), QString(), KFileItem::Unknown));
m_model->slotCompleted();
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "grandChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "realGrandChild2" << "child2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "grandChild1"
+ << "realGrandChild1"
+ << "child1"
+ << "parent2"
+ << "realChild2"
+ << "realGrandChild2"
+ << "child2");
m_model->slotItemsAdded(realChild2, KFileItemList() << KFileItem(QUrl("grandChild2"), QString(), KFileItem::Unknown));
m_model->slotCompleted();
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "grandChild1" << "realGrandChild1" << "child1" << "parent2" << "realChild2" << "grandChild2" << "realGrandChild2" << "child2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "grandChild1"
+ << "realGrandChild1"
+ << "child1"
+ << "parent2"
+ << "realChild2"
+ << "grandChild2"
+ << "realGrandChild2"
+ << "child2");
// Set a name filter that matches nothing -> nothing will remain.
m_model->setNameFilter("xyz");
// Set a name filter that matches only "realChild". Their prarents should still show.
m_model->setNameFilter("realChild");
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "realChild1" << "parent2" << "realChild2");
- QCOMPARE(itemsRemovedSpy.count(), 0); // nothing was removed, itemsRemovedSpy will not be called this time
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "realChild1"
+ << "parent2"
+ << "realChild2");
+ QCOMPARE(itemsRemovedSpy.count(), 0); // nothing was removed, itemsRemovedSpy will not be called this time
// Collapse "parent1".
m_model->setExpanded(0, false);
- QCOMPARE(itemsInModel(), QStringList() << "parent1" << "parent2" << "realChild2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "parent1"
+ << "parent2"
+ << "realChild2");
QCOMPARE(itemsRemovedSpy.count(), 1);
arguments = itemsRemovedSpy.takeFirst();
itemRangeList = arguments.at(0).value<KItemRangeList>();
m_model->setGroupedSorting(true);
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "b.txt" << "c.txt" << "d.txt" << "e.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "b.txt"
+ << "c.txt"
+ << "d.txt"
+ << "e.txt");
- QList<QPair<int, QVariant> > expectedGroups;
+ QList<QPair<int, QVariant>> expectedGroups;
expectedGroups << QPair<int, QVariant>(0, QLatin1String("B"));
expectedGroups << QPair<int, QVariant>(1, QLatin1String("C"));
expectedGroups << QPair<int, QVariant>(2, QLatin1String("D"));
data.insert("text", "a.txt");
m_model->setData(2, data);
QVERIFY(itemsMovedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt" << "e.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.txt"
+ << "e.txt");
expectedGroups.clear();
expectedGroups << QPair<int, QVariant>(0, QLatin1String("A"));
data.insert("text", "d.txt");
m_model->setData(2, data);
QVERIFY(groupsChangedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "d.txt" << "e.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "d.txt"
+ << "e.txt");
expectedGroups.clear();
expectedGroups << QPair<int, QVariant>(0, QLatin1String("A"));
m_model->slotRefreshItems({qMakePair(fileItemD, fileItemC)});
QVERIFY(groupsChangedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt" << "e.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.txt"
+ << "e.txt");
expectedGroups.clear();
expectedGroups << QPair<int, QVariant>(0, QLatin1String("A"));
QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a/b.txt", "a/c.txt", "d/e.txt", "d/f.txt"});
m_model->setGroupedSorting(true);
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "d");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "d");
- QList<QPair<int, QVariant> > expectedGroups;
+ QList<QPair<int, QVariant>> expectedGroups;
expectedGroups << QPair<int, QVariant>(0, QLatin1String("A"));
expectedGroups << QPair<int, QVariant>(1, QLatin1String("D"));
QCOMPARE(m_model->groups(), expectedGroups);
m_model->setExpanded(0, true);
QVERIFY(m_model->isExpanded(0));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b.txt" << "c.txt" << "d");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b.txt"
+ << "c.txt"
+ << "d");
QCOMPARE(m_model->groups(), expectedGroups);
m_model->setExpanded(3, true);
QVERIFY(m_model->isExpanded(3));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b.txt" << "c.txt" << "d" << "e.txt" << "f.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b.txt"
+ << "c.txt"
+ << "d"
+ << "e.txt"
+ << "f.txt");
QCOMPARE(m_model->groups(), expectedGroups);
}
QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFiles({"a/b/c1.txt", "a/b/c2.txt"});
m_model->setExpanded(0, true);
QVERIFY(m_model->isExpanded(0));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b");
m_model->setExpanded(1, true);
QVERIFY(m_model->isExpanded(1));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c1.txt" << "c2.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "c1.txt"
+ << "c2.txt");
// Add the files "c1.txt" and "c2.txt" to the model also as top-level items.
// Such a thing can in principle happen when performing a search, and there
items << newItem << m_model->fileItem(2) << m_model->fileItem(3);
m_model->slotItemsAdded(m_model->directory(), items);
m_model->slotCompleted();
- QCOMPARE(itemsInModel(), QStringList() << "a" << "b" << "c1.txt" << "c2.txt" << "a2" << "c1.txt" << "c2.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "b"
+ << "c1.txt"
+ << "c2.txt"
+ << "a2"
+ << "c1.txt"
+ << "c2.txt");
m_model->setExpanded(0, false);
// Test that the right items have been removed, see
// https://bugs.kde.org/show_bug.cgi?id=324371
- QCOMPARE(itemsInModel(), QStringList() << "a" << "a2" << "c1.txt" << "c2.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "a2"
+ << "c1.txt"
+ << "c2.txt");
// Test that resorting does not cause a crash, see
// https://bugs.kde.org/show_bug.cgi?id=325359
// The crash is not 100% reproducible, but Valgrind will report an invalid memory access.
m_model->resortAllItems();
-
}
void KFileItemModelTest::testChangeRolesForFilteredItems()
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "aa.txt" << "aaa.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "aa.txt"
+ << "aaa.txt");
for (int index = 0; index < m_model->count(); ++index) {
// All items should have the "text" and "owner" roles, but not "group".
// Modify the filter, such that "aa.txt" reappears, and verify that all items have the expected roles.
m_model->setNameFilter("aa");
- QCOMPARE(itemsInModel(), QStringList() << "aa.txt" << "aaa.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "aa.txt"
+ << "aaa.txt");
for (int index = 0; index < m_model->count(); ++index) {
// All items should have the "text", "owner", and "group" roles.
// Clear the filter, and verify that all items have the expected roles
m_model->setNameFilter(QString());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "aa.txt" << "aaa.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "aa.txt"
+ << "aaa.txt");
for (int index = 0; index < m_model->count(); ++index) {
// All items should have the "text" and "group" roles, but now "owner".
entry[2].fastInsert(KIO::UDSEntry::UDS_USER, "user-a");
for (int i = 0; i < 3; ++i) {
- entry[i].fastInsert(KIO::UDSEntry::UDS_FILE_TYPE, 0100000); // S_IFREG might not be defined on non-Unix platforms.
+ entry[i].fastInsert(KIO::UDSEntry::UDS_FILE_TYPE, 0100000); // S_IFREG might not be defined on non-Unix platforms.
entry[i].fastInsert(KIO::UDSEntry::UDS_ACCESS, 07777);
entry[i].fastInsert(KIO::UDSEntry::UDS_SIZE, 0);
entry[i].fastInsert(KIO::UDSEntry::UDS_MODIFICATION_TIME, 0);
m_model->slotItemsAdded(m_testDir->url(), items);
m_model->slotCompleted();
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.txt");
// Add a filter.
m_model->setNameFilter("a");
// Clear the filter, and verify that the items are sorted correctly.
m_model->setNameFilter(QString());
- QCOMPARE(itemsInModel(), QStringList() << "c.txt" << "a.txt" << "b.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "c.txt"
+ << "a.txt"
+ << "b.txt");
}
void KFileItemModelTest::testRefreshFilteredItems()
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.jpg" << "d.jpg");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.jpg"
+ << "d.jpg");
const KFileItem fileItemC = m_model->fileItem(2);
// Show only the .txt files.
m_model->setNameFilter(".txt");
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt");
// Rename one of the .jpg files.
KFileItem fileItemE = fileItemC;
// Show all files again, and verify that the model has updated the file name.
m_model->setNameFilter(QString());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "d.jpg" << "e.jpg");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "d.jpg"
+ << "e.jpg");
}
void KFileItemModelTest::testCreateMimeData()
QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFile("a/1");
// Expand "a/".
m_model->setExpanded(0, true);
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a" << "1");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a"
+ << "1");
// Verify that creating the MIME data for a child of an expanded folder does
// not cause a crash, see https://bugs.kde.org/show_bug.cgi?id=329119
KItemSet selection;
selection.insert(1);
- QMimeData* mimeData = m_model->createMimeData(selection);
+ QMimeData *mimeData = m_model->createMimeData(selection);
delete mimeData;
}
QSignalSpy itemsInsertedSpy(m_model, &KFileItemModel::itemsInserted);
QSet<QByteArray> modelRoles = m_model->roles();
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFile("a2/b/c1.txt");
m_model->setExpanded(0, true);
QVERIFY(m_model->isExpanded(0));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a2" << "b");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a2"
+ << "b");
// Expand "a2/b/".
m_model->setExpanded(1, true);
QVERIFY(m_model->isExpanded(1));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a2" << "b" << "c1.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a2"
+ << "b"
+ << "c1.txt");
// Simulate that a new item "c2.txt" appears, but that the dir lister's completed()
// signal is not emitted yet.
const QUrl urlB = m_model->fileItem(1).url();
m_model->slotItemsAdded(urlB, KFileItemList() << fileItemC2);
- QCOMPARE(itemsInModel(), QStringList() << "a2" << "b" << "c1.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a2"
+ << "b"
+ << "c1.txt");
// Collapse "a2/". This should also remove all its (indirect) children from
// the model and from the model's m_pendingItemsToInsert member.
m_model->setExpanded(0, true);
QVERIFY(m_model->isExpanded(0));
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a2" << "b");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a2"
+ << "b");
// Now simulate that a new folder "a1/" is appears, but that the dir lister's
// completed() signal is not emitted yet.
fileItemA1.setUrl(urlA1);
m_model->slotItemsAdded(m_model->directory(), KFileItemList() << fileItemA1);
- QCOMPARE(itemsInModel(), QStringList() << "a2" << "b");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a2"
+ << "b");
// Collapse "a2/". Note that this will cause "a1/" to be added to the model,
// i.e., the index of "a2/" will change from 0 to 1. Check that this does not
// confuse the code which collapses the folder.
m_model->setExpanded(0, false);
- QCOMPARE(itemsInModel(), QStringList() << "a1" << "a2");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a1"
+ << "a2");
QVERIFY(!m_model->isExpanded(0));
QVERIFY(!m_model->isExpanded(1));
}
m_model->loadDirectory(m_testDir->url());
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "b.txt" << "c.txt" << "d.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "b.txt"
+ << "c.txt"
+ << "d.txt");
const KFileItem fileItemB = m_model->fileItem(1);
m_model->slotItemsDeleted(list);
QVERIFY(m_model->isConsistent());
- QCOMPARE(itemsInModel(), QStringList() << "a.txt" << "c.txt" << "d.txt");
+ QCOMPARE(itemsInModel(),
+ QStringList() << "a.txt"
+ << "c.txt"
+ << "d.txt");
}
void KFileItemModelTest::testInsertAfterExpand()
// Test expanding subfolders in a folder with the items "a/", "a/a/"
QSet<QByteArray> originalModelRoles = m_model->roles();
QSet<QByteArray> modelRoles = originalModelRoles;
- modelRoles << "isExpanded" << "isExpandable" << "expandedParentsCount";
+ modelRoles << "isExpanded"
+ << "isExpandable"
+ << "expandedParentsCount";
m_model->setRoles(modelRoles);
m_testDir->createFile("a/b/1");
KItemRangeList itemRangeList = itemsInsertedSpy.takeFirst().at(0).value<KItemRangeList>();
QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(0, 1)); // 1 new item "a/" with index 0
QCOMPARE(m_model->expandedParentsCount(0), 0);
-
}
itemsInsertedSpy.clear();
KItemRangeList itemRangeList = itemsInsertedSpy.takeFirst().at(0).value<KItemRangeList>();
QCOMPARE(itemRangeList, KItemRangeList() << KItemRange(1, 1)); // 1 new item "a/b" with index 1
QCOMPARE(m_model->expandedParentsCount(1), 1);
-
}
itemsInsertedSpy.clear();
// Expand "a/b" -> "a/b/1" becomes visible
m_model->setExpanded(1, true);
QVERIFY(itemsInsertedSpy.wait());
- QCOMPARE(m_model->expandedDirectories(), QSet({QUrl::fromLocalFile(m_testDir->path() + "/a"),
- QUrl::fromLocalFile(m_testDir->path() + "/a/b")}));
+ QCOMPARE(m_model->expandedDirectories(), QSet({QUrl::fromLocalFile(m_testDir->path() + "/a"), QUrl::fromLocalFile(m_testDir->path() + "/a/b")}));
QCOMPARE(itemsInsertedSpy.count(), 1);
{
// Insert additional files into "a/b/"
m_testDir->createFile("a/b/2");
- #if KIO_VERSION < QT_VERSION_CHECK(5, 92, 0)
- QEXPECT_FAIL("", "Requires new API from frameworks", Abort);
- #endif
+#if KIO_VERSION < QT_VERSION_CHECK(5, 92, 0)
+ QEXPECT_FAIL("", "Requires new API from frameworks", Abort);
+#endif
QVERIFY(!itemsInsertedSpy.wait(5000));
QCOMPARE(itemsInModel(), {"a"});
- m_model->setExpanded(0, true);;
+ m_model->setExpanded(0, true);
+ ;
QTRY_COMPARE(itemsInModel(), QStringList({"a", "b", "1", "2"}));
QCOMPARE(m_model->expandedParentsCount(0), 0); // a
QCOMPARE(m_model->expandedParentsCount(1), 1); // a/b
QCOMPARE(m_model->expandedParentsCount(2), 2); // a/b/1
- QCOMPARE(m_model->expandedParentsCount(3), 2) ;// a/b/2
-
+ QCOMPARE(m_model->expandedParentsCount(3), 2); // a/b/2
}
void KFileItemModelTest::testCurrentDirRemoved()
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-#include "kitemviews/kitemlistcontainer.h"
+#include "kitemviews/kitemlistcontroller.h"
#include "kitemviews/kfileitemlistview.h"
#include "kitemviews/kfileitemmodel.h"
-#include "kitemviews/kitemlistcontroller.h"
+#include "kitemviews/kitemlistcontainer.h"
#include "kitemviews/kitemlistselectionmanager.h"
#include "kitemviews/private/kitemlistviewlayouter.h"
#include "testdir.h"
-#include <QTest>
#include <QGraphicsSceneMouseEvent>
-#include <QSignalSpy>
#include <QProxyStyle>
+#include <QSignalSpy>
#include <QStandardPaths>
+#include <QTest>
/**
* \class KItemListControllerTestStyle is a proxy style for testing the
{
Q_OBJECT
public:
- KItemListControllerTestStyle(QStyle* style) :
- QProxyStyle(style),
- m_activateItemOnSingleClick((bool)style->styleHint(SH_ItemView_ActivateItemOnSingleClick))
+ KItemListControllerTestStyle(QStyle *style)
+ : QProxyStyle(style)
+ , m_activateItemOnSingleClick((bool)style->styleHint(SH_ItemView_ActivateItemOnSingleClick))
{
}
return m_activateItemOnSingleClick;
}
- int styleHint(StyleHint hint,
- const QStyleOption* option = nullptr,
- const QWidget* widget = nullptr,
- QStyleHintReturn* returnData = nullptr) const override
+ int styleHint(StyleHint hint, const QStyleOption *option = nullptr, const QWidget *widget = nullptr, QStyleHintReturn *returnData = nullptr) const override
{
switch (hint) {
case QStyle::SH_ItemView_ActivateItemOnSingleClick:
void adjustGeometryForColumnCount(int count);
private:
- KFileItemListView* m_view;
- KItemListController* m_controller;
- KItemListSelectionManager* m_selectionManager;
- KFileItemModel* m_model;
- TestDir* m_testDir;
- KItemListContainer* m_container;
- KItemListControllerTestStyle* m_testStyle;
+ KFileItemListView *m_view;
+ KItemListController *m_controller;
+ KItemListSelectionManager *m_selectionManager;
+ KFileItemModel *m_model;
+ TestDir *m_testDir;
+ KItemListContainer *m_container;
+ KItemListControllerTestStyle *m_testStyle;
};
/**
m_view->setStyle(m_testStyle);
QStringList files;
- files
- << "a1" << "a2" << "a3"
- << "b1"
- << "c1" << "c2" << "c3" << "c4" << "c5"
- << "d1" << "d2" << "d3" << "d4"
- << "e" << "e 2" << "e 3" << "e 4" << "e 5" << "e 6" << "e 7";
+ files << "a1"
+ << "a2"
+ << "a3"
+ << "b1"
+ << "c1"
+ << "c2"
+ << "c3"
+ << "c4"
+ << "c5"
+ << "d1"
+ << "d2"
+ << "d3"
+ << "d4"
+ << "e"
+ << "e 2"
+ << "e 3"
+ << "e 4"
+ << "e 5"
+ << "e 6"
+ << "e 7";
m_testDir->createFiles(files);
m_model->loadDirectory(m_testDir->url());
* including the key and the keyboard modifiers.
*/
struct KeyPress {
-
- KeyPress(Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier) :
- m_key(key),
- m_modifier(modifier)
- {}
+ KeyPress(Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier)
+ : m_key(key)
+ , m_modifier(modifier)
+ {
+ }
Qt::Key m_key;
Qt::KeyboardModifiers m_modifier;
* key press.
*/
struct ViewState {
-
- ViewState(int current, const KItemSet &selection, bool activated = false) :
- m_current(current),
- m_selection(selection),
- m_activated(activated)
- {}
+ ViewState(int current, const KItemSet &selection, bool activated = false)
+ : m_current(current)
+ , m_selection(selection)
+ , m_activated(activated)
+ {
+ }
int m_current;
KItemSet m_selection;
QTest::addColumn<int>("columnCount");
QTest::addColumn<KItemListController::SelectionBehavior>("selectionBehavior");
QTest::addColumn<bool>("groupingEnabled");
- QTest::addColumn<QList<QPair<KeyPress, ViewState> > >("testList");
+ QTest::addColumn<QList<QPair<KeyPress, ViewState>>>("testList");
QList<KFileItemListView::ItemLayout> layoutList;
QHash<KFileItemListView::ItemLayout, QString> layoutNames;
groupingEnabledList.append(true);
groupingEnabledNames[true] = "grouping enabled";
- for (const KFileItemListView::ItemLayout& layout : layoutList) {
+ for (const KFileItemListView::ItemLayout &layout : layoutList) {
// The following settings depend on the layout.
// Note that 'columns' are actually 'rows' in
// Compact layout.
}
for (int columnCount : qAsConst(columnCountList)) {
- for (const KItemListController::SelectionBehavior& selectionBehavior : qAsConst(selectionBehaviorList)) {
+ for (const KItemListController::SelectionBehavior &selectionBehavior : qAsConst(selectionBehaviorList)) {
for (bool groupingEnabled : qAsConst(groupingEnabledList)) {
- QList<QPair<KeyPress, ViewState> > testList;
+ QList<QPair<KeyPress, ViewState>> testList;
// First, key presses which should have the same effect
// for any layout and any number of columns.
- testList
- << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1))
- << qMakePair(KeyPress(Qt::Key_Return), ViewState(1, KItemSet() << 1, true))
- << qMakePair(KeyPress(Qt::Key_Enter), ViewState(1, KItemSet() << 1, true))
- << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2))
- << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3))
- << qMakePair(KeyPress(Qt::Key_Return), ViewState(3, KItemSet() << 2 << 3, true))
- << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 2))
- << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 2 << 3))
- << qMakePair(KeyPress(Qt::Key_Return), ViewState(4, KItemSet() << 2 << 3, true))
- << qMakePair(KeyPress(previousItemKey), ViewState(3, KItemSet() << 3))
- << qMakePair(KeyPress(Qt::Key_Home, Qt::ShiftModifier), ViewState(0, KItemSet() << 0 << 1 << 2 << 3))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3))
- << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 2 << 3))
- << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3))
- << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19))
- << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(18, KItemSet() << 18 << 19))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0))
- << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet()))
- << qMakePair(KeyPress(Qt::Key_Enter), ViewState(0, KItemSet(), true))
- << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet() << 0))
- << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet()))
- << qMakePair(KeyPress(Qt::Key_Space), ViewState(0, KItemSet())) // This used to select, but we are now using it to trigger either
- // selection mode or "QuickLook". Ctrl+Space still works for selecting as expected.
- << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13))
- << qMakePair(KeyPress(Qt::Key_Space), ViewState(14, KItemSet() << 14))
- << qMakePair(KeyPress(Qt::Key_3), ViewState(15, KItemSet() << 15))
- << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet()))
- << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13))
- << qMakePair(KeyPress(Qt::Key_E), ViewState(14, KItemSet() << 14))
- << qMakePair(KeyPress(Qt::Key_E), ViewState(15, KItemSet() << 15))
- << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet()))
- << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0))
- << qMakePair(KeyPress(Qt::Key_Escape), ViewState(0, KItemSet()));
+ testList << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1))
+ << qMakePair(KeyPress(Qt::Key_Return), ViewState(1, KItemSet() << 1, true))
+ << qMakePair(KeyPress(Qt::Key_Enter), ViewState(1, KItemSet() << 1, true))
+ << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2))
+ << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3))
+ << qMakePair(KeyPress(Qt::Key_Return), ViewState(3, KItemSet() << 2 << 3, true))
+ << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 2))
+ << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 2 << 3))
+ << qMakePair(KeyPress(Qt::Key_Return), ViewState(4, KItemSet() << 2 << 3, true))
+ << qMakePair(KeyPress(previousItemKey), ViewState(3, KItemSet() << 3))
+ << qMakePair(KeyPress(Qt::Key_Home, Qt::ShiftModifier), ViewState(0, KItemSet() << 0 << 1 << 2 << 3))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3))
+ << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 2 << 3))
+ << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(1, KItemSet() << 0 << 1 << 2 << 3))
+ << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19))
+ << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(18, KItemSet() << 18 << 19))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0))
+ << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet()))
+ << qMakePair(KeyPress(Qt::Key_Enter), ViewState(0, KItemSet(), true))
+ << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet() << 0))
+ << qMakePair(KeyPress(Qt::Key_Space, Qt::ControlModifier), ViewState(0, KItemSet()))
+ << qMakePair(KeyPress(Qt::Key_Space), ViewState(0, KItemSet())) // This used to select, but we are now using it to trigger either
+ // selection mode or "QuickLook". Ctrl+Space still works for selecting as expected.
+ << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13))
+ << qMakePair(KeyPress(Qt::Key_Space), ViewState(14, KItemSet() << 14))
+ << qMakePair(KeyPress(Qt::Key_3), ViewState(15, KItemSet() << 15))
+ << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet()))
+ << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13))
+ << qMakePair(KeyPress(Qt::Key_E), ViewState(14, KItemSet() << 14))
+ << qMakePair(KeyPress(Qt::Key_E), ViewState(15, KItemSet() << 15))
+ << qMakePair(KeyPress(Qt::Key_Escape), ViewState(15, KItemSet()))
+ << qMakePair(KeyPress(Qt::Key_E), ViewState(13, KItemSet() << 13))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0))
+ << qMakePair(KeyPress(Qt::Key_Escape), ViewState(0, KItemSet()));
// Next, we test combinations of key presses which only work for a
// particular number of columns and either enabled or disabled grouping.
// One column.
if (columnCount == 1) {
- testList
- << qMakePair(KeyPress(nextRowKey), ViewState(1, KItemSet() << 1))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 1 << 2))
- << qMakePair(KeyPress(nextRowKey, Qt::ControlModifier), ViewState(3, KItemSet() << 1 << 2))
- << qMakePair(KeyPress(previousRowKey), ViewState(2, KItemSet() << 2))
- << qMakePair(KeyPress(previousItemKey), ViewState(1, KItemSet() << 1))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
+ testList << qMakePair(KeyPress(nextRowKey), ViewState(1, KItemSet() << 1))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(2, KItemSet() << 1 << 2))
+ << qMakePair(KeyPress(nextRowKey, Qt::ControlModifier), ViewState(3, KItemSet() << 1 << 2))
+ << qMakePair(KeyPress(previousRowKey), ViewState(2, KItemSet() << 2))
+ << qMakePair(KeyPress(previousItemKey), ViewState(1, KItemSet() << 1))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
}
// Multiple columns: we test both 3 and 5 columns with grouping
// d4 e1 e2 | 12 13 14
// e3 e4 e5 | 15 16 17
// e6 e7 | 18 19
- testList
- << qMakePair(KeyPress(nextRowKey), ViewState(3, KItemSet() << 3))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 3))
- << qMakePair(KeyPress(nextRowKey), ViewState(7, KItemSet() << 7))
- << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8))
- << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(9, KItemSet() << 7 << 8 << 9))
- << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8))
- << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7))
- << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7))
- << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 5 << 6 << 7))
- << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7))
- << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7))
- << qMakePair(KeyPress(nextRowKey), ViewState(10, KItemSet() << 10))
- << qMakePair(KeyPress(nextItemKey), ViewState(11, KItemSet() << 11))
- << qMakePair(KeyPress(nextRowKey), ViewState(14, KItemSet() << 14))
- << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17))
- << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19))
- << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17))
- << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19))
- << qMakePair(KeyPress(previousRowKey), ViewState(16, KItemSet() << 16))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
+ testList << qMakePair(KeyPress(nextRowKey), ViewState(3, KItemSet() << 3))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(4, KItemSet() << 3))
+ << qMakePair(KeyPress(nextRowKey), ViewState(7, KItemSet() << 7))
+ << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8))
+ << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(9, KItemSet() << 7 << 8 << 9))
+ << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(8, KItemSet() << 7 << 8))
+ << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7))
+ << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7))
+ << qMakePair(KeyPress(previousItemKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 5 << 6 << 7))
+ << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 6 << 7))
+ << qMakePair(KeyPress(nextItemKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7))
+ << qMakePair(KeyPress(nextRowKey), ViewState(10, KItemSet() << 10))
+ << qMakePair(KeyPress(nextItemKey), ViewState(11, KItemSet() << 11))
+ << qMakePair(KeyPress(nextRowKey), ViewState(14, KItemSet() << 14))
+ << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17))
+ << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19))
+ << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17))
+ << qMakePair(KeyPress(Qt::Key_End), ViewState(19, KItemSet() << 19))
+ << qMakePair(KeyPress(previousRowKey), ViewState(16, KItemSet() << 16))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
}
if (columnCount == 5 && !groupingEnabled) {
// c2 c3 c4 c5 d1 | 5 6 7 8 9
// d2 d3 d4 e1 e2 | 10 11 12 13 14
// e3 e4 e5 e6 e7 | 15 16 17 18 19
- testList
- << qMakePair(KeyPress(nextRowKey), ViewState(5, KItemSet() << 5))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(6, KItemSet() << 5))
- << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11))
- << qMakePair(KeyPress(nextItemKey), ViewState(12, KItemSet() << 12))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(17, KItemSet() << 12 << 13 << 14 << 15 << 16 << 17))
- << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12))
- << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7 << 8 << 9 << 10 << 11 << 12))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12))
- << qMakePair(KeyPress(Qt::Key_End, Qt::ControlModifier), ViewState(19, KItemSet() << 12))
- << qMakePair(KeyPress(previousRowKey), ViewState(14, KItemSet() << 14))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
+ testList << qMakePair(KeyPress(nextRowKey), ViewState(5, KItemSet() << 5))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(6, KItemSet() << 5))
+ << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11))
+ << qMakePair(KeyPress(nextItemKey), ViewState(12, KItemSet() << 12))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(17, KItemSet() << 12 << 13 << 14 << 15 << 16 << 17))
+ << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12))
+ << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(7, KItemSet() << 7 << 8 << 9 << 10 << 11 << 12))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(12, KItemSet() << 12))
+ << qMakePair(KeyPress(Qt::Key_End, Qt::ControlModifier), ViewState(19, KItemSet() << 12))
+ << qMakePair(KeyPress(previousRowKey), ViewState(14, KItemSet() << 14))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
}
if (columnCount == 3 && groupingEnabled) {
// e1 e2 e3 | 13 14 15
// e4 e5 e6 | 16 17 18
// e7 | 19
- testList
- << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1))
- << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 2 << 3 << 4 << 5 << 6))
- << qMakePair(KeyPress(nextRowKey), ViewState(8, KItemSet() << 8))
- << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(12, KItemSet() << 11))
- << qMakePair(KeyPress(nextRowKey), ViewState(13, KItemSet() << 13))
- << qMakePair(KeyPress(nextRowKey), ViewState(16, KItemSet() << 16))
- << qMakePair(KeyPress(nextItemKey), ViewState(17, KItemSet() << 17))
- << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19))
- << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
+ testList << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1))
+ << qMakePair(KeyPress(nextItemKey), ViewState(2, KItemSet() << 2))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 2 << 3))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(6, KItemSet() << 2 << 3 << 4 << 5 << 6))
+ << qMakePair(KeyPress(nextRowKey), ViewState(8, KItemSet() << 8))
+ << qMakePair(KeyPress(nextRowKey), ViewState(11, KItemSet() << 11))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(12, KItemSet() << 11))
+ << qMakePair(KeyPress(nextRowKey), ViewState(13, KItemSet() << 13))
+ << qMakePair(KeyPress(nextRowKey), ViewState(16, KItemSet() << 16))
+ << qMakePair(KeyPress(nextItemKey), ViewState(17, KItemSet() << 17))
+ << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19))
+ << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
}
if (columnCount == 5 && groupingEnabled) {
// d1 d2 d3 d4 | 9 10 11 12
// e1 e2 e3 e4 e5 | 13 14 15 16 17
// e6 e7 | 18 19
- testList
- << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 1 << 2 << 3))
- << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 1 << 2 << 3 << 4 << 5))
- << qMakePair(KeyPress(nextItemKey), ViewState(6, KItemSet() << 6))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(7, KItemSet() << 6))
- << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(8, KItemSet() << 6))
- << qMakePair(KeyPress(nextRowKey), ViewState(12, KItemSet() << 12))
- << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17))
- << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19))
- << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17))
- << qMakePair(KeyPress(Qt::Key_End, Qt::ShiftModifier), ViewState(19, KItemSet() << 17 << 18 << 19))
- << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(14, KItemSet() << 14 << 15 << 16 << 17))
- << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
+ testList << qMakePair(KeyPress(nextItemKey), ViewState(1, KItemSet() << 1))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(3, KItemSet() << 1 << 2 << 3))
+ << qMakePair(KeyPress(nextRowKey, Qt::ShiftModifier), ViewState(5, KItemSet() << 1 << 2 << 3 << 4 << 5))
+ << qMakePair(KeyPress(nextItemKey), ViewState(6, KItemSet() << 6))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(7, KItemSet() << 6))
+ << qMakePair(KeyPress(nextItemKey, Qt::ControlModifier), ViewState(8, KItemSet() << 6))
+ << qMakePair(KeyPress(nextRowKey), ViewState(12, KItemSet() << 12))
+ << qMakePair(KeyPress(nextRowKey), ViewState(17, KItemSet() << 17))
+ << qMakePair(KeyPress(nextRowKey), ViewState(19, KItemSet() << 19))
+ << qMakePair(KeyPress(previousRowKey), ViewState(17, KItemSet() << 17))
+ << qMakePair(KeyPress(Qt::Key_End, Qt::ShiftModifier), ViewState(19, KItemSet() << 17 << 18 << 19))
+ << qMakePair(KeyPress(previousRowKey, Qt::ShiftModifier), ViewState(14, KItemSet() << 14 << 15 << 16 << 17))
+ << qMakePair(KeyPress(Qt::Key_Home), ViewState(0, KItemSet() << 0));
}
- const QString testName =
- layoutNames[layout] + ", " +
- QString("%1 columns, ").arg(columnCount) +
- selectionBehaviorNames[selectionBehavior] + ", " +
- groupingEnabledNames[groupingEnabled];
+ const QString testName = layoutNames[layout] + ", " + QString("%1 columns, ").arg(columnCount) + selectionBehaviorNames[selectionBehavior]
+ + ", " + groupingEnabledNames[groupingEnabled];
const QByteArray testNameAscii = testName.toLatin1();
- QTest::newRow(testNameAscii.data())
- << layout
- << scrollOrientation
- << columnCount
- << selectionBehavior
- << groupingEnabled
- << testList;
+ QTest::newRow(testNameAscii.data()) << layout << scrollOrientation << columnCount << selectionBehavior << groupingEnabled << testList;
}
}
}
QCOMPARE(m_selectionManager->currentItem(), current);
switch (selectionBehavior) {
- case KItemListController::NoSelection: QVERIFY(m_selectionManager->selectedItems().isEmpty()); break;
- case KItemListController::SingleSelection: QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << current); break;
- case KItemListController::MultiSelection: QCOMPARE(m_selectionManager->selectedItems(), selection); break;
+ case KItemListController::NoSelection:
+ QVERIFY(m_selectionManager->selectedItems().isEmpty());
+ break;
+ case KItemListController::SingleSelection:
+ QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << current);
+ break;
+ case KItemListController::MultiSelection:
+ QCOMPARE(m_selectionManager->selectedItems(), selection);
+ break;
}
if (activated) {
#include "kitemviews/private/kitemlistkeyboardsearchmanager.h"
-#include <QTest>
#include <QSignalSpy>
#include <QStandardPaths>
+#include <QTest>
class KItemListKeyboardSearchManagerTest : public QObject
{
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-#include "kitemviews/kitemmodelbase.h"
#include "kitemviews/kitemlistselectionmanager.h"
+#include "kitemviews/kitemmodelbase.h"
-#include <QTest>
#include <QSignalSpy>
#include <QStandardPaths>
+#include <QTest>
class DummyModel : public KItemModelBase
{
int m_count;
};
-DummyModel::DummyModel() :
- KItemModelBase(),
- m_count(100)
+DummyModel::DummyModel()
+ : KItemModelBase()
+ , m_count(100)
{
}
return QHash<QByteArray, QVariant>();
}
-
class KItemListSelectionManagerTest : public QObject
{
Q_OBJECT
void testAnchoredSelectionAfterMovingItems();
private:
- void verifySelectionChange(QSignalSpy& spy, const KItemSet& currentSelection, const KItemSet& previousSelection) const;
+ void verifySelectionChange(QSignalSpy &spy, const KItemSet ¤tSelection, const KItemSet &previousSelection) const;
- KItemListSelectionManager* m_selectionManager;
- DummyModel* m_model;
+ KItemListSelectionManager *m_selectionManager;
+ DummyModel *m_model;
};
void KItemListSelectionManagerTest::initTestCase()
QVERIFY(m_selectionManager->hasSelection());
// Inserting items should update current item and anchor item.
- m_selectionManager->itemsInserted(KItemRangeList() <<
- KItemRange(0, 1) <<
- KItemRange(2, 2) <<
- KItemRange(6, 3));
+ m_selectionManager->itemsInserted(KItemRangeList() << KItemRange(0, 1) << KItemRange(2, 2) << KItemRange(6, 3));
QCOMPARE(m_selectionManager->currentItem(), 5);
QCOMPARE(spyCurrent.count(), 1);
QVERIFY(m_selectionManager->hasSelection());
// Removing items should update current item and anchor item.
- m_selectionManager->itemsRemoved(KItemRangeList() <<
- KItemRange(0, 2) <<
- KItemRange(2, 1) <<
- KItemRange(9, 2));
+ m_selectionManager->itemsRemoved(KItemRangeList() << KItemRange(0, 2) << KItemRange(2, 1) << KItemRange(9, 2));
QCOMPARE(m_selectionManager->currentItem(), 2);
QCOMPARE(spyCurrent.count(), 1);
QVERIFY(selectedItems.contains(17));
// Insert 3 items between the selections
- m_selectionManager->itemsInserted(KItemRangeList() <<
- KItemRange(15, 1) <<
- KItemRange(16, 1) <<
- KItemRange(17, 1));
+ m_selectionManager->itemsInserted(KItemRangeList() << KItemRange(15, 1) << KItemRange(16, 1) << KItemRange(17, 1));
selectedItems = m_selectionManager->selectedItems();
QCOMPARE(selectedItems.count(), 3);
QVERIFY(selectedItems.contains(16));
}
// Remove the items 6 , 8 and 10
- m_selectionManager->itemsRemoved(KItemRangeList() <<
- KItemRange(6, 1) <<
- KItemRange(8, 1) <<
- KItemRange(10, 1));
+ m_selectionManager->itemsRemoved(KItemRangeList() << KItemRange(6, 1) << KItemRange(8, 1) << KItemRange(10, 1));
selectedItems = m_selectionManager->selectedItems();
QCOMPARE(selectedItems.count(), 3);
QVERIFY(selectedItems.contains(5));
QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << 5 << 6 << 7 << 9 << 10);
}
-namespace {
- enum ChangeType {
- NoChange,
- InsertItems,
- RemoveItems,
- MoveItems,
- EndAnchoredSelection,
- SetSelected
- };
+namespace
+{
+enum ChangeType { NoChange, InsertItems, RemoveItems, MoveItems, EndAnchoredSelection, SetSelected };
}
Q_DECLARE_METATYPE(KItemSet)
QTest::addColumn<int>("current");
QTest::addColumn<KItemSet>("expectedSelection");
QTest::addColumn<ChangeType>("changeType");
- QTest::addColumn<QList<QVariant> >("data");
+ QTest::addColumn<QList<QVariant>>("data");
QTest::addColumn<KItemSet>("finalSelection");
- QTest::newRow("No change")
- << (KItemSet() << 5 << 6)
- << 2 << 3
- << (KItemSet() << 2 << 3 << 5 << 6)
- << NoChange
- << QList<QVariant>{}
- << (KItemSet() << 2 << 3 << 5 << 6);
-
- QTest::newRow("Insert Items")
- << (KItemSet() << 5 << 6)
- << 2 << 3
- << (KItemSet() << 2 << 3 << 5 << 6)
- << InsertItems
- << QList<QVariant>{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(5, 2) << KItemRange(10, 5))}
- << (KItemSet() << 3 << 4 << 8 << 9);
-
- QTest::newRow("Remove Items")
- << (KItemSet() << 5 << 6)
- << 2 << 3
- << (KItemSet() << 2 << 3 << 5 << 6)
- << RemoveItems
- << QList<QVariant>{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(3, 1) << KItemRange(10, 5))}
- << (KItemSet() << 1 << 2 << 3 << 4);
-
- QTest::newRow("Empty Anchored Selection")
- << KItemSet()
- << 2 << 2
- << KItemSet()
- << EndAnchoredSelection
- << QList<QVariant>{}
- << KItemSet();
-
- QTest::newRow("Toggle selection")
- << (KItemSet() << 1 << 3 << 4)
- << 6 << 8
- << (KItemSet() << 1 << 3 << 4 << 6 << 7 << 8)
- << SetSelected
- << QList<QVariant>{0, 10, QVariant::fromValue(KItemListSelectionManager::Toggle)}
- << (KItemSet() << 0 << 2 << 5 << 9);
+ QTest::newRow("No change") << (KItemSet() << 5 << 6) << 2 << 3 << (KItemSet() << 2 << 3 << 5 << 6) << NoChange << QList<QVariant>{}
+ << (KItemSet() << 2 << 3 << 5 << 6);
+
+ QTest::newRow("Insert Items") << (KItemSet() << 5 << 6) << 2 << 3 << (KItemSet() << 2 << 3 << 5 << 6) << InsertItems
+ << QList<QVariant>{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(5, 2) << KItemRange(10, 5))}
+ << (KItemSet() << 3 << 4 << 8 << 9);
+
+ QTest::newRow("Remove Items") << (KItemSet() << 5 << 6) << 2 << 3 << (KItemSet() << 2 << 3 << 5 << 6) << RemoveItems
+ << QList<QVariant>{QVariant::fromValue(KItemRangeList() << KItemRange(1, 1) << KItemRange(3, 1) << KItemRange(10, 5))}
+ << (KItemSet() << 1 << 2 << 3 << 4);
+
+ QTest::newRow("Empty Anchored Selection") << KItemSet() << 2 << 2 << KItemSet() << EndAnchoredSelection << QList<QVariant>{} << KItemSet();
+
+ QTest::newRow("Toggle selection") << (KItemSet() << 1 << 3 << 4) << 6 << 8 << (KItemSet() << 1 << 3 << 4 << 6 << 7 << 8) << SetSelected
+ << QList<QVariant>{0, 10, QVariant::fromValue(KItemListSelectionManager::Toggle)} << (KItemSet() << 0 << 2 << 5 << 9);
// Swap items 2, 3 and 4, 5
- QTest::newRow("Move items")
- << (KItemSet() << 0 << 1 << 2 << 3)
- << -1 << -1
- << (KItemSet() << 0 << 1 << 2 << 3)
- << MoveItems
- << QList<QVariant>{QVariant::fromValue(KItemRange(2, 4)),
- QVariant::fromValue(QList<int>{4, 5, 2, 3})}
- << (KItemSet() << 0 << 1 << 4 << 5);
+ QTest::newRow("Move items") << (KItemSet() << 0 << 1 << 2 << 3) << -1 << -1 << (KItemSet() << 0 << 1 << 2 << 3) << MoveItems
+ << QList<QVariant>{QVariant::fromValue(KItemRange(2, 4)), QVariant::fromValue(QList<int>{4, 5, 2, 3})}
+ << (KItemSet() << 0 << 1 << 4 << 5);
QTest::newRow("Move items with active anchored selection")
- << KItemSet()
- << 0 << 3
- << (KItemSet() << 0 << 1 << 2 << 3)
- << MoveItems
- << QList<QVariant>{QVariant::fromValue(KItemRange(2, 4)),
- QVariant::fromValue(QList<int>{4, 5, 2, 3})}
- << (KItemSet() << 0 << 1 << 4 << 5);
+ << KItemSet() << 0 << 3 << (KItemSet() << 0 << 1 << 2 << 3) << MoveItems
+ << QList<QVariant>{QVariant::fromValue(KItemRange(2, 4)), QVariant::fromValue(QList<int>{4, 5, 2, 3})} << (KItemSet() << 0 << 1 << 4 << 5);
// Revert sort order
- QTest::newRow("Revert sort order")
- << (KItemSet() << 0 << 1)
- << 3 << 4
- << (KItemSet() << 0 << 1 << 3 << 4)
- << MoveItems
- << QList<QVariant>{QVariant::fromValue(KItemRange(0, 10)),
- QVariant::fromValue(QList<int>{9, 8, 7, 6, 5, 4, 3, 2, 1, 0})}
- << (KItemSet() << 5 << 6 << 8 << 9);
+ QTest::newRow("Revert sort order") << (KItemSet() << 0 << 1) << 3 << 4 << (KItemSet() << 0 << 1 << 3 << 4) << MoveItems
+ << QList<QVariant>{QVariant::fromValue(KItemRange(0, 10)), QVariant::fromValue(QList<int>{9, 8, 7, 6, 5, 4, 3, 2, 1, 0})}
+ << (KItemSet() << 5 << 6 << 8 << 9);
}
void KItemListSelectionManagerTest::testChangeSelection()
m_selectionManager->itemsRemoved(data.at(0).value<KItemRangeList>());
break;
case MoveItems:
- m_selectionManager->itemsMoved(data.at(0).value<KItemRange>(),
- data.at(1).value<QList<int>>());
+ m_selectionManager->itemsMoved(data.at(0).value<KItemRange>(), data.at(1).value<QList<int>>());
break;
case EndAnchoredSelection:
m_selectionManager->endAnchoredSelection();
QTest::addColumn<int>("removeCount");
QTest::addColumn<int>("newCurrentItemIndex");
- QTest::newRow("Remove before") << 50 << 0 << 10 << 40;
- QTest::newRow("Remove after") << 50 << 51 << 10 << 50;
- QTest::newRow("Remove exactly current item") << 50 << 50 << 1 << 50;
- QTest::newRow("Remove around current item") << 50 << 45 << 10 << 45;
- QTest::newRow("Remove all except one item") << 50 << 1 << 99 << 0;
+ QTest::newRow("Remove before") << 50 << 0 << 10 << 40;
+ QTest::newRow("Remove after") << 50 << 51 << 10 << 50;
+ QTest::newRow("Remove exactly current item") << 50 << 50 << 1 << 50;
+ QTest::newRow("Remove around current item") << 50 << 45 << 10 << 45;
+ QTest::newRow("Remove all except one item") << 50 << 1 << 99 << 0;
}
void KItemListSelectionManagerTest::testDeleteCurrentItem()
QCOMPARE(m_selectionManager->selectedItems(), KItemSet() << 1 << 2);
}
-void KItemListSelectionManagerTest::verifySelectionChange(QSignalSpy& spy,
- const KItemSet& currentSelection,
- const KItemSet& previousSelection) const
+void KItemListSelectionManagerTest::verifySelectionChange(QSignalSpy &spy, const KItemSet ¤tSelection, const KItemSet &previousSelection) const
{
QCOMPARE(m_selectionManager->selectedItems(), currentSelection);
QCOMPARE(m_selectionManager->hasSelection(), !currentSelection.isEmpty());
for (int index = 0; index < m_selectionManager->model()->count(); ++index) {
if (currentSelection.contains(index)) {
QVERIFY(m_selectionManager->isSelected(index));
- }
- else {
+ } else {
QVERIFY(!m_selectionManager->isSelected(index));
}
}
if (currentSelection == previousSelection) {
QCOMPARE(spy.count(), 0);
- }
- else {
+ } else {
QCOMPARE(spy.count(), 1);
QList<QVariant> arguments = spy.takeFirst();
QCOMPARE(qvariant_cast<KItemSet>(arguments.at(0)), currentSelection);
void KItemRangeTest::testFromSortedContainer_data()
{
- QTest::addColumn<QVector<int> >("sortedNumbers");
+ QTest::addColumn<QVector<int>>("sortedNumbers");
QTest::addColumn<KItemRangeList>("expected");
QTest::newRow("empty") << QVector<int>{} << KItemRangeList();
/**
* Converts a KItemRangeList to a KItemSet.
*/
-KItemSet KItemRangeList2KItemSet(const KItemRangeList& itemRanges)
+KItemSet KItemRangeList2KItemSet(const KItemRangeList &itemRanges)
{
KItemSet result;
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
for (int i = range.index; i < range.index + range.count; ++i) {
result.insert(i);
}
/**
* Converts a KItemRangeList to a QSet<int>.
*/
-QSet<int> KItemRangeList2QSet(const KItemRangeList& itemRanges)
+QSet<int> KItemRangeList2QSet(const KItemRangeList &itemRanges)
{
QSet<int> result;
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
for (int i = range.index; i < range.index + range.count; ++i) {
result.insert(i);
}
/**
* Converts a KItemRangeList to a QVector<int>.
*/
-QVector<int> KItemRangeList2QVector(const KItemRangeList& itemRanges)
+QVector<int> KItemRangeList2QVector(const KItemRangeList &itemRanges)
{
QVector<int> result;
- for (const KItemRange& range : itemRanges) {
+ for (const KItemRange &range : itemRanges) {
for (int i = range.index; i < range.index + range.count; ++i) {
result.append(i);
}
/**
* Converts a KItemSet to a QSet<int>.
*/
-static QSet<int> KItemSet2QSet(const KItemSet& itemSet)
+static QSet<int> KItemSet2QSet(const KItemSet &itemSet)
{
QSet<int> result;
for (int i : itemSet) {
return result;
}
-
/**
* The main test class.
*/
void testSymmetricDifference();
private:
- QHash<const char*, KItemRangeList> m_testCases;
+ QHash<const char *, KItemRangeList> m_testCases;
};
void KItemSetTest::initTestCase()
m_testCases.insert("[1, 2] [4, 5]", KItemRangeList() << KItemRange(1, 2) << KItemRange(4, 2));
m_testCases.insert("[1, 5]", KItemRangeList() << KItemRange(1, 5));
m_testCases.insert("[1, 2] [4, 5] [7] [9, 10] [13] [20, 25] [30]",
- KItemRangeList() << KItemRange(1, 2) << KItemRange(4, 2) << KItemRange(7, 1) << KItemRange(9, 2) << KItemRange(20, 6) << KItemRange(30, 1));
+ KItemRangeList() << KItemRange(1, 2) << KItemRange(4, 2) << KItemRange(7, 1) << KItemRange(9, 2) << KItemRange(20, 6)
+ << KItemRange(30, 1));
m_testCases.insert("[-10, -1]", KItemRangeList() << KItemRange(-10, 10));
m_testCases.insert("[-10, 0]", KItemRangeList() << KItemRange(-10, 11));
m_testCases.insert("[-10, 1]", KItemRangeList() << KItemRange(-10, 12));
{
QTest::addColumn<KItemRangeList>("itemRanges");
- QHash<const char*, KItemRangeList>::const_iterator it = m_testCases.constBegin();
- const QHash<const char*, KItemRangeList>::const_iterator end = m_testCases.constEnd();
+ QHash<const char *, KItemRangeList>::const_iterator it = m_testCases.constBegin();
+ const QHash<const char *, KItemRangeList>::const_iterator end = m_testCases.constEnd();
while (it != end) {
QTest::newRow(it.key()) << it.value();
{
QTest::addColumn<KItemRangeList>("itemRanges");
- QHash<const char*, KItemRangeList>::const_iterator it = m_testCases.constBegin();
- const QHash<const char*, KItemRangeList>::const_iterator end = m_testCases.constEnd();
+ QHash<const char *, KItemRangeList>::const_iterator it = m_testCases.constBegin();
+ const QHash<const char *, KItemRangeList>::const_iterator end = m_testCases.constEnd();
while (it != end) {
QTest::newRow(it.key()) << it.value();
{
QTest::addColumn<KItemRangeList>("itemRanges");
- QHash<const char*, KItemRangeList>::const_iterator it = m_testCases.constBegin();
- const QHash<const char*, KItemRangeList>::const_iterator end = m_testCases.constEnd();
+ QHash<const char *, KItemRangeList>::const_iterator it = m_testCases.constBegin();
+ const QHash<const char *, KItemRangeList>::const_iterator end = m_testCases.constEnd();
while (it != end) {
QTest::newRow(it.key()) << it.value();
{
QTest::addColumn<KItemRangeList>("itemRanges");
- QHash<const char*, KItemRangeList>::const_iterator it = m_testCases.constBegin();
- const QHash<const char*, KItemRangeList>::const_iterator end = m_testCases.constEnd();
+ QHash<const char *, KItemRangeList>::const_iterator it = m_testCases.constBegin();
+ const QHash<const char *, KItemRangeList>::const_iterator end = m_testCases.constEnd();
while (it != end) {
QTest::newRow(it.key()) << it.value();
// Test insert(int), remove(int), and erase(KItemSet::iterator)
// for items between min - 2 and max + 2.
for (int i = min - 2; i <= max + 2; ++i) {
-
// Test insert(int).
{
KItemSet tmp(itemSet);
QTest::addColumn<KItemRangeList>("itemRanges1");
QTest::addColumn<KItemRangeList>("itemRanges2");
- QHash<const char*, KItemRangeList>::const_iterator it1 = m_testCases.constBegin();
- const QHash<const char*, KItemRangeList>::const_iterator end = m_testCases.constEnd();
+ QHash<const char *, KItemRangeList>::const_iterator it1 = m_testCases.constBegin();
+ const QHash<const char *, KItemRangeList>::const_iterator end = m_testCases.constEnd();
while (it1 != end) {
- QHash<const char*, KItemRangeList>::const_iterator it2 = m_testCases.constBegin();
+ QHash<const char *, KItemRangeList>::const_iterator it2 = m_testCases.constBegin();
while (it2 != end) {
QByteArray name = it1.key() + QByteArray(" + ") + it2.key();
QTest::addColumn<KItemRangeList>("itemRanges1");
QTest::addColumn<KItemRangeList>("itemRanges2");
- QHash<const char*, KItemRangeList>::const_iterator it1 = m_testCases.constBegin();
- const QHash<const char*, KItemRangeList>::const_iterator end = m_testCases.constEnd();
+ QHash<const char *, KItemRangeList>::const_iterator it1 = m_testCases.constBegin();
+ const QHash<const char *, KItemRangeList>::const_iterator end = m_testCases.constEnd();
while (it1 != end) {
- QHash<const char*, KItemRangeList>::const_iterator it2 = m_testCases.constBegin();
+ QHash<const char *, KItemRangeList>::const_iterator it2 = m_testCases.constBegin();
while (it2 != end) {
QByteArray name = it1.key() + QByteArray(" ^ ") + it2.key();
QCOMPARE(itemSet2 ^ symmetricDifference, itemSet1);
}
-
QTEST_GUILESS_MAIN(KItemSetTest)
#include "kitemsettest.moc"
#include <sys/utime.h>
#endif
-TestDir::TestDir(const QString& directoryPrefix) :
- QTemporaryDir(directoryPrefix)
+TestDir::TestDir(const QString &directoryPrefix)
+ : QTemporaryDir(directoryPrefix)
{
}
}
/** The following function is taken from kdelibs/kio/tests/kiotesthelper.h, copyright (C) 2006 by David Faure */
-static void setTimeStamp(const QString& path, const QDateTime& mtime)
+static void setTimeStamp(const QString &path, const QDateTime &mtime)
{
#ifdef Q_OS_UNIX
struct utimbuf utbuf;
#endif
}
-void TestDir::createFile(const QString& path, const QByteArray& data, const QDateTime& time)
+void TestDir::createFile(const QString &path, const QByteArray &data, const QDateTime &time)
{
QString absolutePath = path;
makePathAbsoluteAndCreateParents(absolutePath);
Q_ASSERT(QFile::exists(absolutePath));
}
-void TestDir::createFiles(const QStringList& files)
+void TestDir::createFiles(const QStringList &files)
{
- for (const QString& path : files) {
+ for (const QString &path : files) {
createFile(path);
}
}
-void TestDir::createDir(const QString& path, const QDateTime& time)
+void TestDir::createDir(const QString &path, const QDateTime &time)
{
QString absolutePath = path;
makePathAbsoluteAndCreateParents(absolutePath);
Q_ASSERT(QFile::exists(absolutePath));
}
-void TestDir::removeFiles(const QStringList& files)
+void TestDir::removeFiles(const QStringList &files)
{
- for (const QString& path : files) {
+ for (const QString &path : files) {
removeFile(path);
}
}
-void TestDir::removeFile(const QString& path)
+void TestDir::removeFile(const QString &path)
{
QString absolutePath = path;
QFileInfo fileInfo(absolutePath);
QFile::remove(absolutePath);
}
-void TestDir::removeDir(const QString& path)
+void TestDir::removeDir(const QString &path)
{
QString absolutePath = path;
QFileInfo fileInfo(absolutePath);
dirToRemove.removeRecursively();
}
-void TestDir::makePathAbsoluteAndCreateParents(QString& path)
+void TestDir::makePathAbsoluteAndCreateParents(QString &path)
{
QFileInfo fileInfo(path);
if (!fileInfo.isAbsolute()) {
#ifndef TESTDIR_H
#define TESTDIR_H
-#include <QUrl>
-#include <QTemporaryDir>
#include <QDateTime>
+#include <QTemporaryDir>
+#include <QUrl>
/**
* TestDir provides a temporary directory. In addition to QTemporaryDir, it has
*/
class TestDir : public QTemporaryDir
{
-
public:
- TestDir(const QString& directoryPrefix = QString());
+ TestDir(const QString &directoryPrefix = QString());
virtual ~TestDir();
QUrl url() const;
* The paths may be absolute or relative to the test directory. Any missing parent
* directories will be created automatically.
*/
- void createFile(const QString& path,
- const QByteArray& data = QByteArray("test"),
- const QDateTime& time = QDateTime());
- void createFiles(const QStringList& files);
- void createDir(const QString& path, const QDateTime& time = QDateTime());
+ void createFile(const QString &path, const QByteArray &data = QByteArray("test"), const QDateTime &time = QDateTime());
+ void createFiles(const QStringList &files);
+ void createDir(const QString &path, const QDateTime &time = QDateTime());
- void removeFile(const QString& path);
- void removeFiles(const QStringList& files);
- void removeDir(const QString& path);
+ void removeFile(const QString &path);
+ void removeFiles(const QStringList &files);
+ void removeDir(const QString &path);
private:
- void makePathAbsoluteAndCreateParents(QString& path);
-
+ void makePathAbsoluteAndCreateParents(QString &path);
};
#endif
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-#include "dolphin_generalsettings.h"
#include "views/viewproperties.h"
+#include "dolphin_generalsettings.h"
#include "testdir.h"
#include <QTest>
private:
bool m_globalViewProps;
- TestDir* m_testDir;
+ TestDir *m_testDir;
};
void ViewPropertiesTest::initTestCase()
#include "dolphintrash.h"
-#include <QList>
-#include <KNotification>
#include <KConfig>
#include <KConfigGroup>
#include <KLocalizedString>
+#include <KNotification>
+#include <QList>
#include <kio_version.h>
#if KIO_VERSION >= QT_VERSION_CHECK(5, 100, 0)
uiDelegate.setWindow(window);
bool confirmed = uiDelegate.askDeleteConfirmation(QList<QUrl>(), KIO::JobUiDelegate::EmptyTrash, KIO::JobUiDelegate::DefaultConfirmation);
if (confirmed) {
- KIO::Job* job = KIO::emptyTrash();
+ KIO::Job *job = KIO::emptyTrash();
KJobWidgets::setWindow(job, window);
job->uiDelegate()->setAutoErrorHandlingEnabled(true);
QObject::connect(job, &KIO::Job::result, notifyEmptied);
KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig);
return (trashConfig.group("Status").readEntry("Empty", true));
}
-
#include <QWidget>
-#include <KIO/EmptyTrashJob>
#include <KDirLister>
+#include <KIO/EmptyTrashJob>
-class Trash: public QObject
+class Trash : public QObject
{
Q_OBJECT
public:
// delete copy and move constructors and assign operators
- Trash(Trash const&) = delete;
- Trash(Trash&&) = delete;
- Trash& operator=(Trash const&) = delete;
- Trash& operator=(Trash &&) = delete;
+ Trash(Trash const &) = delete;
+ Trash(Trash &&) = delete;
+ Trash &operator=(Trash const &) = delete;
+ Trash &operator=(Trash &&) = delete;
- static Trash& instance();
+ static Trash &instance();
static void empty(QWidget *window);
static bool isEmpty();
public:
static DolphinFeedbackProvider *instance();
- DolphinFeedbackProvider(const DolphinFeedbackProvider&) = delete;
- DolphinFeedbackProvider(DolphinFeedbackProvider&&) = delete;
- DolphinFeedbackProvider& operator=(const DolphinFeedbackProvider&) = delete;
- DolphinFeedbackProvider& operator=(DolphinFeedbackProvider&&) = delete;
+ DolphinFeedbackProvider(const DolphinFeedbackProvider &) = delete;
+ DolphinFeedbackProvider(DolphinFeedbackProvider &&) = delete;
+ DolphinFeedbackProvider &operator=(const DolphinFeedbackProvider &) = delete;
+ DolphinFeedbackProvider &operator=(DolphinFeedbackProvider &&) = delete;
private:
DolphinFeedbackProvider();
PlacesDataSource::PlacesDataSource()
: KUserFeedback::AbstractDataSource(QStringLiteral("places"), KUserFeedback::Provider::DetailedSystemInformation)
-{}
+{
+}
QString PlacesDataSource::name() const
{
QString name() const override;
QString description() const override;
QVariant data() override;
-
};
#endif // PLACESDATASOURCE_H
*/
#include "settingsdatasource.h"
-#include "dolphinmainwindow.h"
#include "dolphin_generalsettings.h"
+#include "dolphinmainwindow.h"
#include <KLocalizedString>
#include <KUserFeedback/Provider>
SettingsDataSource::SettingsDataSource()
: KUserFeedback::AbstractDataSource(QStringLiteral("settings"), KUserFeedback::Provider::DetailedSystemInformation)
-{}
+{
+}
QString SettingsDataSource::name() const
{
#include <KIconLoader>
-DolphinFileItemListWidget::DolphinFileItemListWidget(KItemListWidgetInformant* informant,
- QGraphicsItem* parent) :
- KFileItemListWidget(informant, parent)
+DolphinFileItemListWidget::DolphinFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent)
+ : KFileItemListWidget(informant, parent)
{
}
// as tint colors and are mixed with the current set text color. The tint colors
// have been optimized for the base colors of the corresponding Oxygen emblems.
switch (version) {
- case KVersionControlPlugin::UpdateRequiredVersion: tintColor = Qt::yellow; break;
- case KVersionControlPlugin::LocallyModifiedUnstagedVersion: tintColor = Qt::green; break;
- case KVersionControlPlugin::LocallyModifiedVersion: tintColor = Qt::green; break;
- case KVersionControlPlugin::AddedVersion: tintColor = Qt::green; break;
- case KVersionControlPlugin::RemovedVersion: tintColor = Qt::darkRed; break;
- case KVersionControlPlugin::ConflictingVersion: tintColor = Qt::red; break;
- case KVersionControlPlugin::IgnoredVersion: tintColor = Qt::white; break;
- case KVersionControlPlugin::MissingVersion: tintColor = Qt::red; break;
+ case KVersionControlPlugin::UpdateRequiredVersion:
+ tintColor = Qt::yellow;
+ break;
+ case KVersionControlPlugin::LocallyModifiedUnstagedVersion:
+ tintColor = Qt::green;
+ break;
+ case KVersionControlPlugin::LocallyModifiedVersion:
+ tintColor = Qt::green;
+ break;
+ case KVersionControlPlugin::AddedVersion:
+ tintColor = Qt::green;
+ break;
+ case KVersionControlPlugin::RemovedVersion:
+ tintColor = Qt::darkRed;
+ break;
+ case KVersionControlPlugin::ConflictingVersion:
+ tintColor = Qt::red;
+ break;
+ case KVersionControlPlugin::IgnoredVersion:
+ tintColor = Qt::white;
+ break;
+ case KVersionControlPlugin::MissingVersion:
+ tintColor = Qt::red;
+ break;
case KVersionControlPlugin::NormalVersion:
case KVersionControlPlugin::UnversionedVersion:
default:
break;
}
- color = QColor((tintColor.red() + textColor.red()) / 2,
+ color = QColor((tintColor.red() + textColor.red()) / 2,
(tintColor.green() + textColor.green()) / 2,
- (tintColor.blue() + textColor.blue()) / 2,
+ (tintColor.blue() + textColor.blue()) / 2,
(tintColor.alpha() + textColor.alpha()) / 2);
setOverlay(overlayForState(version, styleOption().iconSize));
return QIcon::fromTheme(iconName).pixmap(QSize(overlayHeight, overlayHeight));
}
-
Q_OBJECT
public:
- DolphinFileItemListWidget(KItemListWidgetInformant* informant, QGraphicsItem* parent);
+ DolphinFileItemListWidget(KItemListWidgetInformant *informant, QGraphicsItem *parent);
~DolphinFileItemListWidget() override;
protected:
private:
static QPixmap overlayForState(KVersionControlPlugin::ItemVersion version, int size);
-
};
#endif
-
-
#include <KIO/PreviewJob>
#include <QtMath>
-
-DolphinItemListView::DolphinItemListView(QGraphicsWidget* parent) :
- KFileItemListView(parent),
- m_zoomLevel(0)
+DolphinItemListView::DolphinItemListView(QGraphicsWidget *parent)
+ : KFileItemListView(parent)
+ , m_zoomLevel(0)
{
updateFont();
updateGridSize();
DetailsModeSettings::self()->save();
}
-KItemListWidgetCreatorBase* DolphinItemListView::defaultWidgetCreator() const
+KItemListWidgetCreatorBase *DolphinItemListView::defaultWidgetCreator() const
{
return new KItemListWidgetCreator<DolphinFileItemListWidget>();
}
updateGridSize();
}
-void DolphinItemListView::onVisibleRolesChanged(const QList<QByteArray>& current,
- const QList<QByteArray>& previous)
+void DolphinItemListView::onVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous)
{
KFileItemListView::onVisibleRolesChanged(current, previous);
updateGridSize();
switch (itemLayout()) {
case KFileItemListView::IconsLayout: {
-
// an exponential factor based on zoom, 0 -> 1, 4 -> 1.36 8 -> ~1.85, 16 -> 3.4
auto zoomFactor = qExp(m_zoomLevel / 13.0);
// 9 is the average char width for 10pt Noto Sans, making fontFactor =1
Q_OBJECT
public:
- explicit DolphinItemListView(QGraphicsWidget* parent = nullptr);
+ explicit DolphinItemListView(QGraphicsWidget *parent = nullptr);
~DolphinItemListView() override;
void setZoomLevel(int level);
int zoomLevel() const;
- enum SelectionTogglesEnabled {
- True,
- False,
- FollowSetting
- };
+ enum SelectionTogglesEnabled { True, False, FollowSetting };
/**
* Sets whether the items in this view should show a small selection toggle area on mouse hover.
* The default for this view is to follow the "showSelectionToggle" setting but this method can
void writeSettings();
protected:
- KItemListWidgetCreatorBase* defaultWidgetCreator() const override;
+ KItemListWidgetCreatorBase *defaultWidgetCreator() const override;
/** Overwriting in the Dolphin-specific class because we want this to be user-configurable.
* @see KStandardItemListView::itemLayoutHighlightEntireRow */
bool itemLayoutHighlightEntireRow(ItemLayout layout) const override;
bool itemLayoutSupportsItemExpanding(ItemLayout layout) const override;
void onItemLayoutChanged(ItemLayout current, ItemLayout previous) override;
void onPreviewsShownChanged(bool shown) override;
- void onVisibleRolesChanged(const QList<QByteArray>& current,
- const QList<QByteArray>& previous) override;
+ void onVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous) override;
void updateFont() override;
};
Q_GLOBAL_STATIC(DolphinNewFileMenuObserverSingleton, s_DolphinNewFileMenuObserver)
-DolphinNewFileMenuObserver& DolphinNewFileMenuObserver::instance()
+DolphinNewFileMenuObserver &DolphinNewFileMenuObserver::instance()
{
return s_DolphinNewFileMenuObserver->instance;
}
-void DolphinNewFileMenuObserver::attach(const DolphinNewFileMenu* menu)
+void DolphinNewFileMenuObserver::attach(const DolphinNewFileMenu *menu)
{
- connect(menu, &DolphinNewFileMenu::fileCreated,
- this, &DolphinNewFileMenuObserver::itemCreated);
- connect(menu, &DolphinNewFileMenu::directoryCreated,
- this, &DolphinNewFileMenuObserver::itemCreated);
- connect(menu, &DolphinNewFileMenu::errorMessage,
- this, &DolphinNewFileMenuObserver::errorMessage);
+ connect(menu, &DolphinNewFileMenu::fileCreated, this, &DolphinNewFileMenuObserver::itemCreated);
+ connect(menu, &DolphinNewFileMenu::directoryCreated, this, &DolphinNewFileMenuObserver::itemCreated);
+ connect(menu, &DolphinNewFileMenu::errorMessage, this, &DolphinNewFileMenuObserver::errorMessage);
}
-void DolphinNewFileMenuObserver::detach(const DolphinNewFileMenu* menu)
+void DolphinNewFileMenuObserver::detach(const DolphinNewFileMenu *menu)
{
- disconnect(menu, &DolphinNewFileMenu::fileCreated,
- this, &DolphinNewFileMenuObserver::itemCreated);
- disconnect(menu, &DolphinNewFileMenu::directoryCreated,
- this, &DolphinNewFileMenuObserver::itemCreated);
- disconnect(menu, &DolphinNewFileMenu::errorMessage,
- this, &DolphinNewFileMenuObserver::errorMessage);
+ disconnect(menu, &DolphinNewFileMenu::fileCreated, this, &DolphinNewFileMenuObserver::itemCreated);
+ disconnect(menu, &DolphinNewFileMenu::directoryCreated, this, &DolphinNewFileMenuObserver::itemCreated);
+ disconnect(menu, &DolphinNewFileMenu::errorMessage, this, &DolphinNewFileMenuObserver::errorMessage);
}
-DolphinNewFileMenuObserver::DolphinNewFileMenuObserver() :
- QObject(nullptr)
+DolphinNewFileMenuObserver::DolphinNewFileMenuObserver()
+ : QObject(nullptr)
{
}
DolphinNewFileMenuObserver::~DolphinNewFileMenuObserver()
{
}
-
Q_OBJECT
public:
- static DolphinNewFileMenuObserver& instance();
- void attach(const DolphinNewFileMenu* menu);
- void detach(const DolphinNewFileMenu* menu);
+ static DolphinNewFileMenuObserver &instance();
+ void attach(const DolphinNewFileMenu *menu);
+ void detach(const DolphinNewFileMenu *menu);
Q_SIGNALS:
- void itemCreated(const QUrl& url);
- void errorMessage(const QString& error);
+ void itemCreated(const QUrl &url);
+ void errorMessage(const QString &error);
private:
DolphinNewFileMenuObserver();
* SPDX-License-Identifier: GPL-2.0-or-later
*/
- /*
+/*
* This code is largely based on the kremoteencodingplugin
* SPDX-FileCopyrightText: 2003 Thiago Macieira <thiago.macieira@kdemail.net>
* Distributed under the same terms.
#include "dolphinremoteencoding.h"
-#include "dolphinviewactionhandler.h"
#include "dolphindebug.h"
+#include "dolphinviewactionhandler.h"
#include <KActionCollection>
#include <KActionMenu>
#include <QMenu>
-#define DATA_KEY QStringLiteral("Charset")
+#define DATA_KEY QStringLiteral("Charset")
-DolphinRemoteEncoding::DolphinRemoteEncoding(QObject* parent, DolphinViewActionHandler* actionHandler)
- :QObject(parent),
- m_actionHandler(actionHandler),
- m_loaded(false),
- m_idDefault(0)
+DolphinRemoteEncoding::DolphinRemoteEncoding(QObject *parent, DolphinViewActionHandler *actionHandler)
+ : QObject(parent)
+ , m_actionHandler(actionHandler)
+ , m_loaded(false)
+ , m_idDefault(0)
{
m_menu = new KActionMenu(QIcon::fromTheme(QStringLiteral("character-set")), i18n("Select Remote Charset"), this);
m_actionHandler->actionCollection()->addAction(QStringLiteral("change_remote_encoding"), m_menu);
- connect(m_menu->menu(), &QMenu::aboutToShow,
- this, &DolphinRemoteEncoding::slotAboutToShow);
+ connect(m_menu->menu(), &QMenu::aboutToShow, this, &DolphinRemoteEncoding::slotAboutToShow);
m_menu->setEnabled(false);
m_menu->setPopupMode(QToolButton::InstantPopup);
if (m_currentURL.scheme() != oldURL.scheme()) {
// This plugin works on ftp, fish, etc.
// everything whose type is T_FILESYSTEM except for local files
- if (!m_currentURL.isLocalFile() &&
- KProtocolManager::outputType(m_currentURL) == KProtocolInfo::T_FILESYSTEM) {
-
+ if (!m_currentURL.isLocalFile() && KProtocolManager::outputType(m_currentURL) == KProtocolInfo::T_FILESYSTEM) {
m_menu->setEnabled(true);
loadSettings();
} else {
void DolphinRemoteEncoding::fillMenu()
{
- QMenu* menu = m_menu->menu();
+ QMenu *menu = m_menu->menu();
menu->clear();
menu->addAction(i18n("Default"), this, SLOT(slotDefault()), 0)->setCheckable(true);
- for (int i = 0; i < m_encodingDescriptions.size();i++) {
- QAction* action = new QAction(m_encodingDescriptions.at(i), this);
+ for (int i = 0; i < m_encodingDescriptions.size(); i++) {
+ QAction *action = new QAction(m_encodingDescriptions.at(i), this);
action->setCheckable(true);
action->setData(i);
menu->addAction(action);
}
// uncheck everything
- for (int i = 0; i < m_menu->menu()->actions().count(); i++) {
+ for (int i = 0; i < m_menu->menu()->actions().count(); i++) {
m_menu->menu()->actions().at(i)->setChecked(false);
}
qCDebug(DolphinDebug) << "URL=" << m_currentURL << " charset=" << charset;
if (!isFound) {
- qCWarning(DolphinDebug) << "could not find entry for charset=" << charset ;
+ qCWarning(DolphinDebug) << "could not find entry for charset=" << charset;
} else {
m_menu->menu()->actions().at(id)->setChecked(true);
}
} else {
m_menu->menu()->actions().at(m_idDefault)->setChecked(true);
}
-
}
void DolphinRemoteEncoding::slotAboutToShow()
updateMenu();
}
-void DolphinRemoteEncoding::slotItemSelected(QAction* action)
+void DolphinRemoteEncoding::slotItemSelected(QAction *action)
{
if (action) {
int id = action->data().toInt();
partList.erase(partList.begin());
}
- for (QStringList::const_iterator it = domains.constBegin(); it != domains.constEnd();++it) {
+ for (QStringList::const_iterator it = domains.constBegin(); it != domains.constEnd(); ++it) {
qCDebug(DolphinDebug) << "Domain to remove: " << *it;
if (config.hasGroup(*it)) {
config.deleteGroup(*it);
m_actionHandler->currentView()->setUrl(m_currentURL);
m_actionHandler->currentView()->reload();
}
-
* When browsing remote url, its possible to change encoding from Tools Menu.
*/
-class DOLPHIN_EXPORT DolphinRemoteEncoding: public QObject
+class DOLPHIN_EXPORT DolphinRemoteEncoding : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- DolphinRemoteEncoding(QObject* parent, DolphinViewActionHandler* actionHandler);
- ~DolphinRemoteEncoding() override;
+ DolphinRemoteEncoding(QObject *parent, DolphinViewActionHandler *actionHandler);
+ ~DolphinRemoteEncoding() override;
public Q_SLOTS:
- void slotAboutToOpenUrl();
- void slotItemSelected(QAction* action);
- void slotReload();
- void slotDefault();
+ void slotAboutToOpenUrl();
+ void slotItemSelected(QAction *action);
+ void slotReload();
+ void slotDefault();
private Q_SLOTS:
- void slotAboutToShow();
+ void slotAboutToShow();
private:
- void updateView();
- void loadSettings();
- void fillMenu();
- void updateMenu();
-
- KActionMenu* m_menu;
- QStringList m_encodingDescriptions;
- QUrl m_currentURL;
- DolphinViewActionHandler* m_actionHandler;
-
- bool m_loaded;
- int m_idDefault;
+ void updateView();
+ void loadSettings();
+ void fillMenu();
+ void updateMenu();
+
+ KActionMenu *m_menu;
+ QStringList m_encodingDescriptions;
+ QUrl m_currentURL;
+ DolphinViewActionHandler *m_actionHandler;
+
+ bool m_loaded;
+ int m_idDefault;
};
#endif
#include "dolphinview.h"
-#include "dolphin_generalsettings.h"
#include "dolphin_detailsmodesettings.h"
+#include "dolphin_generalsettings.h"
#include "dolphinitemlistview.h"
#include "dolphinnewfilemenuobserver.h"
#include "draganddrophelper.h"
#include "kitemviews/kitemlistheader.h"
#include "kitemviews/kitemlistselectionmanager.h"
#include "kitemviews/private/kitemlistroleeditor.h"
-#include "settings/viewmodes/viewmodesettings.h"
#include "selectionmode/singleclickselectionproxystyle.h"
+#include "settings/viewmodes/viewmodesettings.h"
#include "versioncontrol/versioncontrolobserver.h"
#include "viewproperties.h"
#include "views/tooltips/tooltipmanager.h"
#include <QToolTip>
#include <QVBoxLayout>
-DolphinView::DolphinView(const QUrl& url, QWidget* parent) :
- QWidget(parent),
- m_active(true),
- m_tabsForFiles(false),
- m_assureVisibleCurrentIndex(false),
- m_isFolderWritable(true),
- m_dragging(false),
- m_url(url),
- m_viewPropertiesContext(),
- m_mode(DolphinView::IconsView),
- m_visibleRoles(),
- m_topLayout(nullptr),
- m_model(nullptr),
- m_view(nullptr),
- m_container(nullptr),
- m_toolTipManager(nullptr),
- m_selectionChangedTimer(nullptr),
- m_currentItemUrl(),
- m_scrollToCurrentItem(false),
- m_restoredContentsPosition(),
- m_selectedUrls(),
- m_clearSelectionBeforeSelectingNewItems(false),
- m_markFirstNewlySelectedItemAsCurrent(false),
- m_versionControlObserver(nullptr),
- m_twoClicksRenamingTimer(nullptr),
- m_placeholderLabel(nullptr),
- m_showLoadingPlaceholderTimer(nullptr)
+DolphinView::DolphinView(const QUrl &url, QWidget *parent)
+ : QWidget(parent)
+ , m_active(true)
+ , m_tabsForFiles(false)
+ , m_assureVisibleCurrentIndex(false)
+ , m_isFolderWritable(true)
+ , m_dragging(false)
+ , m_url(url)
+ , m_viewPropertiesContext()
+ , m_mode(DolphinView::IconsView)
+ , m_visibleRoles()
+ , m_topLayout(nullptr)
+ , m_model(nullptr)
+ , m_view(nullptr)
+ , m_container(nullptr)
+ , m_toolTipManager(nullptr)
+ , m_selectionChangedTimer(nullptr)
+ , m_currentItemUrl()
+ , m_scrollToCurrentItem(false)
+ , m_restoredContentsPosition()
+ , m_selectedUrls()
+ , m_clearSelectionBeforeSelectingNewItems(false)
+ , m_markFirstNewlySelectedItemAsCurrent(false)
+ , m_versionControlObserver(nullptr)
+ , m_twoClicksRenamingTimer(nullptr)
+ , m_placeholderLabel(nullptr)
+ , m_showLoadingPlaceholderTimer(nullptr)
{
m_topLayout = new QVBoxLayout(this);
m_topLayout->setSpacing(0);
// When a new item has been created by the "Create New..." menu, the item should
// get selected and it must be assured that the item will get visible. As the
// creation is done asynchronously, several signals must be checked:
- connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated,
- this, &DolphinView::observeCreatedItem);
+ connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated, this, &DolphinView::observeCreatedItem);
m_selectionChangedTimer = new QTimer(this);
m_selectionChangedTimer->setSingleShot(true);
m_selectionChangedTimer->setInterval(300);
- connect(m_selectionChangedTimer, &QTimer::timeout,
- this, &DolphinView::emitSelectionChangedSignal);
+ connect(m_selectionChangedTimer, &QTimer::timeout, this, &DolphinView::emitSelectionChangedSignal);
m_model = new KFileItemModel(this);
m_view = new DolphinItemListView();
m_view->setVisibleRoles({"text"});
applyModeToView();
- KItemListController* controller = new KItemListController(m_model, m_view, this);
+ KItemListController *controller = new KItemListController(m_model, m_view, this);
const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
controller->setAutoActivationDelay(delay);
m_container = new KItemListContainer(controller, this);
m_container->installEventFilter(this);
setFocusProxy(m_container);
- connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, [=] { hideToolTip(); });
- connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] { hideToolTip(); });
+ connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, [=] {
+ hideToolTip();
+ });
+ connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] {
+ hideToolTip();
+ });
m_showLoadingPlaceholderTimer = new QTimer(this);
m_showLoadingPlaceholderTimer->setInterval(500);
centeringLayout->addWidget(m_placeholderLabel);
centeringLayout->setAlignment(m_placeholderLabel, Qt::AlignCenter);
m_placeholderLabel->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(m_placeholderLabel, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos){
+ connect(m_placeholderLabel, &QWidget::customContextMenuRequested, this, [this](const QPoint &pos) {
slotViewContextMenuRequested(m_placeholderLabel->mapToGlobal(pos));
});
connect(controller, &KItemListController::swipeUp, this, &DolphinView::slotSwipeUp);
connect(controller, &KItemListController::selectionModeChangeRequested, this, &DolphinView::selectionModeChangeRequested);
- connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted);
- connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
- connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::slotDirectoryLoadingCanceled);
- connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress);
- connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress);
- connect(m_model, &KFileItemModel::itemsChanged,
- this, &DolphinView::slotItemsChanged);
- connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged);
- connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged);
- connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage);
- connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage);
+ connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted);
+ connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
+ connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::slotDirectoryLoadingCanceled);
+ connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress);
+ connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress);
+ connect(m_model, &KFileItemModel::itemsChanged, this, &DolphinView::slotItemsChanged);
+ connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged);
+ connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged);
+ connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage);
+ connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage);
connect(m_model, &KFileItemModel::directoryRedirection, this, &DolphinView::slotDirectoryRedirection);
- connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError);
- connect(m_model, &KFileItemModel::fileItemsChanged, this, &DolphinView::fileItemsChanged);
+ connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError);
+ connect(m_model, &KFileItemModel::fileItemsChanged, this, &DolphinView::fileItemsChanged);
connect(m_model, &KFileItemModel::currentDirectoryRemoved, this, &DolphinView::currentDirectoryRemoved);
- connect(this, &DolphinView::itemCountChanged,
- this, &DolphinView::updatePlaceholderLabel);
+ connect(this, &DolphinView::itemCountChanged, this, &DolphinView::updatePlaceholderLabel);
m_view->installEventFilter(this);
- connect(m_view, &DolphinItemListView::sortOrderChanged,
- this, &DolphinView::slotSortOrderChangedByHeader);
- connect(m_view, &DolphinItemListView::sortRoleChanged,
- this, &DolphinView::slotSortRoleChangedByHeader);
- connect(m_view, &DolphinItemListView::visibleRolesChanged,
- this, &DolphinView::slotVisibleRolesChangedByHeader);
- connect(m_view, &DolphinItemListView::roleEditingCanceled,
- this, &DolphinView::slotRoleEditingCanceled);
- connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished,
- this, &DolphinView::slotHeaderColumnWidthChangeFinished);
- connect(m_view->header(), &KItemListHeader::sidePaddingChanged,
- this, &DolphinView::slotSidePaddingWidthChanged);
-
- KItemListSelectionManager* selectionManager = controller->selectionManager();
- connect(selectionManager, &KItemListSelectionManager::selectionChanged,
- this, &DolphinView::slotSelectionChanged);
+ connect(m_view, &DolphinItemListView::sortOrderChanged, this, &DolphinView::slotSortOrderChangedByHeader);
+ connect(m_view, &DolphinItemListView::sortRoleChanged, this, &DolphinView::slotSortRoleChangedByHeader);
+ connect(m_view, &DolphinItemListView::visibleRolesChanged, this, &DolphinView::slotVisibleRolesChangedByHeader);
+ connect(m_view, &DolphinItemListView::roleEditingCanceled, this, &DolphinView::slotRoleEditingCanceled);
+ connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished, this, &DolphinView::slotHeaderColumnWidthChangeFinished);
+ connect(m_view->header(), &KItemListHeader::sidePaddingChanged, this, &DolphinView::slotSidePaddingWidthChanged);
+
+ KItemListSelectionManager *selectionManager = controller->selectionManager();
+ connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &DolphinView::slotSelectionChanged);
#if HAVE_BALOO
m_toolTipManager = new ToolTipManager(this);
KFileItemList DolphinView::selectedItems() const
{
- const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
KFileItemList selectedItems;
const auto items = selectionManager->selectedItems();
int DolphinView::selectedItemsCount() const
{
- const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
return selectionManager->selectedItems().count();
}
-void DolphinView::markUrlsAsSelected(const QList<QUrl>& urls)
+void DolphinView::markUrlsAsSelected(const QList<QUrl> &urls)
{
m_selectedUrls = urls;
}
void DolphinView::selectItems(const QRegularExpression ®exp, bool enabled)
{
- const KItemListSelectionManager::SelectionMode mode = enabled
- ? KItemListSelectionManager::Select
- : KItemListSelectionManager::Deselect;
- KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ const KItemListSelectionManager::SelectionMode mode = enabled ? KItemListSelectionManager::Select : KItemListSelectionManager::Deselect;
+ KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
for (int index = 0; index < m_model->count(); index++) {
const KFileItem item = m_model->fileItem(index);
return m_view->zoomLevel();
}
-void DolphinView::setSortRole(const QByteArray& role)
+void DolphinView::setSortRole(const QByteArray &role)
{
if (role != sortRole()) {
updateSortRole(role);
QByteArray DolphinView::sortRole() const
{
- const KItemModelBase* model = m_container->controller()->model();
+ const KItemModelBase *model = m_container->controller()->model();
return model->sortRole();
}
return m_model->sortHiddenLast();
}
-void DolphinView::setVisibleRoles(const QList<QByteArray>& roles)
+void DolphinView::setVisibleRoles(const QList<QByteArray> &roles)
{
const QList<QByteArray> previousRoles = roles;
m_view->writeSettings();
}
-void DolphinView::setNameFilter(const QString& nameFilter)
+void DolphinView::setNameFilter(const QString &nameFilter)
{
m_model->setNameFilter(nameFilter);
}
return m_model->nameFilter();
}
-void DolphinView::setMimeTypeFilters(const QStringList& filters)
+void DolphinView::setMimeTypeFilters(const QStringList &filters)
{
return m_model->setMimeTypeFilters(filters);
}
// Give a summary of the status of the selected files
const KFileItemList list = selectedItems();
- for (const KFileItem& item : list) {
+ for (const KFileItem &item : list) {
if (item.isDir()) {
++folderCount;
} else {
return;
}
- m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(),
- KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
- connect(m_statJobForStatusBarText, &KJob::result,
- this, &DolphinView::slotStatJobResult);
+ m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(), KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
+ connect(m_statJobForStatusBarText, &KJob::result, this, &DolphinView::slotStatJobResult);
m_statJobForStatusBarText->start();
}
}
-void DolphinView::emitStatusBarText(const int folderCount, const int fileCount,
- KIO::filesize_t totalFileSize, const Selection selection)
+void DolphinView::emitStatusBarText(const int folderCount, const int fileCount, KIO::filesize_t totalFileSize, const Selection selection)
{
QString foldersText;
QString filesText;
}
if (fileCount > 0 && folderCount > 0) {
- summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
- foldersText, filesText,
- KFormat().formatByteSize(totalFileSize));
+ summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)", foldersText, filesText, KFormat().formatByteSize(totalFileSize));
} else if (fileCount > 0) {
- summary = i18nc("@info:status files (size)", "%1 (%2)",
- filesText,
- KFormat().formatByteSize(totalFileSize));
+ summary = i18nc("@info:status files (size)", "%1 (%2)", filesText, KFormat().formatByteSize(totalFileSize));
} else if (folderCount > 0) {
summary = foldersText;
} else {
Q_EMIT statusBarTextChanged(summary);
}
-QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
+QList<QAction *> DolphinView::versionControlActions(const KFileItemList &items) const
{
- QList<QAction*> actions;
+ QList<QAction *> actions;
if (items.isEmpty()) {
const KFileItem item = m_model->rootItem();
return actions;
}
-void DolphinView::setUrl(const QUrl& url)
+void DolphinView::setUrl(const QUrl &url)
{
if (url == m_url) {
return;
hideToolTip();
- disconnect(m_view, &DolphinItemListView::roleEditingFinished,
- this, &DolphinView::slotRoleEditingFinished);
+ disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
// It is important to clear the items from the model before
// applying the view properties, otherwise expensive operations
void DolphinView::selectAll()
{
- KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
selectionManager->setSelected(0, m_model->count());
}
void DolphinView::invertSelection()
{
- KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
}
if (items.count() == 1 && GeneralSettings::renameInline()) {
const int index = m_model->index(items.first());
- QMetaObject::Connection * const connection = new QMetaObject::Connection;
- *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=](){
+ QMetaObject::Connection *const connection = new QMetaObject::Connection;
+ *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=]() {
QObject::disconnect(*connection);
delete connection;
hideToolTip();
- connect(m_view, &DolphinItemListView::roleEditingFinished,
- this, &DolphinView::slotRoleEditingFinished);
+ connect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
});
m_view->scrollToItem(index);
} else {
- KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(items, this);
- connect(dialog, &KIO::RenameFileDialog::renamingFinished,
- this, &DolphinView::slotRenameDialogRenamingFinished);
+ KIO::RenameFileDialog *dialog = new KIO::RenameFileDialog(items, this);
+ connect(dialog, &KIO::RenameFileDialog::renamingFinished, this, &DolphinView::slotRenameDialogRenamingFinished);
dialog->open();
}
KIO::JobUiDelegate uiDelegate;
uiDelegate.setWindow(window());
if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) {
- KIO::Job* job = KIO::trash(list);
+ KIO::Job *job = KIO::trash(list);
KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job);
KJobWidgets::setWindow(job, this);
- connect(job, &KIO::Job::result,
- this, &DolphinView::slotTrashFileFinished);
+ connect(job, &KIO::Job::result, this, &DolphinView::slotTrashFileFinished);
}
#endif
}
KIO::JobUiDelegate uiDelegate;
uiDelegate.setWindow(window());
if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) {
- KIO::Job* job = KIO::del(list);
+ KIO::Job *job = KIO::del(list);
KJobWidgets::setWindow(job, this);
- connect(job, &KIO::Job::result,
- this, &DolphinView::slotDeleteFileFinished);
+ connect(job, &KIO::Job::result, this, &DolphinView::slotDeleteFileFinished);
}
#endif
}
void DolphinView::cutSelectedItemsToClipboard()
{
- QMimeData* mimeData = selectionMimeData();
+ QMimeData *mimeData = selectionMimeData();
KIO::setClipboardDataCut(mimeData, true);
KUrlMimeData::exportUrlsToPortal(mimeData);
QApplication::clipboard()->setMimeData(mimeData);
void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
{
- KIO::CopyJob* job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
+ KIO::CopyJob *job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
KJobWidgets::setWindow(job, this);
connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
{
- KIO::CopyJob* job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
+ KIO::CopyJob *job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
KJobWidgets::setWindow(job, this);
connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
KIO::FileUndoManager::self()->recordCopyJob(job);
-
}
void DolphinView::paste()
// but before the filename extension, if present
QList<QUrl> newSelection;
for (const auto &item : itemList) {
- const QUrl originalURL = item.url();
+ const QUrl originalURL = item.url();
const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
const QString originalFileName = item.name();
// No extension; new filename is "<oldfilename> copy"
if (extension.isEmpty()) {
duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFileName));
- // There's an extension; new filename is "<oldfilename> copy.<extension>"
+ // There's an extension; new filename is "<oldfilename> copy.<extension>"
} else {
// Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
extension = QLatin1String(".") + extension;
duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension);
}
- KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL);
+ KIO::CopyJob *job = KIO::copyAs(originalURL, duplicateURL);
KJobWidgets::setWindow(job, this);
if (job) {
color.setAlpha(150);
}
- QWidget* viewport = m_container->viewport();
+ QWidget *viewport = m_container->viewport();
if (viewport) {
QPalette palette;
palette.setColor(viewport->backgroundRole(), color);
m_twoClicksRenamingTimer->stop();
}
-bool DolphinView::eventFilter(QObject* watched, QEvent* event)
+bool DolphinView::eventFilter(QObject *watched, QEvent *event)
{
switch (event->type()) {
case QEvent::PaletteChange:
case QEvent::KeyPress:
hideToolTip(ToolTipManager::HideBehavior::Instantly);
if (GeneralSettings::useTabForSwitchingSplitView()) {
- QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
+ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
Q_EMIT toggleActiveViewRequested();
return true;
break;
case QEvent::ToolTip:
- tryShowNameToolTip(static_cast<QHelpEvent*>(event));
+ tryShowNameToolTip(static_cast<QHelpEvent *>(event));
default:
break;
return QWidget::eventFilter(watched, event);
}
-void DolphinView::wheelEvent(QWheelEvent* event)
+void DolphinView::wheelEvent(QWheelEvent *event)
{
if (event->modifiers().testFlag(Qt::ControlModifier)) {
const QPoint numDegrees = event->angleDelta() / 8;
}
}
-void DolphinView::hideEvent(QHideEvent* event)
+void DolphinView::hideEvent(QHideEvent *event)
{
hideToolTip();
QWidget::hideEvent(event);
}
-bool DolphinView::event(QEvent* event)
+bool DolphinView::event(QEvent *event)
{
if (event->type() == QEvent::WindowDeactivate) {
/* See Bug 297355
if (indexes.count() > 5) {
QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- const int answer = KMessageBox::warningTwoActions(this, question, {},
+ const int answer = KMessageBox::warningTwoActions(
+ this,
+ question,
+ {},
#else
- const int answer = KMessageBox::warningYesNo(this, question, {},
+ const int answer =
+ KMessageBox::warningYesNo(this,
+ question,
+ {},
#endif
- KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes.count()),
- QStringLiteral("document-open")),
- KStandardGuiItem::cancel());
+ KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes.count()), QStringLiteral("document-open")),
+ KStandardGuiItem::cancel());
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
if (answer != KMessageBox::PrimaryAction) {
#else
for (int index : indexes) {
KFileItem item = m_model->fileItem(index);
- const QUrl& url = openItemAsFolderUrl(item);
+ const QUrl &url = openItemAsFolderUrl(item);
if (!url.isEmpty()) {
// Open folders in new tabs or in new windows depending on the modifier
void DolphinView::slotItemMiddleClicked(int index)
{
- const KFileItem& item = m_model->fileItem(index);
- const QUrl& url = openItemAsFolderUrl(item);
+ const KFileItem &item = m_model->fileItem(index);
+ const QUrl &url = openItemAsFolderUrl(item);
const auto modifiers = QGuiApplication::keyboardModifiers();
if (!url.isEmpty()) {
// keep in sync with KUrlNavigator::slotNavigatorButtonClicked
}
}
-void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
+void DolphinView::slotItemContextMenuRequested(int index, const QPointF &pos)
{
// Force emit of a selection changed signal before we request the
// context menu, to update the edit-actions first. (See Bug 294013)
Q_EMIT requestContextMenu(pos.toPoint(), item, selectedItems(), url());
}
-void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
+void DolphinView::slotViewContextMenuRequested(const QPointF &pos)
{
Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), selectedItems(), url());
}
-void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
+void DolphinView::slotHeaderContextMenuRequested(const QPointF &pos)
{
ViewProperties props(viewPropertiesUrl());
QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
- KItemListView* view = m_container->controller()->view();
+ KItemListView *view = m_container->controller()->view();
const QList<QByteArray> visibleRolesSet = view->visibleRoles();
bool indexingEnabled = false;
#endif
QString groupName;
- QMenu* groupMenu = nullptr;
+ QMenu *groupMenu = nullptr;
// Add all roles to the menu that can be shown or hidden by the user
const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
- for (const KFileItemModel::RoleInfo& info : rolesInfo) {
+ for (const KFileItemModel::RoleInfo &info : rolesInfo) {
if (info.role == "text") {
// It should not be possible to hide the "text" role
continue;
}
const QString text = m_model->roleDescription(info.role);
- QAction* action = nullptr;
+ QAction *action = nullptr;
if (info.group.isEmpty()) {
action = menu->addAction(text);
} else {
action->setChecked(visibleRolesSet.contains(info.role));
action->setData(info.role);
- const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
- (info.requiresBaloo) ||
- (info.requiresIndexer && indexingEnabled);
+ const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled);
action->setEnabled(enable);
}
menu->addSeparator();
- QActionGroup* widthsGroup = new QActionGroup(menu);
+ QActionGroup *widthsGroup = new QActionGroup(menu);
const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
- QAction* toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding"));
+ QAction *toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding"));
toggleSidePaddingAction->setCheckable(true);
toggleSidePaddingAction->setChecked(view->header()->sidePadding() > 0);
- QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
+ QAction *autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
autoAdjustWidthsAction->setCheckable(true);
autoAdjustWidthsAction->setChecked(autoColumnWidths);
autoAdjustWidthsAction->setActionGroup(widthsGroup);
- QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
+ QAction *customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
customWidthsAction->setCheckable(true);
customWidthsAction->setChecked(!autoColumnWidths);
customWidthsAction->setActionGroup(widthsGroup);
- QAction* action = menu->exec(pos.toPoint());
+ QAction *action = menu->exec(pos.toPoint());
if (menu && action) {
- KItemListHeader* header = view->header();
+ KItemListHeader *header = view->header();
if (action == autoAdjustWidthsAction) {
// Clear the column-widths from the viewproperties and turn on
QList<int> columnWidths;
const auto visibleRoles = view->visibleRoles();
columnWidths.reserve(visibleRoles.count());
- for (const QByteArray& role : visibleRoles) {
+ for (const QByteArray &role : visibleRoles) {
columnWidths.append(header->columnWidth(role));
}
props.setHeaderColumnWidths(columnWidths);
if (!header->automaticColumnResizing()) {
const auto visibleRoles = view->visibleRoles();
columnWidths.reserve(visibleRoles.count());
- for (const QByteArray& role : visibleRoles) {
+ for (const QByteArray &role : visibleRoles) {
columnWidths.append(header->columnWidth(role));
}
}
delete menu;
}
-void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
+void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray &role, qreal current)
{
const QList<QByteArray> visibleRoles = m_view->visibleRoles();
if (columnWidths.count() != visibleRoles.count()) {
columnWidths.clear();
columnWidths.reserve(visibleRoles.count());
- const KItemListHeader* header = m_view->header();
- for (const QByteArray& role : visibleRoles) {
+ const KItemListHeader *header = m_view->header();
+ for (const QByteArray &role : visibleRoles) {
const int width = header->columnWidth(role);
columnWidths.append(width);
}
Q_EMIT requestItemInfo(KFileItem());
}
-void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
+void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event)
{
QUrl destUrl;
KFileItem destItem = m_model->fileItem(index);
destUrl = destItem.mostLocalUrl();
}
- QDropEvent dropEvent(event->pos().toPoint(),
- event->possibleActions(),
- event->mimeData(),
- event->buttons(),
- event->modifiers());
+ QDropEvent dropEvent(event->pos().toPoint(), event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
dropUrls(destUrl, &dropEvent, this);
setActive(true);
void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
{
- KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
+ KIO::DropJob *job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
if (job) {
connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
}
}
-void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
+void DolphinView::slotModelChanged(KItemModelBase *current, KItemModelBase *previous)
{
if (previous != nullptr) {
- Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
- KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
+ Q_ASSERT(qobject_cast<KFileItemModel *>(previous));
+ KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(previous);
disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
m_versionControlObserver->setModel(nullptr);
}
if (current) {
- Q_ASSERT(qobject_cast<KFileItemModel*>(current));
- KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
+ Q_ASSERT(qobject_cast<KFileItemModel *>(current));
+ KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(current);
connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
m_versionControlObserver->setModel(fileItemModel);
}
slotItemCreated(to);
}
-void DolphinView::slotItemCreated(const QUrl& url)
+void DolphinView::slotItemCreated(const QUrl &url)
{
if (m_markFirstNewlySelectedItemAsCurrent) {
markUrlAsCurrent(url);
}
}
-void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
+void DolphinView::slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous)
{
const int currentCount = current.count();
const int previousCount = previous.count();
- const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
- (currentCount > 0 && previousCount == 0);
+ const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || (currentCount > 0 && previousCount == 0);
// If nothing has been selected before and something got selected (or if something
// was selected before and now nothing is selected) the selectionChangedSignal must
KIO::filesize_t totalFileSize = 0;
bool countFileSize = true;
- const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
+ const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
// We have a precomputed value.
- totalFileSize = static_cast<KIO::filesize_t>(
- entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
+ totalFileSize = static_cast<KIO::filesize_t>(entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
countFileSize = false;
}
emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
}
-void DolphinView::updateSortRole(const QByteArray& role)
+void DolphinView::updateSortRole(const QByteArray &role)
{
ViewProperties props(viewPropertiesUrl());
props.setSortRole(role);
- KItemModelBase* model = m_container->controller()->model();
+ KItemModelBase *model = m_container->controller()->model();
model->setSortRole(role);
Q_EMIT sortRoleChanged(role);
Q_EMIT sortHiddenLastChanged(hiddenLast);
}
-
QPair<bool, QString> DolphinView::pasteInfo() const
{
const QMimeData *mimeData = QApplication::clipboard()->mimeData();
return m_mode == DetailsView;
}
-bool DolphinView::isExpanded(const KFileItem& item) const
+bool DolphinView::isExpanded(const KFileItem &item) const
{
Q_ASSERT(item.isDir());
Q_ASSERT(items().contains(item));
return m_model->isExpanded(m_model->index(item));
}
-void DolphinView::restoreState(QDataStream& stream)
+void DolphinView::restoreState(QDataStream &stream)
{
// Read the version number of the view state and check if the version is supported.
quint32 version = 0;
m_model->restoreExpandedDirectories(urls);
}
-void DolphinView::saveState(QDataStream& stream)
+void DolphinView::saveState(QDataStream &stream)
{
stream << quint32(1); // View state version
return m_model->rootItem();
}
-void DolphinView::setViewPropertiesContext(const QString& context)
+void DolphinView::setViewPropertiesContext(const QString &context)
{
m_viewPropertiesContext = context;
}
return m_viewPropertiesContext;
}
-QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
+QUrl DolphinView::openItemAsFolderUrl(const KFileItem &item, const bool browseThroughArchives)
{
if (item.isNull()) {
return QUrl();
}
if (item.isMimeTypeKnown()) {
- const QString& mimetype = item.mimetype();
+ const QString &mimetype = item.mimetype();
if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
// Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
// The .protocol file specifies the mimetype that the kioslave handles.
// Note that we don't use mimetype inheritance since we don't want to
// open OpenDocument files as zip folders...
- const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
+ const QString &protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
if (!protocol.isEmpty()) {
url.setScheme(protocol);
return url;
setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize)));
}
-void DolphinView::observeCreatedItem(const QUrl& url)
+void DolphinView::observeCreatedItem(const QUrl &url)
{
if (m_active) {
forceUrlsSelection(url, {url});
}
}
-void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
+void DolphinView::slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl)
{
if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
Q_EMIT redirection(oldUrl, newUrl);
void DolphinView::updateViewState()
{
if (m_currentItemUrl != QUrl()) {
- KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
// if there is a selection already, leave it that way
if (!selectionManager->hasSelection()) {
}
if (!m_selectedUrls.isEmpty()) {
- KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
// if there is a selection already, leave it that way
if (!selectionManager->hasSelection()) {
Q_UNUSED(behavior)
#endif
} else if (m_mode == DolphinView::IconsView) {
- QToolTip::hideText();
+ QToolTip::hideText();
}
}
void DolphinView::slotTwoClicksRenamingTimerTimeout()
{
- const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
// verify that only one item is selected
if (selectionManager->selectedItems().count() == 1) {
}
}
-void DolphinView::slotTrashFileFinished(KJob* job)
+void DolphinView::slotTrashFileFinished(KJob *job)
{
if (job->error() == 0) {
Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
}
}
-void DolphinView::slotDeleteFileFinished(KJob* job)
+void DolphinView::slotDeleteFileFinished(KJob *job)
{
if (job->error() == 0) {
Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
}
}
-void DolphinView::slotRenamingResult(KJob* job)
+void DolphinView::slotRenamingResult(KJob *job)
{
if (job->error()) {
KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
Q_EMIT sortOrderChanged(current);
}
-void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
+void DolphinView::slotSortRoleChangedByHeader(const QByteArray ¤t, const QByteArray &previous)
{
Q_UNUSED(previous)
Q_ASSERT(m_model->sortRole() == current);
Q_EMIT sortRoleChanged(current);
}
-void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
- const QList<QByteArray>& previous)
+void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray> ¤t, const QList<QByteArray> &previous)
{
Q_UNUSED(previous)
Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
void DolphinView::slotRoleEditingCanceled()
{
- disconnect(m_view, &DolphinItemListView::roleEditingFinished,
- this, &DolphinView::slotRoleEditingFinished);
+ disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
}
-void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
+void DolphinView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value)
{
- disconnect(m_view, &DolphinItemListView::roleEditingFinished,
- this, &DolphinView::slotRoleEditingFinished);
+ disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
const KFileItemList items = selectedItems();
if (items.count() != 1) {
KGuiItem yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden"));
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
- const auto code = KMessageBox::questionTwoActions(this,
+ const auto code =
+ KMessageBox::questionTwoActions(this,
#else
- const auto code = KMessageBox::questionYesNo(this,
+ const auto code =
+ KMessageBox::questionYesNo(this,
#endif
- oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
- "Do you still want to rename it?")
- : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
- "Do you still want to rename it?"),
- oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
- yesGuiItem,
- KStandardGuiItem::cancel(),
- QStringLiteral("ConfirmHide")
- );
+ oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
+ "Do you still want to rename it?")
+ : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
+ "Do you still want to rename it?"),
+ oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
+ yesGuiItem,
+ KStandardGuiItem::cancel(),
+ QStringLiteral("ConfirmHide"));
#if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
if (code == KMessageBox::SecondaryAction) {
#else
if (code == KMessageBox::No) {
#endif
- return;
+ return;
}
}
#endif
m_model->setData(index, data);
}
- KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
+ KIO::Job *job = KIO::moveAs(oldUrl, newUrl);
KJobWidgets::setWindow(job, this);
KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
job->uiDelegate()->setAutoErrorHandlingEnabled(true);
if (retVal.direction != EditDone) {
const short indexShift = retVal.direction == EditNext ? 1 : -1;
m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect);
- m_container->controller()->selectionManager()->setSelected(index + indexShift, 1,
- KItemListSelectionManager::Select);
+ m_container->controller()->selectionManager()->setSelected(index + indexShift, 1, KItemListSelectionManager::Select);
renameSelectedItems();
}
}
}
-void DolphinView::loadDirectory(const QUrl& url, bool reload)
+void DolphinView::loadDirectory(const QUrl &url, bool reload)
{
if (!url.isValid()) {
const QString location(url.toDisplayString(QUrl::PreferLocalFile));
applyViewProperties(props);
}
-void DolphinView::applyViewProperties(const ViewProperties& props)
+void DolphinView::applyViewProperties(const ViewProperties &props)
{
m_view->beginTransaction();
}
}
- KItemListView* itemListView = m_container->controller()->view();
+ KItemListView *itemListView = m_container->controller()->view();
if (itemListView->isHeaderVisible()) {
- KItemListHeader* header = itemListView->header();
+ KItemListHeader *header = itemListView->header();
const QList<int> headerColumnWidths = props.headerColumnWidths();
const int rolesCount = m_visibleRoles.count();
if (headerColumnWidths.count() == rolesCount) {
void DolphinView::applyModeToView()
{
switch (m_mode) {
- case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
- case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
- case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
- default: Q_ASSERT(false); break;
+ case IconsView:
+ m_view->setItemLayout(KFileItemListView::IconsLayout);
+ break;
+ case CompactView:
+ m_view->setItemLayout(KFileItemListView::CompactLayout);
+ break;
+ case DetailsView:
+ m_view->setItemLayout(KFileItemListView::DetailsLayout);
+ break;
+ default:
+ Q_ASSERT(false);
+ break;
}
}
-void DolphinView::pasteToUrl(const QUrl& url)
+void DolphinView::pasteToUrl(const QUrl &url)
{
KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
KJobWidgets::setWindow(job, this);
const KFileItemList items = selectedItems();
urls.reserve(items.count());
- for (const KFileItem& item : items) {
+ for (const KFileItem &item : items) {
urls.append(item.url());
}
return urls;
}
-QMimeData* DolphinView::selectionMimeData() const
+QMimeData *DolphinView::selectionMimeData() const
{
- const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
+ const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
const KItemSet selectedIndexes = selectionManager->selectedItems();
return m_model->createMimeData(selectedIndexes);
return url;
}
-void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
+void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl> &urls)
{
forceUrlsSelection(urls.first(), urls);
}
-void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
+void DolphinView::forceUrlsSelection(const QUrl ¤t, const QList<QUrl> &selected)
{
clearSelection();
m_clearSelectionBeforeSelectingNewItems = true;
if (list.isEmpty()) {
return;
}
- const KFileItem& item = list.at(0);
+ const KFileItem &item = list.at(0);
QString path = item.localPath();
if (path.isEmpty()) {
path = item.url().toDisplayString();
}
- QClipboard* clipboard = QApplication::clipboard();
+ QClipboard *clipboard = QApplication::clipboard();
if (clipboard == nullptr) {
return;
}
m_placeholderLabel->setVisible(true);
}
-void DolphinView::tryShowNameToolTip(QHelpEvent* event)
+void DolphinView::tryShowNameToolTip(QHelpEvent *event)
{
if (!GeneralSettings::showToolTips() && m_mode == DolphinView::IconsView) {
const std::optional<int> index = m_view->itemAt(event->pos());
// Check whether the filename has been elided
const bool isElided = m_view->isElided(index.value());
- if(isElided) {
+ if (isElided) {
const KFileItem item = m_model->fileItem(index.value());
const QString text = item.text();
const QPoint pos = mapToGlobal(event->pos());
#ifndef DOLPHINVIEW_H
#define DOLPHINVIEW_H
-#include "dolphintabwidget.h"
#include "dolphin_export.h"
+#include "dolphintabwidget.h"
#include "tooltips/tooltipmanager.h"
+#include "config-dolphin.h"
#include <KFileItem>
#include <KIO/Job>
-#include "config-dolphin.h"
#include <kio/fileundomanager.h>
#include <kparts/part.h>
* view mode is automatically updated if the directory itself
* defines a view mode (see class ViewProperties for details).
*/
- enum Mode
- {
+ enum Mode {
/**
* The items are shown as icons with a name-label below.
*/
* @param url Specifies the content which should be shown.
* @param parent Parent widget of the view.
*/
- DolphinView(const QUrl& url, QWidget* parent);
+ DolphinView(const QUrl &url, QWidget *parent);
~DolphinView() override;
* Marks the item indicated by \p url to be scrolled to and as the
* current item after directory DolphinView::url() has been loaded.
*/
- void markUrlAsCurrent(const QUrl& url);
+ void markUrlAsCurrent(const QUrl &url);
/**
* All items that match the regular expression \a regexp will get selected
*/
void resetZoomLevel();
- void setSortRole(const QByteArray& role);
+ void setSortRole(const QByteArray &role);
QByteArray sortRole() const;
void setSortOrder(Qt::SortOrder order);
bool sortHiddenLast() const;
/** Sets the additional information which should be shown for the items. */
- void setVisibleRoles(const QList<QByteArray>& roles);
+ void setVisibleRoles(const QList<QByteArray> &roles);
/** Returns the additional information which should be shown for the items. */
QList<QByteArray> visibleRoles() const;
* Filters the currently shown items by \a nameFilter. All items
* which contain the given filter string will be shown.
*/
- void setNameFilter(const QString& nameFilter);
+ void setNameFilter(const QString &nameFilter);
QString nameFilter() const;
/**
* whose content-type matches those given by the list of filters
* will be shown.
*/
- void setMimeTypeFilters(const QStringList& filters);
+ void setMimeTypeFilters(const QStringList &filters);
QStringList mimeTypeFilters() const;
/**
* Returns the version control actions that are provided for the items \p items.
* Usually the actions are presented in the context menu.
*/
- QList<QAction*> versionControlActions(const KFileItemList& items) const;
+ QList<QAction *> versionControlActions(const KFileItemList &items) const;
/**
* Returns the state of the paste action:
/**
* Restores the view state (current item, contents position, details view expansion state)
*/
- void restoreState(QDataStream& stream);
+ void restoreState(QDataStream &stream);
/**
* Saves the view state (current item, contents position, details view expansion state)
*/
- void saveState(QDataStream& stream);
+ void saveState(QDataStream &stream);
/**
* Returns the root item which represents the current URL.
* makes sense if specific types of URLs (e.g. search-URLs) should
* share common view-properties.
*/
- void setViewPropertiesContext(const QString& context);
+ void setViewPropertiesContext(const QString &context);
QString viewPropertiesContext() const;
/**
* @return a valid and adjusted url if the item can be opened as folder,
* otherwise return an empty url.
*/
- static QUrl openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives = true);
+ static QUrl openItemAsFolderUrl(const KFileItem &item, const bool browseThroughArchives = true);
/**
* Hides tooltip displayed over element.
* Changes the directory to \a url. If the current directory is equal to
* \a url, nothing will be done (use DolphinView::reload() instead).
*/
- void setUrl(const QUrl& url);
+ void setUrl(const QUrl &url);
/**
* Selects all items.
void updateViewState();
/** Activates the view if the item list container gets focus. */
- bool eventFilter(QObject* watched, QEvent* event) override;
+ bool eventFilter(QObject *watched, QEvent *event) override;
Q_SIGNALS:
/**
void activated();
/** Is emitted if the URL of the view has been changed to \a url. */
- void urlChanged(const QUrl& url);
+ void urlChanged(const QUrl &url);
/**
* Is emitted when clicking on an item with the left mouse button.
/**
* Is emitted if a new tab should be opened for the URL \a url.
*/
- void tabRequested(const QUrl& url);
+ void tabRequested(const QUrl &url);
/**
* Is emitted if a new tab should be opened for the URL \a url and set as active.
void statusBarTextChanged(QString statusBarText);
/** Is emitted if the sorting by name, size or date has been changed. */
- void sortRoleChanged(const QByteArray& role);
+ void sortRoleChanged(const QByteArray &role);
/** Is emitted if the sort order (ascending or descending) has been changed. */
void sortOrderChanged(Qt::SortOrder order);
void sortHiddenLastChanged(bool hiddenLast);
/** Is emitted if the additional information shown for this view has been changed. */
- void visibleRolesChanged(const QList<QByteArray>& current,
- const QList<QByteArray>& previous);
+ void visibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous);
/** Is emitted if the zoom level has been changed by zooming in or out. */
void zoomLevelChanged(int current, int previous);
* Is emitted if information of an item is requested to be shown e. g. in the panel.
* If item is null, no item information request is pending.
*/
- void requestItemInfo(const KFileItem& item);
+ void requestItemInfo(const KFileItem &item);
/**
* Is emitted whenever the selection has been changed.
*/
- void selectionChanged(const KFileItemList& selection);
+ void selectionChanged(const KFileItemList &selection);
/**
* Is emitted if a context menu is requested for the item \a item,
* which is part of \a url. If the item is null, the context menu
* for the URL should be shown.
*/
- void requestContextMenu(const QPoint& pos,
- const KFileItem& item,
- const KFileItemList &selectedItems,
- const QUrl& url);
+ void requestContextMenu(const QPoint &pos, const KFileItem &item, const KFileItemList &selectedItems, const QUrl &url);
/**
* Is emitted if an information message with the content \a msg
* should be shown.
*/
- void infoMessage(const QString& msg);
+ void infoMessage(const QString &msg);
/**
* Is emitted if an error message with the content \a msg
* should be shown.
*/
- void errorMessage(const QString& msg);
+ void errorMessage(const QString &msg);
/**
* Is emitted if an "operation completed" message with the content \a msg
* should be shown.
*/
- void operationCompletedMessage(const QString& msg);
+ void operationCompletedMessage(const QString &msg);
/**
* Is emitted after DolphinView::setUrl() has been invoked and
* Emitted when the file-item-model emits redirection.
* Testcase: fish://localhost
*/
- void redirection(const QUrl& oldUrl, const QUrl& newUrl);
+ void redirection(const QUrl &oldUrl, const QUrl &newUrl);
/**
* Is emitted when the URL set by DolphinView::setUrl() represents a file.
* In this case no signal errorMessage() will be emitted.
*/
- void urlIsFileError(const QUrl& url);
+ void urlIsFileError(const QUrl &url);
/**
* Is emitted when the write state of the folder has been changed. The application
* Is emitted when the user clicks a tag or a link
* in the metadata widget of a tooltip.
*/
- void urlActivated(const QUrl& url);
+ void urlActivated(const QUrl &url);
void goUpRequested();
protected:
/** Changes the zoom level if Control is pressed during a wheel event. */
- void wheelEvent(QWheelEvent* event) override;
+ void wheelEvent(QWheelEvent *event) override;
- void hideEvent(QHideEvent* event) override;
- bool event(QEvent* event) override;
+ void hideEvent(QHideEvent *event) override;
+ bool event(QEvent *event) override;
private Q_SLOTS:
/**
void slotItemActivated(int index);
void slotItemsActivated(const KItemSet &indexes);
void slotItemMiddleClicked(int index);
- void slotItemContextMenuRequested(int index, const QPointF& pos);
- void slotViewContextMenuRequested(const QPointF& pos);
- void slotHeaderContextMenuRequested(const QPointF& pos);
- void slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current);
+ void slotItemContextMenuRequested(int index, const QPointF &pos);
+ void slotViewContextMenuRequested(const QPointF &pos);
+ void slotHeaderContextMenuRequested(const QPointF &pos);
+ void slotHeaderColumnWidthChangeFinished(const QByteArray &role, qreal current);
void slotSidePaddingWidthChanged(qreal width);
void slotItemHovered(int index);
void slotItemUnhovered(int index);
- void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event);
- void slotModelChanged(KItemModelBase* current, KItemModelBase* previous);
+ void slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event);
+ void slotModelChanged(KItemModelBase *current, KItemModelBase *previous);
void slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons);
- void slotRenameDialogRenamingFinished(const QList<QUrl>& urls);
+ void slotRenameDialogRenamingFinished(const QList<QUrl> &urls);
void slotSelectedItemTextPressed(int index);
void slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to);
void slotIncreaseZoom();
* the signal is emitted only after no selection change has been done
* within a small delay.
*/
- void slotSelectionChanged(const KItemSet& current, const KItemSet& previous);
+ void slotSelectionChanged(const KItemSet ¤t, const KItemSet &previous);
/**
* Is called by emitDelayedSelectionChangedSignal() and emits the
* Updates the view properties of the current URL to the
* sorting given by \a role.
*/
- void updateSortRole(const QByteArray& role);
+ void updateSortRole(const QByteArray &role);
/**
* Updates the view properties of the current URL to the
* Indicates in the status bar that the delete operation
* of the job \a job has been finished.
*/
- void slotDeleteFileFinished(KJob* job);
+ void slotDeleteFileFinished(KJob *job);
/**
* Indicates in the status bar that the trash operation
* of the job \a job has been finished.
*/
- void slotTrashFileFinished(KJob* job);
+ void slotTrashFileFinished(KJob *job);
/**
* Invoked when the rename job is done, for error handling.
*/
- void slotRenamingResult(KJob* job);
+ void slotRenamingResult(KJob *job);
/**
* Invoked when the file item model has started the loading
* Is invoked when the sort role has been changed by the user by clicking
* on a header item. The view properties of the directory will get updated.
*/
- void slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous);
+ void slotSortRoleChangedByHeader(const QByteArray ¤t, const QByteArray &previous);
/**
* Is invoked when the visible roles have been changed by the user by dragging
* a header item. The view properties of the directory will get updated.
*/
- void slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
- const QList<QByteArray>& previous);
+ void slotVisibleRolesChangedByHeader(const QList<QByteArray> ¤t, const QList<QByteArray> &previous);
void slotRoleEditingCanceled();
- void slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value);
+ void slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value);
/**
* Observes the item with the URL \a url. As soon as the directory
* Called when a redirection happens.
* Testcase: fish://localhost
*/
- void slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl);
+ void slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl);
void slotTwoClicksRenamingTimerTimeout();
private:
- void loadDirectory(const QUrl& url, bool reload = false);
+ void loadDirectory(const QUrl &url, bool reload = false);
/**
* Applies the view properties which are defined by the current URL
/**
* Applies the given view properties to the DolphinView.
*/
- void applyViewProperties(const ViewProperties& props);
+ void applyViewProperties(const ViewProperties &props);
/**
* Applies the m_mode property to the corresponding
*/
void applyModeToView();
- enum Selection {
- HasSelection,
- NoSelection
- };
+ enum Selection { HasSelection, NoSelection };
/**
* Helper method for DolphinView::requestStatusBarText().
* Generates the status bar text from the parameters and
* @param selection if HasSelection is passed, the emitted status bar text will say
* that the folders and files which are counted here are selected.
*/
- void emitStatusBarText(const int folderCount, const int fileCount,
- KIO::filesize_t totalFileSize, const Selection selection);
+ void emitStatusBarText(const int folderCount, const int fileCount, KIO::filesize_t totalFileSize, const Selection selection);
/**
* Helper method for DolphinView::paste() and DolphinView::pasteIntoFolder().
* Pastes the clipboard data into the URL \a url.
*/
- void pasteToUrl(const QUrl& url);
+ void pasteToUrl(const QUrl &url);
/**
* Returns a list of URLs for all selected items. The list is
/**
* Returns the MIME data for all selected items.
*/
- QMimeData* selectionMimeData() const;
+ QMimeData *selectionMimeData() const;
/**
* Updates m_isFolderWritable dependent on whether the folder represented by
* @param current URL to be set as current
* @param selected list of selected items
*/
- void forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected);
+ void forceUrlsSelection(const QUrl ¤t, const QList<QUrl> &selected);
void abortTwoClicksRenaming();
void updatePlaceholderLabel();
- void tryShowNameToolTip(QHelpEvent* event);
+ void tryShowNameToolTip(QHelpEvent *event);
private:
void updatePalette();
bool m_dragging; // True if a dragging is done. Required to be able to decide whether a
// tooltip may be shown when hovering an item.
- enum class LoadingState {
- Idle,
- Loading,
- Canceled,
- Completed
- };
+ enum class LoadingState { Idle, Loading, Canceled, Completed };
LoadingState m_loadingState = LoadingState::Idle;
QUrl m_url;
QPointer<KIO::StatJob> m_statJobForStatusBarText;
- QVBoxLayout* m_topLayout;
+ QVBoxLayout *m_topLayout;
- KFileItemModel* m_model;
- DolphinItemListView* m_view;
- KItemListContainer* m_container;
+ KFileItemModel *m_model;
+ DolphinItemListView *m_view;
+ KItemListContainer *m_container;
- ToolTipManager* m_toolTipManager;
+ ToolTipManager *m_toolTipManager;
- QTimer* m_selectionChangedTimer;
+ QTimer *m_selectionChangedTimer;
QUrl m_currentItemUrl; // Used for making the view to remember the current URL after F5
bool m_scrollToCurrentItem; // Used for marking we need to scroll to current item or not
bool m_clearSelectionBeforeSelectingNewItems;
bool m_markFirstNewlySelectedItemAsCurrent;
- VersionControlObserver* m_versionControlObserver;
+ VersionControlObserver *m_versionControlObserver;
- QTimer* m_twoClicksRenamingTimer;
+ QTimer *m_twoClicksRenamingTimer;
QUrl m_twoClicksRenamingItemUrl;
- QLabel* m_placeholderLabel;
- QTimer* m_showLoadingPlaceholderTimer;
+ QLabel *m_placeholderLabel;
+ QTimer *m_showLoadingPlaceholderTimer;
/// Used for selection mode. @see setSelectionMode()
std::unique_ptr<QProxyStyle> m_proxyStyle;
friend class TestBase;
friend class DolphinDetailsViewTest;
friend class DolphinMainWindowTest;
- friend class DolphinPart; // Accesses m_model
+ friend class DolphinPart; // Accesses m_model
};
/// Allow using DolphinView::Mode in QVariant
#include <QMenu>
#include <QPointer>
-DolphinViewActionHandler::DolphinViewActionHandler(KActionCollection* collection, SelectionMode::ActionTextHelper* actionTextHelper, QObject* parent) :
- QObject(parent),
- m_actionCollection(collection),
- m_currentView(nullptr),
- m_sortByActions(),
- m_visibleRoles()
+DolphinViewActionHandler::DolphinViewActionHandler(KActionCollection *collection, SelectionMode::ActionTextHelper *actionTextHelper, QObject *parent)
+ : QObject(parent)
+ , m_actionCollection(collection)
+ , m_currentView(nullptr)
+ , m_sortByActions()
+ , m_visibleRoles()
{
Q_ASSERT(m_actionCollection);
createActions(actionTextHelper);
}
-void DolphinViewActionHandler::setCurrentView(DolphinView* view)
+void DolphinViewActionHandler::setCurrentView(DolphinView *view)
{
Q_ASSERT(view);
m_currentView = view;
- connect(view, &DolphinView::modeChanged,
- this, &DolphinViewActionHandler::updateViewActions);
- connect(view, &DolphinView::previewsShownChanged,
- this, &DolphinViewActionHandler::slotPreviewsShownChanged);
- connect(view, &DolphinView::sortOrderChanged,
- this, &DolphinViewActionHandler::slotSortOrderChanged);
- connect(view, &DolphinView::sortFoldersFirstChanged,
- this, &DolphinViewActionHandler::slotSortFoldersFirstChanged);
- connect(view, &DolphinView::sortHiddenLastChanged,
- this, &DolphinViewActionHandler::slotSortHiddenLastChanged);
- connect(view, &DolphinView::visibleRolesChanged,
- this, &DolphinViewActionHandler::slotVisibleRolesChanged);
- connect(view, &DolphinView::groupedSortingChanged,
- this, &DolphinViewActionHandler::slotGroupedSortingChanged);
- connect(view, &DolphinView::hiddenFilesShownChanged,
- this, &DolphinViewActionHandler::slotHiddenFilesShownChanged);
- connect(view, &DolphinView::sortRoleChanged,
- this, &DolphinViewActionHandler::slotSortRoleChanged);
- connect(view, &DolphinView::zoomLevelChanged,
- this, &DolphinViewActionHandler::slotZoomLevelChanged);
- connect(view, &DolphinView::writeStateChanged,
- this, &DolphinViewActionHandler::slotWriteStateChanged);
- connect(view, &DolphinView::selectionModeChangeRequested,
- this, [this](bool enabled) { Q_EMIT selectionModeChangeTriggered(enabled); });
- connect(view, &DolphinView::selectionChanged,
- this, &DolphinViewActionHandler::slotSelectionChanged);
+ connect(view, &DolphinView::modeChanged, this, &DolphinViewActionHandler::updateViewActions);
+ connect(view, &DolphinView::previewsShownChanged, this, &DolphinViewActionHandler::slotPreviewsShownChanged);
+ connect(view, &DolphinView::sortOrderChanged, this, &DolphinViewActionHandler::slotSortOrderChanged);
+ connect(view, &DolphinView::sortFoldersFirstChanged, this, &DolphinViewActionHandler::slotSortFoldersFirstChanged);
+ connect(view, &DolphinView::sortHiddenLastChanged, this, &DolphinViewActionHandler::slotSortHiddenLastChanged);
+ connect(view, &DolphinView::visibleRolesChanged, this, &DolphinViewActionHandler::slotVisibleRolesChanged);
+ connect(view, &DolphinView::groupedSortingChanged, this, &DolphinViewActionHandler::slotGroupedSortingChanged);
+ connect(view, &DolphinView::hiddenFilesShownChanged, this, &DolphinViewActionHandler::slotHiddenFilesShownChanged);
+ connect(view, &DolphinView::sortRoleChanged, this, &DolphinViewActionHandler::slotSortRoleChanged);
+ connect(view, &DolphinView::zoomLevelChanged, this, &DolphinViewActionHandler::slotZoomLevelChanged);
+ connect(view, &DolphinView::writeStateChanged, this, &DolphinViewActionHandler::slotWriteStateChanged);
+ connect(view, &DolphinView::selectionModeChangeRequested, this, [this](bool enabled) {
+ Q_EMIT selectionModeChangeTriggered(enabled);
+ });
+ connect(view, &DolphinView::selectionChanged, this, &DolphinViewActionHandler::slotSelectionChanged);
slotSelectionChanged(m_currentView->selectedItems());
}
-DolphinView* DolphinViewActionHandler::currentView()
+DolphinView *DolphinViewActionHandler::currentView()
{
return m_currentView;
}
{
// This action doesn't appear in the GUI, it's for the shortcut only.
// KNewFileMenu takes care of the GUI stuff.
- QAction* newDirAction = m_actionCollection->addAction(QStringLiteral("create_dir"));
+ QAction *newDirAction = m_actionCollection->addAction(QStringLiteral("create_dir"));
newDirAction->setText(i18nc("@action", "Create Folder..."));
m_actionCollection->setDefaultShortcuts(newDirAction, KStandardShortcut::createFolder());
newDirAction->setIcon(QIcon::fromTheme(QStringLiteral("folder-new")));
- newDirAction->setEnabled(false); // Will be enabled in slotWriteStateChanged(bool) if the current URL is writable
+ newDirAction->setEnabled(false); // Will be enabled in slotWriteStateChanged(bool) if the current URL is writable
connect(newDirAction, &QAction::triggered, this, &DolphinViewActionHandler::createDirectoryTriggered);
// File menu
auto renameAction = KStandardAction::renameFile(this, &DolphinViewActionHandler::slotRename, m_actionCollection);
- renameAction->setWhatsThis(xi18nc("@info:whatsthis", "This renames the "
- "items in your current selection.<nl/>Renaming multiple items "
- "at once amounts to their new names differing only in a number."));
+ renameAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "This renames the "
+ "items in your current selection.<nl/>Renaming multiple items "
+ "at once amounts to their new names differing only in a number."));
auto trashAction = KStandardAction::moveToTrash(this, &DolphinViewActionHandler::slotTrashActivated, m_actionCollection);
auto trashShortcuts = trashAction->shortcuts();
trashShortcuts.append(QKeySequence::Delete);
m_actionCollection->setDefaultShortcuts(trashAction, trashShortcuts);
}
- trashAction->setWhatsThis(xi18nc("@info:whatsthis", "This moves the "
- "items in your current selection to the <filename>Trash"
- "</filename>.<nl/>The trash is a temporary storage where "
- "items can be deleted from if disk space is needed."));
+ trashAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "This moves the "
+ "items in your current selection to the <filename>Trash"
+ "</filename>.<nl/>The trash is a temporary storage where "
+ "items can be deleted from if disk space is needed."));
auto deleteAction = KStandardAction::deleteFile(this, &DolphinViewActionHandler::slotDeleteItems, m_actionCollection);
auto deleteShortcuts = deleteAction->shortcuts();
deleteShortcuts.append(Qt::SHIFT | Qt::Key_Delete);
m_actionCollection->setDefaultShortcuts(deleteAction, deleteShortcuts);
}
- deleteAction->setWhatsThis(xi18nc("@info:whatsthis", "This deletes "
- "the items in your current selection completely. They can "
- "not be recovered by normal means."));
+ deleteAction->setWhatsThis(xi18nc("@info:whatsthis",
+ "This deletes "
+ "the items in your current selection completely. They can "
+ "not be recovered by normal means."));
// This action is useful for being enabled when KStandardAction::MoveToTrash should be
// disabled and KStandardAction::DeleteFile is enabled (e.g. non-local files), so that Key_Del
// can be used for deleting the file (#76016). It needs to be a separate action
// so that the Edit menu isn't affected.
- QAction* deleteWithTrashShortcut = m_actionCollection->addAction(QStringLiteral("delete_shortcut"));
+ QAction *deleteWithTrashShortcut = m_actionCollection->addAction(QStringLiteral("delete_shortcut"));
// The descriptive text is just for the shortcuts editor.
deleteWithTrashShortcut->setText(i18nc("@action \"Move to Trash\" for non-local files, etc.", "Delete (using shortcut for Trash)"));
m_actionCollection->setDefaultShortcuts(deleteWithTrashShortcut, KStandardShortcut::moveToTrash());
deleteWithTrashShortcut->setEnabled(false);
connect(deleteWithTrashShortcut, &QAction::triggered, this, &DolphinViewActionHandler::slotDeleteItems);
- QAction* duplicateAction = m_actionCollection->addAction(QStringLiteral("duplicate"));
+ QAction *duplicateAction = m_actionCollection->addAction(QStringLiteral("duplicate"));
duplicateAction->setText(i18nc("@action:inmenu File", "Duplicate Here"));
duplicateAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-duplicate")));
m_actionCollection->setDefaultShortcut(duplicateAction, Qt::CTRL | Qt::Key_D);
duplicateAction->setEnabled(false);
connect(duplicateAction, &QAction::triggered, this, &DolphinViewActionHandler::slotDuplicate);
- QAction *propertiesAction = m_actionCollection->addAction( QStringLiteral("properties") );
+ QAction *propertiesAction = m_actionCollection->addAction(QStringLiteral("properties"));
// Well, it's the File menu in dolphinmainwindow and the Edit menu in dolphinpart... :)
- propertiesAction->setText( i18nc("@action:inmenu File", "Properties") );
+ propertiesAction->setText(i18nc("@action:inmenu File", "Properties"));
propertiesAction->setWhatsThis(xi18nc("@info:whatsthis properties",
- "This shows a complete list of properties of the currently "
- "selected items in a new window.<nl/>If nothing is selected the "
- "window will be about the currently viewed folder instead.<nl/>"
- "You can configure advanced options there like managing "
- "read- and write-permissions."));
+ "This shows a complete list of properties of the currently "
+ "selected items in a new window.<nl/>If nothing is selected the "
+ "window will be about the currently viewed folder instead.<nl/>"
+ "You can configure advanced options there like managing "
+ "read- and write-permissions."));
propertiesAction->setIcon(QIcon::fromTheme(QStringLiteral("document-properties")));
m_actionCollection->setDefaultShortcuts(propertiesAction, {Qt::ALT | Qt::Key_Return, Qt::ALT | Qt::Key_Enter});
connect(propertiesAction, &QAction::triggered, this, &DolphinViewActionHandler::slotProperties);
- QAction *copyPathAction = m_actionCollection->addAction( QStringLiteral("copy_location") );
+ QAction *copyPathAction = m_actionCollection->addAction(QStringLiteral("copy_location"));
copyPathAction->setText(i18nc("@action:incontextmenu", "Copy Location"));
- copyPathAction->setWhatsThis(i18nc("@info:whatsthis copy_location",
- "This will copy the path of the first selected item into the clipboard."
- ));
+ copyPathAction->setWhatsThis(i18nc("@info:whatsthis copy_location", "This will copy the path of the first selected item into the clipboard."));
copyPathAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy-path")));
m_actionCollection->setDefaultShortcuts(copyPathAction, {Qt::CTRL | Qt::ALT | Qt::Key_C});
// actions in slotSelectionChanged() after the static ones above.
// View menu
- KToggleAction* iconsAction = iconsModeAction();
- KToggleAction* compactAction = compactModeAction();
- KToggleAction* detailsAction = detailsModeAction();
+ KToggleAction *iconsAction = iconsModeAction();
+ KToggleAction *compactAction = compactModeAction();
+ KToggleAction *detailsAction = detailsModeAction();
iconsAction->setWhatsThis(xi18nc("@info:whatsthis Icons view mode",
- "<para>This switches to a view mode that focuses on the folder "
- "and file icons. This mode makes it easy to distinguish folders "
- "from files and to detect items with distinctive <emphasis>"
- "file types</emphasis>.</para><para> This mode is handy to "
- "browse through pictures when the <interface>Preview"
- "</interface> option is enabled.</para>"));
+ "<para>This switches to a view mode that focuses on the folder "
+ "and file icons. This mode makes it easy to distinguish folders "
+ "from files and to detect items with distinctive <emphasis>"
+ "file types</emphasis>.</para><para> This mode is handy to "
+ "browse through pictures when the <interface>Preview"
+ "</interface> option is enabled.</para>"));
compactAction->setWhatsThis(xi18nc("@info:whatsthis Compact view mode",
- "<para>This switches to a compact view mode that lists the folders "
- "and files in columns with the names beside the icons.</para><para>"
- "This helps to keep the overview in folders with many items.</para>"));
+ "<para>This switches to a compact view mode that lists the folders "
+ "and files in columns with the names beside the icons.</para><para>"
+ "This helps to keep the overview in folders with many items.</para>"));
detailsAction->setWhatsThis(xi18nc("@info:whatsthis Details view mode",
- "<para>This switches to a list view mode that focuses on folder "
- "and file details.</para><para>Click on a detail in the column "
- "header to sort the items by it. Click again to sort the other "
- "way around. To select which details should be displayed click "
- "the header with the right mouse button.</para><para>You can "
- "view the contents of a folder without leaving the current "
- "location by clicking to the left of it. This way you can view "
- "the contents of multiple folders in the same list.</para>"));
-
- KSelectAction* viewModeActions = m_actionCollection->add<KSelectAction>(QStringLiteral("view_mode"));
+ "<para>This switches to a list view mode that focuses on folder "
+ "and file details.</para><para>Click on a detail in the column "
+ "header to sort the items by it. Click again to sort the other "
+ "way around. To select which details should be displayed click "
+ "the header with the right mouse button.</para><para>You can "
+ "view the contents of a folder without leaving the current "
+ "location by clicking to the left of it. This way you can view "
+ "the contents of multiple folders in the same list.</para>"));
+
+ KSelectAction *viewModeActions = m_actionCollection->add<KSelectAction>(QStringLiteral("view_mode"));
viewModeActions->setText(i18nc("@action:intoolbar", "View Mode"));
viewModeActions->addAction(iconsAction);
viewModeActions->addAction(compactAction);
viewModeActions->setToolBarMode(KSelectAction::MenuMode);
connect(viewModeActions, &KSelectAction::triggered, this, &DolphinViewActionHandler::slotViewModeActionTriggered);
- QAction* zoomInAction = KStandardAction::zoomIn(this,
- &DolphinViewActionHandler::zoomIn,
- m_actionCollection);
+ QAction *zoomInAction = KStandardAction::zoomIn(this, &DolphinViewActionHandler::zoomIn, m_actionCollection);
zoomInAction->setWhatsThis(i18nc("@info:whatsthis zoom in", "This increases the icon size."));
- QAction* zoomResetAction = m_actionCollection->addAction(QStringLiteral("view_zoom_reset"));
+ QAction *zoomResetAction = m_actionCollection->addAction(QStringLiteral("view_zoom_reset"));
zoomResetAction->setText(i18nc("@action:inmenu View", "Reset Zoom Level"));
zoomResetAction->setToolTip(i18n("Zoom To Default"));
zoomResetAction->setWhatsThis(i18nc("@info:whatsthis zoom reset", "This resets the icon size to default."));
m_actionCollection->setDefaultShortcuts(zoomResetAction, {Qt::CTRL | Qt::Key_0});
connect(zoomResetAction, &QAction::triggered, this, &DolphinViewActionHandler::zoomReset);
- QAction* zoomOutAction = KStandardAction::zoomOut(this,
- &DolphinViewActionHandler::zoomOut,
- m_actionCollection);
+ QAction *zoomOutAction = KStandardAction::zoomOut(this, &DolphinViewActionHandler::zoomOut, m_actionCollection);
zoomOutAction->setWhatsThis(i18nc("@info:whatsthis zoom out", "This reduces the icon size."));
- KActionMenu* zoomMenu = m_actionCollection->add<KActionMenu>(QStringLiteral("zoom"));
+ KActionMenu *zoomMenu = m_actionCollection->add<KActionMenu>(QStringLiteral("zoom"));
zoomMenu->setText(i18nc("@action:inmenu menu of zoom actions", "Zoom"));
zoomMenu->setIcon(QIcon::fromTheme(QStringLiteral("zoom")));
zoomMenu->setPopupMode(QToolButton::InstantPopup);
zoomMenu->addAction(zoomResetAction);
zoomMenu->addAction(zoomOutAction);
- KToggleAction* showPreview = m_actionCollection->add<KToggleAction>(QStringLiteral("show_preview"));
+ KToggleAction *showPreview = m_actionCollection->add<KToggleAction>(QStringLiteral("show_preview"));
showPreview->setText(i18nc("@action:intoolbar", "Show Previews"));
showPreview->setToolTip(i18nc("@info", "Show preview of files and folders"));
- showPreview->setWhatsThis(xi18nc("@info:whatsthis", "When this is "
- "enabled, the icons are based on the actual file or folder "
- "contents.<nl/>For example the icons of images become scaled "
- "down versions of the images."));
+ showPreview->setWhatsThis(xi18nc("@info:whatsthis",
+ "When this is "
+ "enabled, the icons are based on the actual file or folder "
+ "contents.<nl/>For example the icons of images become scaled "
+ "down versions of the images."));
showPreview->setIcon(QIcon::fromTheme(QStringLiteral("view-preview")));
connect(showPreview, &KToggleAction::triggered, this, &DolphinViewActionHandler::togglePreview);
- KToggleAction* sortFoldersFirst = m_actionCollection->add<KToggleAction>(QStringLiteral("folders_first"));
+ KToggleAction *sortFoldersFirst = m_actionCollection->add<KToggleAction>(QStringLiteral("folders_first"));
sortFoldersFirst->setText(i18nc("@action:inmenu Sort", "Folders First"));
connect(sortFoldersFirst, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleSortFoldersFirst);
- KToggleAction* sortHiddenLast = m_actionCollection->add<KToggleAction>(QStringLiteral("hidden_last"));
+ KToggleAction *sortHiddenLast = m_actionCollection->add<KToggleAction>(QStringLiteral("hidden_last"));
sortHiddenLast->setText(i18nc("@action:inmenu Sort", "Hidden Files Last"));
connect(sortHiddenLast, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleSortHiddenLast);
// View -> Sort By
- QActionGroup* sortByActionGroup = createFileItemRolesActionGroup(QStringLiteral("sort_by_"));
+ QActionGroup *sortByActionGroup = createFileItemRolesActionGroup(QStringLiteral("sort_by_"));
- KActionMenu* sortByActionMenu = m_actionCollection->add<KActionMenu>(QStringLiteral("sort"));
+ KActionMenu *sortByActionMenu = m_actionCollection->add<KActionMenu>(QStringLiteral("sort"));
sortByActionMenu->setIcon(QIcon::fromTheme(QStringLiteral("view-sort")));
sortByActionMenu->setText(i18nc("@action:inmenu View", "Sort By"));
sortByActionMenu->setPopupMode(QToolButton::InstantPopup);
const auto sortByActionGroupActions = sortByActionGroup->actions();
- for (QAction* action : sortByActionGroupActions) {
+ for (QAction *action : sortByActionGroupActions) {
sortByActionMenu->addAction(action);
}
sortByActionMenu->addSeparator();
- QActionGroup* group = new QActionGroup(sortByActionMenu);
+ QActionGroup *group = new QActionGroup(sortByActionMenu);
group->setExclusive(true);
- KToggleAction* ascendingAction = m_actionCollection->add<KToggleAction>(QStringLiteral("ascending"));
+ KToggleAction *ascendingAction = m_actionCollection->add<KToggleAction>(QStringLiteral("ascending"));
ascendingAction->setActionGroup(group);
connect(ascendingAction, &QAction::triggered, this, [this] {
m_currentView->setSortOrder(Qt::AscendingOrder);
});
- KToggleAction* descendingAction = m_actionCollection->add<KToggleAction>(QStringLiteral("descending"));
+ KToggleAction *descendingAction = m_actionCollection->add<KToggleAction>(QStringLiteral("descending"));
descendingAction->setActionGroup(group);
connect(descendingAction, &QAction::triggered, this, [this] {
m_currentView->setSortOrder(Qt::DescendingOrder);
sortByActionMenu->addAction(sortHiddenLast);
// View -> Additional Information
- QActionGroup* visibleRolesGroup = createFileItemRolesActionGroup(QStringLiteral("show_"));
+ QActionGroup *visibleRolesGroup = createFileItemRolesActionGroup(QStringLiteral("show_"));
- KActionMenu* visibleRolesMenu = m_actionCollection->add<KActionMenu>(QStringLiteral("additional_info"));
+ KActionMenu *visibleRolesMenu = m_actionCollection->add<KActionMenu>(QStringLiteral("additional_info"));
visibleRolesMenu->setText(i18nc("@action:inmenu View", "Show Additional Information"));
visibleRolesMenu->setIcon(QIcon::fromTheme(QStringLiteral("documentinfo")));
visibleRolesMenu->setPopupMode(QToolButton::InstantPopup);
const auto visibleRolesGroupActions = visibleRolesGroup->actions();
- for (QAction* action : visibleRolesGroupActions) {
+ for (QAction *action : visibleRolesGroupActions) {
visibleRolesMenu->addAction(action);
}
- KToggleAction* showInGroups = m_actionCollection->add<KToggleAction>(QStringLiteral("show_in_groups"));
+ KToggleAction *showInGroups = m_actionCollection->add<KToggleAction>(QStringLiteral("show_in_groups"));
showInGroups->setIcon(QIcon::fromTheme(QStringLiteral("view-group")));
showInGroups->setText(i18nc("@action:inmenu View", "Show in Groups"));
showInGroups->setWhatsThis(i18nc("@info:whatsthis", "This groups files and folders by their first letter."));
connect(showInGroups, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleGroupedSorting);
- KToggleAction* showHiddenFiles = m_actionCollection->add<KToggleAction>(QStringLiteral("show_hidden_files"));
+ KToggleAction *showHiddenFiles = m_actionCollection->add<KToggleAction>(QStringLiteral("show_hidden_files"));
showHiddenFiles->setIcon(QIcon::fromTheme(QStringLiteral("view-visible")));
showHiddenFiles->setText(i18nc("@action:inmenu View", "Show Hidden Files"));
- showHiddenFiles->setWhatsThis(xi18nc("@info:whatsthis", "<para>When "
- "this is enabled <emphasis>hidden</emphasis> files and folders "
- "are visible. They will be displayed semi-transparent.</para>"
- "<para>Hidden items only differ from other ones in that their "
- "name starts with a \".\". In general there is no need for "
- "users to access them which is why they are hidden.</para>"));
+ showHiddenFiles->setWhatsThis(xi18nc("@info:whatsthis",
+ "<para>When "
+ "this is enabled <emphasis>hidden</emphasis> files and folders "
+ "are visible. They will be displayed semi-transparent.</para>"
+ "<para>Hidden items only differ from other ones in that their "
+ "name starts with a \".\". In general there is no need for "
+ "users to access them which is why they are hidden.</para>"));
m_actionCollection->setDefaultShortcuts(showHiddenFiles, KStandardShortcut::showHideHiddenFiles());
connect(showHiddenFiles, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleShowHiddenFiles);
- QAction* adjustViewProps = m_actionCollection->addAction(QStringLiteral("view_properties"));
+ QAction *adjustViewProps = m_actionCollection->addAction(QStringLiteral("view_properties"));
adjustViewProps->setText(i18nc("@action:inmenu View", "Adjust View Display Style..."));
adjustViewProps->setIcon(QIcon::fromTheme(QStringLiteral("view-choose")));
- adjustViewProps->setWhatsThis(i18nc("@info:whatsthis", "This opens a window "
- "in which all folder view properties can be adjusted."));
+ adjustViewProps->setWhatsThis(i18nc("@info:whatsthis",
+ "This opens a window "
+ "in which all folder view properties can be adjusted."));
connect(adjustViewProps, &QAction::triggered, this, &DolphinViewActionHandler::slotAdjustViewProperties);
}
-QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QString& groupPrefix)
+QActionGroup *DolphinViewActionHandler::createFileItemRolesActionGroup(const QString &groupPrefix)
{
const bool isSortGroup = (groupPrefix == QLatin1String("sort_by_"));
Q_ASSERT(isSortGroup || groupPrefix == QLatin1String("show_"));
- QActionGroup* rolesActionGroup = new QActionGroup(m_actionCollection);
+ QActionGroup *rolesActionGroup = new QActionGroup(m_actionCollection);
rolesActionGroup->setExclusive(isSortGroup);
if (isSortGroup) {
- connect(rolesActionGroup, &QActionGroup::triggered,
- this, &DolphinViewActionHandler::slotSortTriggered);
+ connect(rolesActionGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::slotSortTriggered);
} else {
- connect(rolesActionGroup, &QActionGroup::triggered,
- this, &DolphinViewActionHandler::toggleVisibleRole);
+ connect(rolesActionGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::toggleVisibleRole);
}
QString groupName;
- KActionMenu* groupMenu = nullptr;
- QActionGroup* groupMenuGroup = nullptr;
+ KActionMenu *groupMenu = nullptr;
+ QActionGroup *groupMenuGroup = nullptr;
bool indexingEnabled = false;
#if HAVE_BALOO
#endif
const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
- for (const KFileItemModel::RoleInfo& info : rolesInfo) {
+ for (const KFileItemModel::RoleInfo &info : rolesInfo) {
if (!isSortGroup && info.role == "text") {
// It should not be possible to hide the "text" role
continue;
}
- KToggleAction* action = nullptr;
+ KToggleAction *action = nullptr;
const QString name = groupPrefix + info.role;
if (info.group.isEmpty()) {
action = m_actionCollection->add<KToggleAction>(name);
groupMenuGroup = new QActionGroup(groupMenu);
groupMenuGroup->setExclusive(isSortGroup);
if (isSortGroup) {
- connect(groupMenuGroup, &QActionGroup::triggered,
- this, &DolphinViewActionHandler::slotSortTriggered);
+ connect(groupMenuGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::slotSortTriggered);
} else {
- connect(groupMenuGroup, &QActionGroup::triggered,
- this, &DolphinViewActionHandler::toggleVisibleRole);
+ connect(groupMenuGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::toggleVisibleRole);
}
}
action->setText(info.translation);
action->setData(info.role);
- const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
- (info.requiresBaloo) ||
- (info.requiresIndexer && indexingEnabled);
+ const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled);
action->setEnabled(enable);
if (isSortGroup) {
return rolesActionGroup;
}
-void DolphinViewActionHandler::slotViewModeActionTriggered(QAction* action)
+void DolphinViewActionHandler::slotViewModeActionTriggered(QAction *action)
{
const DolphinView::Mode mode = action->data().value<DolphinView::Mode>();
m_currentView->setViewMode(mode);
- QAction* viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode"));
+ QAction *viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode"));
viewModeMenu->setIcon(action->icon());
}
return QString(); // can't happen
}
-KActionCollection* DolphinViewActionHandler::actionCollection()
+KActionCollection *DolphinViewActionHandler::actionCollection()
{
return m_actionCollection;
}
void DolphinViewActionHandler::updateViewActions()
{
- QAction* viewModeAction = m_actionCollection->action(currentViewModeActionName());
+ QAction *viewModeAction = m_actionCollection->action(currentViewModeActionName());
if (viewModeAction) {
viewModeAction->setChecked(true);
- QAction* viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode"));
+ QAction *viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode"));
viewModeMenu->setIcon(viewModeAction->icon());
}
- QAction* showPreviewAction = m_actionCollection->action(QStringLiteral("show_preview"));
+ QAction *showPreviewAction = m_actionCollection->action(QStringLiteral("show_preview"));
showPreviewAction->setChecked(m_currentView->previewsShown());
slotSortOrderChanged(m_currentView->sortOrder());
void DolphinViewActionHandler::slotSortOrderChanged(Qt::SortOrder order)
{
- QAction* descending = m_actionCollection->action(QStringLiteral("descending"));
- QAction* ascending = m_actionCollection->action(QStringLiteral("ascending"));
+ QAction *descending = m_actionCollection->action(QStringLiteral("descending"));
+ QAction *ascending = m_actionCollection->action(QStringLiteral("ascending"));
const bool sortDescending = (order == Qt::DescendingOrder);
descending->setChecked(sortDescending);
ascending->setChecked(!sortDescending);
m_actionCollection->action(QStringLiteral("hidden_last"))->setChecked(hiddenLast);
}
-void DolphinViewActionHandler::toggleVisibleRole(QAction* action)
+void DolphinViewActionHandler::toggleVisibleRole(QAction *action)
{
Q_EMIT actionBeingHandled();
}
}
-void DolphinViewActionHandler::slotVisibleRolesChanged(const QList<QByteArray>& current,
- const QList<QByteArray>& previous)
+void DolphinViewActionHandler::slotVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous)
{
Q_UNUSED(previous)
const auto checkedRoles = QSet<QByteArray>(current.constBegin(), current.constEnd());
- QHashIterator<QByteArray, KToggleAction*> it(m_visibleRoles);
+ QHashIterator<QByteArray, KToggleAction *> it(m_visibleRoles);
while (it.hasNext()) {
it.next();
- const QByteArray& role = it.key();
- KToggleAction* action = it.value();
+ const QByteArray &role = it.key();
+ KToggleAction *action = it.value();
action->setChecked(checkedRoles.contains(role));
}
}
void DolphinViewActionHandler::slotGroupedSortingChanged(bool groupedSorting)
{
- QAction* showInGroupsAction = m_actionCollection->action(QStringLiteral("show_in_groups"));
+ QAction *showInGroupsAction = m_actionCollection->action(QStringLiteral("show_in_groups"));
showInGroupsAction->setChecked(groupedSorting);
}
void DolphinViewActionHandler::slotHiddenFilesShownChanged(bool shown)
{
- QAction* showHiddenFilesAction = m_actionCollection->action(QStringLiteral("show_hidden_files"));
+ QAction *showHiddenFilesAction = m_actionCollection->action(QStringLiteral("show_hidden_files"));
showHiddenFilesAction->setChecked(shown);
}
void DolphinViewActionHandler::slotWriteStateChanged(bool isFolderWritable)
{
- m_actionCollection->action(QStringLiteral("create_dir"))->setEnabled(isFolderWritable &&
- KProtocolManager::supportsMakeDir(currentView()->url()));
+ m_actionCollection->action(QStringLiteral("create_dir"))->setEnabled(isFolderWritable && KProtocolManager::supportsMakeDir(currentView()->url()));
}
-KToggleAction* DolphinViewActionHandler::iconsModeAction()
+KToggleAction *DolphinViewActionHandler::iconsModeAction()
{
- KToggleAction* iconsView = m_actionCollection->add<KToggleAction>(QStringLiteral("icons"));
+ KToggleAction *iconsView = m_actionCollection->add<KToggleAction>(QStringLiteral("icons"));
iconsView->setText(i18nc("@action:inmenu View Mode", "Icons"));
iconsView->setToolTip(i18nc("@info", "Icons view mode"));
m_actionCollection->setDefaultShortcut(iconsView, Qt::CTRL | Qt::Key_1);
return iconsView;
}
-KToggleAction* DolphinViewActionHandler::compactModeAction()
+KToggleAction *DolphinViewActionHandler::compactModeAction()
{
- KToggleAction* iconsView = m_actionCollection->add<KToggleAction>(QStringLiteral("compact"));
+ KToggleAction *iconsView = m_actionCollection->add<KToggleAction>(QStringLiteral("compact"));
iconsView->setText(i18nc("@action:inmenu View Mode", "Compact"));
iconsView->setToolTip(i18nc("@info", "Compact view mode"));
m_actionCollection->setDefaultShortcut(iconsView, Qt::CTRL | Qt::Key_2);
return iconsView;
}
-KToggleAction* DolphinViewActionHandler::detailsModeAction()
+KToggleAction *DolphinViewActionHandler::detailsModeAction()
{
- KToggleAction* detailsView = m_actionCollection->add<KToggleAction>(QStringLiteral("details"));
+ KToggleAction *detailsView = m_actionCollection->add<KToggleAction>(QStringLiteral("details"));
detailsView->setText(i18nc("@action:inmenu View Mode", "Details"));
detailsView->setToolTip(i18nc("@info", "Details view mode"));
m_actionCollection->setDefaultShortcut(detailsView, Qt::CTRL | Qt::Key_3);
return detailsView;
}
-void DolphinViewActionHandler::slotSortRoleChanged(const QByteArray& role)
+void DolphinViewActionHandler::slotSortRoleChanged(const QByteArray &role)
{
- KToggleAction* action = m_sortByActions.value(role);
+ KToggleAction *action = m_sortByActions.value(role);
if (action) {
action->setChecked(true);
if (!action->icon().isNull()) {
- QAction* sortByMenu = m_actionCollection->action(QStringLiteral("sort"));
+ QAction *sortByMenu = m_actionCollection->action(QStringLiteral("sort"));
sortByMenu->setIcon(action->icon());
}
}
- QAction* descending = m_actionCollection->action(QStringLiteral("descending"));
- QAction* ascending = m_actionCollection->action(QStringLiteral("ascending"));
+ QAction *descending = m_actionCollection->action(QStringLiteral("descending"));
+ QAction *ascending = m_actionCollection->action(QStringLiteral("ascending"));
if (role == "text" || role == "type" || role == "extension" || role == "tags" || role == "comment") {
descending->setText(i18nc("Sort descending", "Z-A"));
{
Q_UNUSED(previous)
- QAction* zoomInAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomIn));
+ QAction *zoomInAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomIn));
if (zoomInAction) {
zoomInAction->setEnabled(current < ZoomLevelInfo::maximumLevel());
}
- QAction* zoomOutAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomOut));
+ QAction *zoomOutAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomOut));
if (zoomOutAction) {
zoomOutAction->setEnabled(current > ZoomLevelInfo::minimumLevel());
}
}
-void DolphinViewActionHandler::slotSortTriggered(QAction* action)
+void DolphinViewActionHandler::slotSortTriggered(QAction *action)
{
// The radiobuttons of the "Sort By"-menu are split between the main-menu
// and several sub-menus. Because of this they don't have a common
// be assured that all other actions get unchecked, except the ascending/
// descending actions
for (QAction *groupAction : qAsConst(m_sortByActions)) {
- KActionMenu* actionMenu = qobject_cast<KActionMenu*>(groupAction);
+ KActionMenu *actionMenu = qobject_cast<KActionMenu *>(groupAction);
if (actionMenu) {
const auto actions = actionMenu->menu()->actions();
- for (QAction* subAction : actions) {
+ for (QAction *subAction : actions) {
subAction->setChecked(false);
}
} else if (groupAction->actionGroup()) {
void DolphinViewActionHandler::slotProperties()
{
- KPropertiesDialog* dialog = nullptr;
+ KPropertiesDialog *dialog = nullptr;
const KFileItemList list = m_currentView->selectedItems();
if (list.isEmpty()) {
const QUrl url = m_currentView->url();
}
}
-void DolphinViewActionHandler::slotSelectionChanged(const KFileItemList& selection)
+void DolphinViewActionHandler::slotSelectionChanged(const KFileItemList &selection)
{
QString basicActionsMenuText;
if (selection.isEmpty()) {
- basicActionsMenuText =
- i18nc("@action:inmenu menu with actions like copy, paste, rename. The user's selection is empty when this text is shown.",
- "Actions for Current View");
+ basicActionsMenuText = i18nc("@action:inmenu menu with actions like copy, paste, rename. The user's selection is empty when this text is shown.",
+ "Actions for Current View");
} else {
+ // clang-format off
QFontMetrics fontMetrics = QMenu().fontMetrics();
// i18n: @action:inmenu menu with actions like copy, paste, rename.
// %1 is a textual representation of the currently selected files or folders. This can be the name of
// If this sort of word puzzle can not be correctly translated in your language, translate it as "NULL" (without the quotes)
// and a fallback will be used.
basicActionsMenuText = i18n("Actions for %1", fileItemListToString(selection, fontMetrics.averageCharWidth() * 40, fontMetrics, ItemsState::Selected));
+ // clang-format on
}
if (basicActionsMenuText == QStringLiteral("NULL")) {
const KFileItemListProperties properties(selection);
- basicActionsMenuText =
- i18ncp("@action:inmenu menu with actions like copy, paste, rename. %1 is the amount of selected files/folders.",
- "Actions for One Selected Item", "Actions for %1 Selected Items", selection.count());
+ basicActionsMenuText = i18ncp("@action:inmenu menu with actions like copy, paste, rename. %1 is the amount of selected files/folders.",
+ "Actions for One Selected Item",
+ "Actions for %1 Selected Items",
+ selection.count());
}
QAction *basicActionsMenu = m_actionCollection->action(QStringLiteral("basic_actions"));
* SPDX-License-Identifier: GPL-2.0-or-later
*/
-
#ifndef DOLPHINVIEWACTIONHANDLER_H
#define DOLPHINVIEWACTIONHANDLER_H
class DolphinView;
class KActionCollection;
class KFileItemList;
-namespace SelectionMode {
- class ActionTextHelper;
+namespace SelectionMode
+{
+class ActionTextHelper;
}
/**
Q_OBJECT
public:
- explicit DolphinViewActionHandler(KActionCollection* collection, SelectionMode::ActionTextHelper* actionTextHelper, QObject* parent);
+ explicit DolphinViewActionHandler(KActionCollection *collection, SelectionMode::ActionTextHelper *actionTextHelper, QObject *parent);
/**
* Sets the view that this action handler should work on.
*/
- void setCurrentView(DolphinView* view);
+ void setCurrentView(DolphinView *view);
/**
* Returns the view that this action handler should work on.
*/
- DolphinView* currentView();
+ DolphinView *currentView();
/**
* Returns the name of the action for the current viewmode
/**
* Returns m_actionCollection
*/
- KActionCollection* actionCollection();
+ KActionCollection *actionCollection();
public Q_SLOTS:
/**
/**
* Emitted when the user requested a change of view mode
*/
- void slotViewModeActionTriggered(QAction*);
+ void slotViewModeActionTriggered(QAction *);
/**
* Let the user input a name for the selected item(s) and trigger
/** Decreases the size of the current set view mode. */
void zoomOut();
-
+
/** Resets the size of the current set view mode to default. */
void zoomReset();
/**
* Updates the state of the 'Sort by' actions.
*/
- void slotSortRoleChanged(const QByteArray& role);
+ void slotSortRoleChanged(const QByteArray &role);
/**
* Updates the state of the 'Zoom In' and 'Zoom Out' actions.
* Switches on or off the displaying of additional information
* as specified by \a action.
*/
- void toggleVisibleRole(QAction* action);
+ void toggleVisibleRole(QAction *action);
/**
* Changes the sorting of the current view.
*/
- void slotSortTriggered(QAction*);
+ void slotSortTriggered(QAction *);
/**
* Updates the state of the 'Additional Information' actions.
*/
- void slotVisibleRolesChanged(const QList<QByteArray>& current,
- const QList<QByteArray>& previous);
+ void slotVisibleRolesChanged(const QList<QByteArray> ¤t, const QList<QByteArray> &previous);
/**
* Switches between sorting by groups or not.
* The name is changed to something like "Actions for 3 Selected Items" to be extra
* explicit of how these basic actions are used.
*/
- void slotSelectionChanged(const KFileItemList& selection);
+ void slotSelectionChanged(const KFileItemList &selection);
private:
/**
* The changes of actions are reported to slotSortTriggered() or
* toggleAdditionalInfo().
*/
- QActionGroup* createFileItemRolesActionGroup(const QString& groupPrefix);
+ QActionGroup *createFileItemRolesActionGroup(const QString &groupPrefix);
/**
* Returns the "switch to icons mode" action.
* Helper method for createActions();
*/
- KToggleAction* iconsModeAction();
+ KToggleAction *iconsModeAction();
/**
* Returns the "switch to compact mode" action.
* Helper method for createActions();
*/
- KToggleAction* compactModeAction();
+ KToggleAction *compactModeAction();
/**
* Returns the "switch to details mode" action.
* Helper method for createActions();
*/
- KToggleAction* detailsModeAction();
+ KToggleAction *detailsModeAction();
- KActionCollection* m_actionCollection;
- DolphinView* m_currentView;
+ KActionCollection *m_actionCollection;
+ DolphinView *m_currentView;
- QHash<QByteArray, KToggleAction*> m_sortByActions;
- QHash<QByteArray, KToggleAction*> m_visibleRoles;
+ QHash<QByteArray, KToggleAction *> m_sortByActions;
+ QHash<QByteArray, KToggleAction *> m_visibleRoles;
};
#endif /* DOLPHINVIEWACTIONHANDLER_H */
QHash<QUrl, bool> DragAndDropHelper::m_urlListMatchesUrlCache;
-bool DragAndDropHelper::urlListMatchesUrl(const QList<QUrl>& urls, const QUrl& destUrl)
+bool DragAndDropHelper::urlListMatchesUrl(const QList<QUrl> &urls, const QUrl &destUrl)
{
auto iteratorResult = m_urlListMatchesUrlCache.constFind(destUrl);
if (iteratorResult != m_urlListMatchesUrlCache.constEnd()) {
return *iteratorResult;
}
- const bool destUrlMatches =
- std::find_if(urls.constBegin(), urls.constEnd(), [destUrl](const QUrl& url) {
- return url.matches(destUrl, QUrl::StripTrailingSlash);
- }) != urls.constEnd();
+ const bool destUrlMatches = std::find_if(urls.constBegin(),
+ urls.constEnd(),
+ [destUrl](const QUrl &url) {
+ return url.matches(destUrl, QUrl::StripTrailingSlash);
+ })
+ != urls.constEnd();
return *m_urlListMatchesUrlCache.insert(destUrl, destUrlMatches);
}
-KIO::DropJob* DragAndDropHelper::dropUrls(const QUrl& destUrl, QDropEvent* event, QWidget* window)
+KIO::DropJob *DragAndDropHelper::dropUrls(const QUrl &destUrl, QDropEvent *event, QWidget *window)
{
- const QMimeData* mimeData = event->mimeData();
+ const QMimeData *mimeData = event->mimeData();
if (isArkDndMimeType(mimeData)) {
const QString remoteDBusClient = mimeData->data(arkDndServiceMimeType());
const QString remoteDBusPath = mimeData->data(arkDndPathMimeType());
- QDBusMessage message = QDBusMessage::createMethodCall(remoteDBusClient, remoteDBusPath,
- QStringLiteral("org.kde.ark.DndExtract"), QStringLiteral("extractSelectedFilesTo"));
+ QDBusMessage message = QDBusMessage::createMethodCall(remoteDBusClient,
+ remoteDBusPath,
+ QStringLiteral("org.kde.ark.DndExtract"),
+ QStringLiteral("extractSelectedFilesTo"));
message.setArguments({destUrl.toDisplayString(QUrl::PreferLocalFile)});
QDBusConnection::sessionBus().call(message);
} else {
bool DragAndDropHelper::isArkDndMimeType(const QMimeData *mimeData)
{
- return mimeData->hasFormat(arkDndServiceMimeType())
- && mimeData->hasFormat(arkDndPathMimeType());
+ return mimeData->hasFormat(arkDndServiceMimeType()) && mimeData->hasFormat(arkDndPathMimeType());
}
class QDropEvent;
class QMimeData;
class QWidget;
-namespace KIO { class DropJob; }
+namespace KIO
+{
+class DropJob;
+}
class DOLPHIN_EXPORT DragAndDropHelper
{
* @return KIO::DropJob pointer or null in case the destUrl is contained
* in the mimeData url list.
*/
- static KIO::DropJob* dropUrls(const QUrl& destUrl,
- QDropEvent* event,
- QWidget *window);
+ static KIO::DropJob *dropUrls(const QUrl &destUrl, QDropEvent *event, QWidget *window);
/**
* @return True if destUrl is contained in the urls parameter.
*/
- static bool urlListMatchesUrl(const QList<QUrl>& urls, const QUrl& destUrl);
+ static bool urlListMatchesUrl(const QList<QUrl> &urls, const QUrl &destUrl);
/**
* @return True if mimeData contains Ark's drag and drop mime types.
*/
static bool isArkDndMimeType(const QMimeData *mimeData);
- static QString arkDndServiceMimeType() { return QStringLiteral("application/x-kde-ark-dndextract-service"); }
- static QString arkDndPathMimeType() { return QStringLiteral("application/x-kde-ark-dndextract-path"); }
+ static QString arkDndServiceMimeType()
+ {
+ return QStringLiteral("application/x-kde-ark-dndextract-service");
+ }
+ static QString arkDndPathMimeType()
+ {
+ return QStringLiteral("application/x-kde-ark-dndextract-path");
+ }
/**
* clear the internal cache.
*/
static void clearUrlListMatchesUrlCache();
+
private:
/**
* Stores the results of the expensive checks made in urlListMatchesUrl.
#include "dolphinfilemetadatawidget.h"
+#include <Baloo/FileMetaDataWidget>
#include <KColorScheme>
#include <KSeparator>
#include <KStringHandler>
-#include <Baloo/FileMetaDataWidget>
#include <QLabel>
#include <QStyleOptionFrame>
#include <QTextLayout>
#include <QVBoxLayout>
-DolphinFileMetaDataWidget::DolphinFileMetaDataWidget(QWidget* parent) :
- QWidget(parent),
- m_preview(nullptr),
- m_name(nullptr),
- m_fileMetaDataWidget(nullptr)
+DolphinFileMetaDataWidget::DolphinFileMetaDataWidget(QWidget *parent)
+ : QWidget(parent)
+ , m_preview(nullptr)
+ , m_name(nullptr)
+ , m_fileMetaDataWidget(nullptr)
{
// Create widget for file preview
m_preview = new QLabel(this);
// Create widget for the meta data
m_fileMetaDataWidget = new Baloo::FileMetaDataWidget(this);
- connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::metaDataRequestFinished,
- this, &DolphinFileMetaDataWidget::metaDataRequestFinished);
- connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::urlActivated,
- this, &DolphinFileMetaDataWidget::urlActivated);
+ connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::metaDataRequestFinished, this, &DolphinFileMetaDataWidget::metaDataRequestFinished);
+ connect(m_fileMetaDataWidget, &Baloo::FileMetaDataWidget::urlActivated, this, &DolphinFileMetaDataWidget::urlActivated);
m_fileMetaDataWidget->setForegroundRole(QPalette::ToolTipText);
m_fileMetaDataWidget->setReadOnly(true);
- QVBoxLayout* textLayout = new QVBoxLayout();
+ QVBoxLayout *textLayout = new QVBoxLayout();
textLayout->addWidget(m_name);
textLayout->addWidget(new KSeparator());
textLayout->addWidget(m_fileMetaDataWidget);
// (see bug #241608)
textLayout->addStretch();
- QHBoxLayout* layout = new QHBoxLayout(this);
+ QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(m_preview);
layout->addSpacing(layout->contentsMargins().left());
layout->addLayout(textLayout);
{
}
-void DolphinFileMetaDataWidget::setPreview(const QPixmap& pixmap)
+void DolphinFileMetaDataWidget::setPreview(const QPixmap &pixmap)
{
m_preview->setPixmap(pixmap);
}
return QPixmap();
}
-void DolphinFileMetaDataWidget::setName(const QString& name)
+void DolphinFileMetaDataWidget::setName(const QString &name)
{
QTextOption textOption;
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
return m_name->text();
}
-void DolphinFileMetaDataWidget::setItems(const KFileItemList& items)
+void DolphinFileMetaDataWidget::setItems(const KFileItemList &items)
{
m_fileMetaDataWidget->setItems(items);
}
{
return m_fileMetaDataWidget->items();
}
-
class KFileItemList;
class QLabel;
-namespace Baloo {
- class FileMetaDataWidget;
+namespace Baloo
+{
+class FileMetaDataWidget;
}
/**
Q_OBJECT
public:
- explicit DolphinFileMetaDataWidget(QWidget* parent = nullptr);
+ explicit DolphinFileMetaDataWidget(QWidget *parent = nullptr);
~DolphinFileMetaDataWidget() override;
- void setPreview(const QPixmap& pixmap);
+ void setPreview(const QPixmap &pixmap);
QPixmap preview() const;
- void setName(const QString& name);
+ void setName(const QString &name);
QString name() const;
/**
* The signal metaDataRequestFinished() will be emitted,
* as soon as the meta data for the items has been received.
*/
- void setItems(const KFileItemList& items);
+ void setItems(const KFileItemList &items);
KFileItemList items() const;
Q_SIGNALS:
* Is emitted after the meta data has been received for the items
* set by DolphinFileMetaDataWidget::setItems().
*/
- void metaDataRequestFinished(const KFileItemList& items);
+ void metaDataRequestFinished(const KFileItemList &items);
/**
* Is emitted when the user clicks a tag or a link
* in the metadata widget.
*/
- void urlActivated(const QUrl& url);
+ void urlActivated(const QUrl &url);
private:
- QLabel* m_preview;
- QLabel* m_name;
- Baloo::FileMetaDataWidget* m_fileMetaDataWidget;
+ QLabel *m_preview;
+ QLabel *m_name;
+ Baloo::FileMetaDataWidget *m_fileMetaDataWidget;
};
#endif
#include "dolphinfilemetadatawidget.h"
-#include <KIO/PreviewJob>
#include <KConfigGroup>
+#include <KIO/PreviewJob>
+#include <KIconLoader>
#include <KJobWidgets>
#include <KSharedConfig>
#include <KToolTipWidget>
-#include <KIconLoader>
#include <QApplication>
#include <QStyle>
#include <QTimer>
#include <QWindow>
-class IconLoaderSingleton {
+class IconLoaderSingleton
+{
public:
IconLoaderSingleton() = default;
Q_GLOBAL_STATIC(IconLoaderSingleton, iconLoader)
-ToolTipManager::ToolTipManager(QWidget* parent) :
- QObject(parent),
- m_showToolTipTimer(nullptr),
- m_contentRetrievalTimer(nullptr),
- m_transientParent(nullptr),
- m_toolTipRequested(false),
- m_metaDataRequested(false),
- m_appliedWaitCursor(false),
- m_margin(4),
- m_item(),
- m_itemRect()
+ToolTipManager::ToolTipManager(QWidget *parent)
+ : QObject(parent)
+ , m_showToolTipTimer(nullptr)
+ , m_contentRetrievalTimer(nullptr)
+ , m_transientParent(nullptr)
+ , m_toolTipRequested(false)
+ , m_metaDataRequested(false)
+ , m_appliedWaitCursor(false)
+ , m_margin(4)
+ , m_item()
+ , m_itemRect()
{
if (parent) {
m_margin = qMax(m_margin, parent->style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth));
}
}
-void ToolTipManager::showToolTip(const KFileItem& item, const QRectF& itemRect, QWindow *transientParent)
+void ToolTipManager::showToolTip(const KFileItem &item, const QRectF &itemRect, QWindow *transientParent)
{
hideToolTip(HideBehavior::Instantly);
const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
const QStringList plugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
- KIO::PreviewJob* job = new KIO::PreviewJob(KFileItemList() << m_item,
- QSize(256, 256),
- &plugins);
+ KIO::PreviewJob *job = new KIO::PreviewJob(KFileItemList() << m_item, QSize(256, 256), &plugins);
job->setIgnoreMaximumSize(m_item.isLocalFile() && !m_item.isSlow());
if (job->uiDelegate()) {
KJobWidgets::setWindow(job, qApp->activeWindow());
}
- connect(job, &KIO::PreviewJob::gotPreview,
- this, &ToolTipManager::setPreviewPix);
- connect(job, &KIO::PreviewJob::failed,
- this, &ToolTipManager::previewFailed);
+ connect(job, &KIO::PreviewJob::gotPreview, this, &ToolTipManager::setPreviewPix);
+ connect(job, &KIO::PreviewJob::failed, this, &ToolTipManager::previewFailed);
}
-
-void ToolTipManager::setPreviewPix(const KFileItem& item,
- const QPixmap& pixmap)
+void ToolTipManager::setPreviewPix(const KFileItem &item, const QPixmap &pixmap)
{
if (!m_toolTipRequested || (m_item.url() != item.url())) {
// No tooltip is requested anymore or an old preview has been received
return;
}
QPalette pal;
- for (auto state : { QPalette::Active, QPalette::Inactive, QPalette::Disabled }) {
+ for (auto state : {QPalette::Active, QPalette::Inactive, QPalette::Disabled}) {
pal.setBrush(state, QPalette::WindowText, pal.toolTipText());
pal.setBrush(state, QPalette::Window, pal.toolTipBase());
}
m_toolTipRequested = false;
}
-
Q_OBJECT
public:
- enum class HideBehavior {
- Instantly,
- Later
- };
+ enum class HideBehavior { Instantly, Later };
- explicit ToolTipManager(QWidget* parent);
+ explicit ToolTipManager(QWidget *parent);
~ToolTipManager() override;
/**
* The tooltip manager takes care that the tooltip is shown
* slightly delayed and with a proper \p transientParent.
*/
- void showToolTip(const KFileItem& item, const QRectF& itemRect, QWindow *transientParent);
+ void showToolTip(const KFileItem &item, const QRectF &itemRect, QWindow *transientParent);
/**
* Hides the currently shown tooltip.
* Is emitted when the user clicks a tag or a link
* in the metadata widget.
*/
- void urlActivated(const QUrl& url);
+ void urlActivated(const QUrl &url);
private Q_SLOTS:
void startContentRetrieval();
- void setPreviewPix(const KFileItem& item, const QPixmap& pix);
+ void setPreviewPix(const KFileItem &item, const QPixmap &pix);
void previewFailed();
void slotMetaDataRequestFinished();
void showToolTip();
private:
/// Timeout from requesting a tooltip until the tooltip
/// should be shown
- QTimer* m_showToolTipTimer;
+ QTimer *m_showToolTipTimer;
/// Timeout from requesting a tooltip until the retrieving of
/// the tooltip content like preview and meta data gets started.
- QTimer* m_contentRetrievalTimer;
+ QTimer *m_contentRetrievalTimer;
/// Transient parent of the tooltip, mandatory on Wayland.
- QWindow* m_transientParent;
+ QWindow *m_transientParent;
QScopedPointer<KToolTipWidget> m_tooltipWidget;
DolphinFileMetaDataWidget *m_fileMetaDataWidget = nullptr;
#include "kversioncontrolplugin.h"
-KVersionControlPlugin::KVersionControlPlugin(QObject* parent) :
- QObject(parent)
+KVersionControlPlugin::KVersionControlPlugin(QObject *parent)
+ : QObject(parent)
{
}
{
}
-QString KVersionControlPlugin::localRepositoryRoot(const QString &/*directory*/) const
+QString KVersionControlPlugin::localRepositoryRoot(const QString & /*directory*/) const
{
return QString();
}
Q_OBJECT
public:
- enum ItemVersion
- {
+ enum ItemVersion {
/** The file is not under version control. */
UnversionedVersion,
/**
MissingVersion
};
- KVersionControlPlugin(QObject* parent = nullptr);
+ KVersionControlPlugin(QObject *parent = nullptr);
~KVersionControlPlugin() override;
/**
* Returns the path of the local repository root for the versioned directory
* Returns an empty QString when directory is not part of a working copy
*/
- virtual QString localRepositoryRoot(const QString& directory) const;
+ virtual QString localRepositoryRoot(const QString &directory) const;
/**
* Is invoked whenever the version control
* \p directory. It is assured that the directory
* contains a trailing slash.
*/
- virtual bool beginRetrieval(const QString& directory) = 0;
+ virtual bool beginRetrieval(const QString &directory) = 0;
/**
* Is invoked after the version control information has been
* invoked before and that the file is part of the directory specified
* in beginRetrieval().
*/
- virtual ItemVersion itemVersion(const KFileItem& item) const = 0;
+ virtual ItemVersion itemVersion(const KFileItem &item) const = 0;
/**
* @return List of actions that are available for the \p items in a version controlled
* path.
*/
- virtual QList<QAction*> versionControlActions(const KFileItemList& items) const = 0;
+ virtual QList<QAction *> versionControlActions(const KFileItemList &items) const = 0;
/**
* @return List of actions that are available for the out of version control
* is for clone/checkout actions.
* @since 21.04
*/
- virtual QList<QAction*> outOfVersionControlActions(const KFileItemList& items) const = 0;
+ virtual QList<QAction *> outOfVersionControlActions(const KFileItemList &items) const = 0;
Q_SIGNALS:
/**
* Is emitted if an information message with the content \a msg
* should be shown.
*/
- void infoMessage(const QString& msg);
+ void infoMessage(const QString &msg);
/**
* Is emitted if an error message with the content \a msg
* should be shown.
*/
- void errorMessage(const QString& msg);
+ void errorMessage(const QString &msg);
/**
* Is emitted if an "operation completed" message with the content \a msg
* should be shown.
*/
- void operationCompletedMessage(const QString& msg);
+ void operationCompletedMessage(const QString &msg);
};
#endif // KVERSIONCONTROLPLUGIN_H
-
#include "updateitemstatesthread.h"
-
-UpdateItemStatesThread::UpdateItemStatesThread(KVersionControlPlugin* plugin,
- const QMap<QString, QVector<VersionControlObserver::ItemState> >& itemStates) :
- QThread(),
- m_globalPluginMutex(nullptr),
- m_plugin(plugin),
- m_itemStates(itemStates)
+UpdateItemStatesThread::UpdateItemStatesThread(KVersionControlPlugin *plugin, const QMap<QString, QVector<VersionControlObserver::ItemState>> &itemStates)
+ : QThread()
+ , m_globalPluginMutex(nullptr)
+ , m_plugin(plugin)
+ , m_itemStates(itemStates)
{
// Several threads may share one instance of a plugin. A global
// mutex is required to serialize the retrieval of version control
Q_ASSERT(m_plugin);
QMutexLocker pluginLocker(m_globalPluginMutex);
- QMap<QString, QVector<VersionControlObserver::ItemState> >::iterator it = m_itemStates.begin();
+ QMap<QString, QVector<VersionControlObserver::ItemState>>::iterator it = m_itemStates.begin();
for (; it != m_itemStates.end(); ++it) {
if (m_plugin->beginRetrieval(it.key())) {
- QVector<VersionControlObserver::ItemState>& items = it.value();
+ QVector<VersionControlObserver::ItemState> &items = it.value();
const int count = items.count();
for (int i = 0; i < count; ++i) {
- const KFileItem& item = items.at(i).first;
+ const KFileItem &item = items.at(i).first;
const KVersionControlPlugin::ItemVersion version = m_plugin->itemVersion(item);
items[i].second = version;
}
}
}
-QMap<QString, QVector<VersionControlObserver::ItemState> > UpdateItemStatesThread::itemStates() const
+QMap<QString, QVector<VersionControlObserver::ItemState>> UpdateItemStatesThread::itemStates() const
{
return m_itemStates;
}
-
* UpdateItemStatesThread::unlockPlugin() must be used.
* @param itemStates List of items, where the states get updated.
*/
- UpdateItemStatesThread(KVersionControlPlugin* plugin,
- const QMap<QString, QVector<VersionControlObserver::ItemState> >& itemStates);
+ UpdateItemStatesThread(KVersionControlPlugin *plugin, const QMap<QString, QVector<VersionControlObserver::ItemState>> &itemStates);
~UpdateItemStatesThread() override;
- QMap<QString, QVector<VersionControlObserver::ItemState> > itemStates() const;
+ QMap<QString, QVector<VersionControlObserver::ItemState>> itemStates() const;
protected:
void run() override;
private:
- QMutex* m_globalPluginMutex; // Protects the m_plugin globally
- KVersionControlPlugin* m_plugin;
+ QMutex *m_globalPluginMutex; // Protects the m_plugin globally
+ KVersionControlPlugin *m_plugin;
- QMap<QString, QVector<VersionControlObserver::ItemState> > m_itemStates;
+ QMap<QString, QVector<VersionControlObserver::ItemState>> m_itemStates;
};
#endif // UPDATEITEMSTATESTHREAD_H
#include "dolphin_versioncontrolsettings.h"
#include "dolphindebug.h"
-#include "views/dolphinview.h"
#include "kitemviews/kfileitemmodel.h"
#include "updateitemstatesthread.h"
+#include "views/dolphinview.h"
#include <KLocalizedString>
#include <KPluginFactory>
#include <QTimer>
-VersionControlObserver::VersionControlObserver(QObject* parent) :
- QObject(parent),
- m_pendingItemStatesUpdate(false),
- m_silentUpdate(false),
- m_view(nullptr),
- m_model(nullptr),
- m_dirVerificationTimer(nullptr),
- m_pluginsInitialized(false),
- m_plugin(nullptr),
- m_updateItemStatesThread(nullptr)
+VersionControlObserver::VersionControlObserver(QObject *parent)
+ : QObject(parent)
+ , m_pendingItemStatesUpdate(false)
+ , m_silentUpdate(false)
+ , m_view(nullptr)
+ , m_model(nullptr)
+ , m_dirVerificationTimer(nullptr)
+ , m_pluginsInitialized(false)
+ , m_plugin(nullptr)
+ , m_updateItemStatesThread(nullptr)
{
// The verification timer specifies the timeout until the shown directory
// is checked whether it is versioned. Per default it is assumed that users
m_dirVerificationTimer = new QTimer(this);
m_dirVerificationTimer->setSingleShot(true);
m_dirVerificationTimer->setInterval(500);
- connect(m_dirVerificationTimer, &QTimer::timeout,
- this, &VersionControlObserver::verifyDirectory);
+ connect(m_dirVerificationTimer, &QTimer::timeout, this, &VersionControlObserver::verifyDirectory);
}
VersionControlObserver::~VersionControlObserver()
}
}
-void VersionControlObserver::setModel(KFileItemModel* model)
+void VersionControlObserver::setModel(KFileItemModel *model)
{
if (m_model) {
- disconnect(m_model, &KFileItemModel::itemsInserted,
- this, &VersionControlObserver::delayedDirectoryVerification);
- disconnect(m_model, &KFileItemModel::itemsChanged,
- this, &VersionControlObserver::slotItemsChanged);
+ disconnect(m_model, &KFileItemModel::itemsInserted, this, &VersionControlObserver::delayedDirectoryVerification);
+ disconnect(m_model, &KFileItemModel::itemsChanged, this, &VersionControlObserver::slotItemsChanged);
}
m_model = model;
if (model) {
- connect(m_model, &KFileItemModel::itemsInserted,
- this, &VersionControlObserver::delayedDirectoryVerification);
- connect(m_model, &KFileItemModel::itemsChanged,
- this, &VersionControlObserver::slotItemsChanged);
+ connect(m_model, &KFileItemModel::itemsInserted, this, &VersionControlObserver::delayedDirectoryVerification);
+ connect(m_model, &KFileItemModel::itemsChanged, this, &VersionControlObserver::slotItemsChanged);
}
}
-KFileItemModel* VersionControlObserver::model() const
+KFileItemModel *VersionControlObserver::model() const
{
return m_model;
}
-void VersionControlObserver::setView(DolphinView* view)
+void VersionControlObserver::setView(DolphinView *view)
{
if (m_view) {
- disconnect(m_view, &DolphinView::activated,
- this, &VersionControlObserver::delayedDirectoryVerification);
+ disconnect(m_view, &DolphinView::activated, this, &VersionControlObserver::delayedDirectoryVerification);
}
m_view = view;
if (m_view) {
- connect(m_view, &DolphinView::activated,
- this, &VersionControlObserver::delayedDirectoryVerification);
+ connect(m_view, &DolphinView::activated, this, &VersionControlObserver::delayedDirectoryVerification);
}
}
-DolphinView* VersionControlObserver::view() const
+DolphinView *VersionControlObserver::view() const
{
return m_view;
}
-QList<QAction*> VersionControlObserver::actions(const KFileItemList& items) const
+QList<QAction *> VersionControlObserver::actions(const KFileItemList &items) const
{
bool hasNullItems = false;
- for (const KFileItem& item : items) {
+ for (const KFileItem &item : items) {
if (item.isNull()) {
qCWarning(DolphinDebug) << "Requesting version-control-actions for empty items";
hasNullItems = true;
if (isVersionControlled()) {
return m_plugin->versionControlActions(items);
} else {
- QList<QAction*> actions;
+ QList<QAction *> actions;
for (const QPointer<KVersionControlPlugin> &plugin : qAsConst(m_plugins)) {
actions << plugin->outOfVersionControlActions(items);
}
m_dirVerificationTimer->start();
}
-void VersionControlObserver::slotItemsChanged(const KItemRangeList& itemRanges, const QSet<QByteArray>& roles)
+void VersionControlObserver::slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles)
{
Q_UNUSED(itemRanges)
// Because "version" role is emitted by VCS plugin (ourselves) we don't need to
// analyze it and update directory item states information. So lets check if
// there is only "version".
- if ( !(roles.count() == 1 && roles.contains("version")) ) {
+ if (!(roles.count() == 1 && roles.contains("version"))) {
delayedDirectoryVerification();
}
}
void VersionControlObserver::slotThreadFinished()
{
- UpdateItemStatesThread* thread = m_updateItemStatesThread;
+ UpdateItemStatesThread *thread = m_updateItemStatesThread;
m_updateItemStatesThread = nullptr; // The thread deletes itself automatically (see updateItemStates())
if (!m_plugin || !thread) {
return;
}
- const QMap<QString, QVector<ItemState> >& itemStates = thread->itemStates();
- QMap<QString, QVector<ItemState> >::const_iterator it = itemStates.constBegin();
+ const QMap<QString, QVector<ItemState>> &itemStates = thread->itemStates();
+ QMap<QString, QVector<ItemState>>::const_iterator it = itemStates.constBegin();
for (; it != itemStates.constEnd(); ++it) {
- const QVector<ItemState>& items = it.value();
+ const QVector<ItemState> &items = it.value();
- for (const ItemState& item : items) {
- const KFileItem& fileItem = item.first;
+ for (const ItemState &item : items) {
+ const KFileItem &fileItem = item.first;
const KVersionControlPlugin::ItemVersion version = item.second;
QHash<QByteArray, QVariant> values;
values.insert("version", QVariant(version));
return;
}
- QMap<QString, QVector<ItemState> > itemStates;
+ QMap<QString, QVector<ItemState>> itemStates;
createItemStatesList(itemStates);
if (!itemStates.isEmpty()) {
Q_EMIT infoMessage(i18nc("@info:status", "Updating version information..."));
}
m_updateItemStatesThread = new UpdateItemStatesThread(m_plugin, itemStates);
- connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished,
- this, &VersionControlObserver::slotThreadFinished);
- connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished,
- m_updateItemStatesThread, &UpdateItemStatesThread::deleteLater);
+ connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished, this, &VersionControlObserver::slotThreadFinished);
+ connect(m_updateItemStatesThread, &UpdateItemStatesThread::finished, m_updateItemStatesThread, &UpdateItemStatesThread::deleteLater);
m_updateItemStatesThread->start(); // slotThreadFinished() is called when finished
}
}
-int VersionControlObserver::createItemStatesList(QMap<QString, QVector<ItemState> >& itemStates,
- const int firstIndex)
+int VersionControlObserver::createItemStatesList(QMap<QString, QVector<ItemState>> &itemStates, const int firstIndex)
{
const int itemCount = m_model->count();
const int currentExpansionLevel = m_model->expandedParentsCount(firstIndex);
}
if (!items.isEmpty()) {
- const QUrl& url = items.first().first.url();
+ const QUrl &url = items.first().first.url();
itemStates.insert(url.adjusted(QUrl::RemoveFilename).path(), items);
}
}
for (auto &plugin : qAsConst(m_plugins)) {
- connect(plugin, &KVersionControlPlugin::itemVersionsChanged,
- this, &VersionControlObserver::silentDirectoryVerification);
- connect(plugin, &KVersionControlPlugin::infoMessage,
- this, &VersionControlObserver::infoMessage);
- connect(plugin, &KVersionControlPlugin::errorMessage,
- this, &VersionControlObserver::errorMessage);
- connect(plugin, &KVersionControlPlugin::operationCompletedMessage,
- this, &VersionControlObserver::operationCompletedMessage);
+ connect(plugin, &KVersionControlPlugin::itemVersionsChanged, this, &VersionControlObserver::silentDirectoryVerification);
+ connect(plugin, &KVersionControlPlugin::infoMessage, this, &VersionControlObserver::infoMessage);
+ connect(plugin, &KVersionControlPlugin::errorMessage, this, &VersionControlObserver::errorMessage);
+ connect(plugin, &KVersionControlPlugin::operationCompletedMessage, this, &VersionControlObserver::operationCompletedMessage);
}
m_pluginsInitialized = true;
}
}
-KVersionControlPlugin* VersionControlObserver::searchPlugin(const QUrl& directory)
+KVersionControlPlugin *VersionControlObserver::searchPlugin(const QUrl &directory)
{
initPlugins();
{
return m_plugin != nullptr;
}
-
Q_OBJECT
public:
- explicit VersionControlObserver(QObject* parent = nullptr);
+ explicit VersionControlObserver(QObject *parent = nullptr);
~VersionControlObserver() override;
- void setModel(KFileItemModel* model);
- KFileItemModel* model() const;
- void setView(DolphinView* view);
- DolphinView* view() const;
+ void setModel(KFileItemModel *model);
+ KFileItemModel *model() const;
+ void setView(DolphinView *view);
+ DolphinView *view() const;
- QList<QAction*> actions(const KFileItemList& items) const;
+ QList<QAction *> actions(const KFileItemList &items) const;
Q_SIGNALS:
/**
* Is emitted if an information message with the content \a msg
* should be shown.
*/
- void infoMessage(const QString& msg);
+ void infoMessage(const QString &msg);
/**
* Is emitted if an error message with the content \a msg
* should be shown.
*/
- void errorMessage(const QString& msg);
+ void errorMessage(const QString &msg);
/**
* Is emitted if an "operation completed" message with the content \a msg
* should be shown.
*/
- void operationCompletedMessage(const QString& msg);
+ void operationCompletedMessage(const QString &msg);
private Q_SLOTS:
/**
* Invokes delayedDirectoryVerification() only if the itemsChanged() signal has not
* been triggered by the VCS plugin itself.
*/
- void slotItemsChanged(const KItemRangeList& itemRanges, const QSet<QByteArray>& roles);
+ void slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles);
void verifyDirectory();
*
* @return The number of (recursive) processed items.
*/
- int createItemStatesList(QMap<QString, QVector<ItemState> >& itemStates,
- const int firstIndex = 0);
+ int createItemStatesList(QMap<QString, QVector<ItemState>> &itemStates, const int firstIndex = 0);
/**
* Returns a matching plugin for the given directory.
* 0 is returned, if no matching plugin has been found.
*/
- KVersionControlPlugin* searchPlugin(const QUrl& directory);
+ KVersionControlPlugin *searchPlugin(const QUrl &directory);
/**
* Returns true, if the directory contains a version control information.
// of version states
QString m_localRepoRoot;
- DolphinView* m_view;
- KFileItemModel* m_model;
+ DolphinView *m_view;
+ KFileItemModel *m_model;
- QTimer* m_dirVerificationTimer;
+ QTimer *m_dirVerificationTimer;
bool m_pluginsInitialized;
- KVersionControlPlugin* m_plugin;
+ KVersionControlPlugin *m_plugin;
QList<QPointer<KVersionControlPlugin>> m_plugins;
- UpdateItemStatesThread* m_updateItemStatesThread;
+ UpdateItemStatesThread *m_updateItemStatesThread;
friend class UpdateItemStatesThread;
};
#endif // REVISIONCONTROLOBSERVER_H
-
#include "zoomlevelinfo.h"
-ViewModeController::ViewModeController(QObject* parent) :
- QObject(parent),
- m_zoomLevel(0),
- m_nameFilter(),
- m_url()
+ViewModeController::ViewModeController(QObject *parent)
+ : QObject(parent)
+ , m_zoomLevel(0)
+ , m_nameFilter()
+ , m_url()
{
}
return m_url;
}
-void ViewModeController::redirectToUrl(const QUrl& url)
+void ViewModeController::redirectToUrl(const QUrl &url)
{
m_url = url;
}
Q_EMIT activationChanged(active);
}
-void ViewModeController::setNameFilter(const QString& nameFilter)
+void ViewModeController::setNameFilter(const QString &nameFilter)
{
if (nameFilter != m_nameFilter) {
m_nameFilter = nameFilter;
return m_zoomLevel;
}
-void ViewModeController::setUrl(const QUrl& url)
+void ViewModeController::setUrl(const QUrl &url)
{
if (m_url != url) {
m_url = url;
Q_EMIT urlChanged(url);
}
}
-
Q_OBJECT
public:
- explicit ViewModeController(QObject* parent = nullptr);
+ explicit ViewModeController(QObject *parent = nullptr);
~ViewModeController() override;
/**
* Sets the URL to \a url and does nothing else. Called when
* a redirection happens. See ViewModeController::setUrl()
*/
- void redirectToUrl(const QUrl& url);
+ void redirectToUrl(const QUrl &url);
/**
* Informs the view mode implementation about a change of the activation
/**
* Sets the name filter to \a and emits the signal nameFilterChanged().
*/
- void setNameFilter(const QString& nameFilter);
+ void setNameFilter(const QString &nameFilter);
QString nameFilter() const;
public Q_SLOTS:
* Sets the URL to \a url and emits the signals cancelPreviews() and
* urlChanged() if \a url is different for the current URL.
*/
- void setUrl(const QUrl& url);
+ void setUrl(const QUrl &url);
Q_SIGNALS:
/**
* Is emitted if the URL has been changed by ViewModeController::setUrl().
*/
- void urlChanged(const QUrl& url);
+ void urlChanged(const QUrl &url);
/**
* Is emitted, if ViewModeController::indicateActivationChange() has been
* Is emitted if the name filter has been changed by
* ViewModeController::setNameFilter().
*/
- void nameFilterChanged(const QString& nameFilter);
+ void nameFilterChanged(const QString &nameFilter);
/**
* Is emitted if the zoom level has been changed by
#include <KFileItem>
-namespace {
- const int AdditionalInfoViewPropertiesVersion = 1;
- const int NameRolePropertiesVersion = 2;
- const int DateRolePropertiesVersion = 4;
- const int CurrentViewPropertiesVersion = 4;
+namespace
+{
+const int AdditionalInfoViewPropertiesVersion = 1;
+const int NameRolePropertiesVersion = 2;
+const int DateRolePropertiesVersion = 4;
+const int CurrentViewPropertiesVersion = 4;
- // String representation to mark the additional properties of
- // the details view as customized by the user. See
- // ViewProperties::visibleRoles() for more information.
- const char CustomizedDetailsString[] = "CustomizedDetails";
+// String representation to mark the additional properties of
+// the details view as customized by the user. See
+// ViewProperties::visibleRoles() for more information.
+const char CustomizedDetailsString[] = "CustomizedDetails";
- // Filename that is used for storing the properties
- const char ViewPropertiesFileName[] = ".directory";
+// Filename that is used for storing the properties
+const char ViewPropertiesFileName[] = ".directory";
}
-ViewProperties::ViewProperties(const QUrl& url) :
- m_changedProps(false),
- m_autoSave(true),
- m_node(nullptr)
+ViewProperties::ViewProperties(const QUrl &url)
+ : m_changedProps(false)
+ , m_autoSave(true)
+ , m_node(nullptr)
{
- GeneralSettings* settings = GeneralSettings::self();
+ GeneralSettings *settings = GeneralSettings::self();
const bool useGlobalViewProps = settings->globalViewProps() || url.isEmpty();
bool useSearchView = false;
bool useTrashView = false;
}
if (useDestinationDir) {
- #ifdef Q_OS_WIN
+#ifdef Q_OS_WIN
// m_filePath probably begins with C:/ - the colon is not a valid character for paths though
- m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':'));
- #endif
+ m_filePath = QDir::separator() + m_filePath.remove(QLatin1Char(':'));
+#endif
m_filePath = destinationDir(QStringLiteral("local")) + m_filePath;
}
// If the .directory file does not exist or the timestamp is too old,
// use default values instead.
- const bool useDefaultProps = (!useGlobalViewProps || useSearchView || useTrashView || useRecentDocumentsView || useDownloadsView) &&
- (!QFile::exists(file) ||
- (m_node->timestamp() < settings->viewPropsTimestamp()));
+ const bool useDefaultProps = (!useGlobalViewProps || useSearchView || useTrashView || useRecentDocumentsView || useDownloadsView)
+ && (!QFile::exists(file) || (m_node->timestamp() < settings->viewPropsTimestamp()));
if (useDefaultProps) {
if (useSearchView) {
const QString path = url.path();
}
} else {
// The global view-properties act as default for directories without
- // any view-property configuration. Constructing a ViewProperties
+ // any view-property configuration. Constructing a ViewProperties
// instance for an empty QUrl ensures that the global view-properties
// are loaded.
QUrl emptyUrl;
return m_node->hiddenFilesShown();
}
-void ViewProperties::setSortRole(const QByteArray& role)
+void ViewProperties::setSortRole(const QByteArray &role)
{
if (m_node->sortRole() != role) {
m_node->setSortRole(role);
return m_node->sortHiddenLast();
}
-void ViewProperties::setVisibleRoles(const QList<QByteArray>& roles)
+void ViewProperties::setVisibleRoles(const QList<QByteArray> &roles)
{
if (roles == visibleRoles()) {
return;
// Add the updated values for the current view-mode
newVisibleRoles.reserve(roles.count());
- for (const QByteArray& role : roles) {
+ for (const QByteArray &role : roles) {
newVisibleRoles.append(prefix + role);
}
if (oldVisibleRoles != newVisibleRoles) {
- const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView)
- && !newVisibleRoles.contains(CustomizedDetailsString);
+ const bool markCustomizedDetails = (m_node->viewMode() == DolphinView::DetailsView) && !newVisibleRoles.contains(CustomizedDetailsString);
if (markCustomizedDetails) {
// The additional information of the details-view has been modified. Set a marker,
// so that it is allowed to also show no additional information without doing the
const int prefixLength = prefix.length();
const QStringList visibleRoles = m_node->visibleRoles();
- for (const QString& visibleRole : visibleRoles) {
+ for (const QString &visibleRole : visibleRoles) {
if (visibleRole.startsWith(prefix)) {
const QByteArray role = visibleRole.right(visibleRole.length() - prefixLength).toLatin1();
if (role != "text") {
// For the details view the size and date should be shown per default
// until the additional information has been explicitly changed by the user
const bool useDefaultValues = roles.count() == 1 // "text"
- && (m_node->viewMode() == DolphinView::DetailsView)
- && !visibleRoles.contains(CustomizedDetailsString);
+ && (m_node->viewMode() == DolphinView::DetailsView) && !visibleRoles.contains(CustomizedDetailsString);
if (useDefaultValues) {
roles.append("size");
roles.append("modificationtime");
return roles;
}
-void ViewProperties::setHeaderColumnWidths(const QList<int>& widths)
+void ViewProperties::setHeaderColumnWidths(const QList<int> &widths)
{
if (m_node->headerColumnWidths() != widths) {
m_node->setHeaderColumnWidths(widths);
return m_node->headerColumnWidths();
}
-void ViewProperties::setDirProperties(const ViewProperties& props)
+void ViewProperties::setDirProperties(const ViewProperties &props)
{
setViewMode(props.viewMode());
setPreviewsShown(props.previewsShown());
return QFile::exists(file);
}
-QString ViewProperties::destinationDir(const QString& subDir) const
+QString ViewProperties::destinationDir(const QString &subDir) const
{
QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
path.append("/view_properties/").append(subDir);
QString prefix;
switch (m_node->viewMode()) {
- case DolphinView::IconsView: prefix = QStringLiteral("Icons_"); break;
- case DolphinView::CompactView: prefix = QStringLiteral("Compact_"); break;
- case DolphinView::DetailsView: prefix = QStringLiteral("Details_"); break;
- default: qCWarning(DolphinDebug) << "Unknown view-mode of the view properties";
+ case DolphinView::IconsView:
+ prefix = QStringLiteral("Icons_");
+ break;
+ case DolphinView::CompactView:
+ prefix = QStringLiteral("Compact_");
+ break;
+ case DolphinView::DetailsView:
+ prefix = QStringLiteral("Details_");
+ break;
+ default:
+ qCWarning(DolphinDebug) << "Unknown view-mode of the view properties";
}
return prefix;
// the internal role. One special-case must be handled: "LinkDestination"
// has been used for "destination".
visibleRoles.reserve(visibleRoles.count() + additionalInfo.count());
- for (const QString& info : additionalInfo) {
+ for (const QString &info : additionalInfo) {
QString visibleRole = info;
int index = visibleRole.indexOf('_');
if (index >= 0 && index + 1 < visibleRole.length()) {
update();
}
-bool ViewProperties::isPartOfHome(const QString& filePath)
+bool ViewProperties::isPartOfHome(const QString &filePath)
{
// For performance reasons cache the path in a static QString
// (see QDir::homePath() for more details)
return filePath.startsWith(homePath);
}
-QString ViewProperties::directoryHashForUrl(const QUrl& url)
+QString ViewProperties::directoryHashForUrl(const QUrl &url)
{
const QByteArray hashValue = QCryptographicHash::hash(url.toEncoded(), QCryptographicHash::Sha1);
QString hashString = hashValue.toBase64();
class DOLPHIN_EXPORT ViewProperties
{
public:
- explicit ViewProperties(const QUrl& url);
+ explicit ViewProperties(const QUrl &url);
virtual ~ViewProperties();
void setViewMode(DolphinView::Mode mode);
void setGroupedSorting(bool grouped);
bool groupedSorting() const;
- void setSortRole(const QByteArray& role);
+ void setSortRole(const QByteArray &role);
QByteArray sortRole() const;
void setSortOrder(Qt::SortOrder sortOrder);
* Note that the additional-info property is the only property where
* the value is dependent from another property (in this case the view-mode).
*/
- void setVisibleRoles(const QList<QByteArray>& info);
+ void setVisibleRoles(const QList<QByteArray> &info);
/**
* Returns the additional information for the current set view-mode.
*/
QList<QByteArray> visibleRoles() const;
- void setHeaderColumnWidths(const QList<int>& widths);
+ void setHeaderColumnWidths(const QList<int> &widths);
QList<int> headerColumnWidths() const;
/**
* show hidden files, sorting and sort order like
* set in \a props.
*/
- void setDirProperties(const ViewProperties& props);
+ void setDirProperties(const ViewProperties &props);
/**
* If \a autoSave is true, the properties are automatically
* properties are stored. \a subDir specifies the used sub
* directory.
*/
- QString destinationDir(const QString& subDir) const;
+ QString destinationDir(const QString &subDir) const;
/**
* Returns the view-mode prefix when storing additional properties for
/**
* Returns true, if \a filePath is part of the home-path (see QDir::homePath()).
*/
- static bool isPartOfHome(const QString& filePath);
+ static bool isPartOfHome(const QString &filePath);
/**
* @return A hash-value for an URL that can be used as directory name.
bool m_changedProps;
bool m_autoSave;
QString m_filePath;
- ViewPropertySettings* m_node;
+ ViewPropertySettings *m_node;
};
#endif
{
int size = KIconLoader::SizeMedium;
switch (level) {
- case 0: size = KIconLoader::SizeSmall; break;
- case 1: size = KIconLoader::SizeSmallMedium; break;
- case 2: size = KIconLoader::SizeMedium; break;
- case 3: size = KIconLoader::SizeLarge; break;
- case 4: size = KIconLoader::SizeHuge; break;
- default: size = KIconLoader::SizeHuge + ((level - 4) << 4);
+ case 0:
+ size = KIconLoader::SizeSmall;
+ break;
+ case 1:
+ size = KIconLoader::SizeSmallMedium;
+ break;
+ case 2:
+ size = KIconLoader::SizeMedium;
+ break;
+ case 3:
+ size = KIconLoader::SizeLarge;
+ break;
+ case 4:
+ size = KIconLoader::SizeHuge;
+ break;
+ default:
+ size = KIconLoader::SizeHuge + ((level - 4) << 4);
}
return size;
}
-int ZoomLevelInfo::zoomLevelForIconSize(const QSize& size)
+int ZoomLevelInfo::zoomLevelForIconSize(const QSize &size)
{
int level = 0;
switch (size.height()) {
- case KIconLoader::SizeSmall: level = 0; break;
- case KIconLoader::SizeSmallMedium: level = 1; break;
- case KIconLoader::SizeMedium: level = 2; break;
- case KIconLoader::SizeLarge: level = 3; break;
- case KIconLoader::SizeHuge: level = 4; break;
- default: level = 4 + ((size.height() - KIconLoader::SizeHuge) >> 4);
+ case KIconLoader::SizeSmall:
+ level = 0;
+ break;
+ case KIconLoader::SizeSmallMedium:
+ level = 1;
+ break;
+ case KIconLoader::SizeMedium:
+ level = 2;
+ break;
+ case KIconLoader::SizeLarge:
+ level = 3;
+ break;
+ case KIconLoader::SizeHuge:
+ level = 4;
+ break;
+ default:
+ level = 4 + ((size.height() - KIconLoader::SizeHuge) >> 4);
}
return level;
}
* @short Helper class for getting information about the zooming
* capabilities.
*/
-class ZoomLevelInfo {
+class ZoomLevelInfo
+{
public:
static int minimumLevel();
static int maximumLevel();
* is between the range ZoomLevelInfo::minimumLevel() and
* ZoomLevelInfo::maximumLevel().
*/
- static int zoomLevelForIconSize(const QSize& size);
+ static int zoomLevelForIconSize(const QSize &size);
};
#endif