2 * SPDX-FileCopyrightText: 2006-2009 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2006 Gregor Kališnik <gregor@podnapisi.net>
5 * SPDX-License-Identifier: GPL-2.0-or-later
8 #include "dolphinview.h"
10 #include "dolphin_detailsmodesettings.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphinitemlistview.h"
13 #include "dolphinnewfilemenuobserver.h"
14 #include "draganddrophelper.h"
15 #ifndef QT_NO_ACCESSIBILITY
16 #include "kitemviews/accessibility/kitemlistviewaccessible.h"
18 #include "kitemviews/kfileitemlistview.h"
19 #include "kitemviews/kfileitemmodel.h"
20 #include "kitemviews/kitemlistcontainer.h"
21 #include "kitemviews/kitemlistcontroller.h"
22 #include "kitemviews/kitemlistheader.h"
23 #include "kitemviews/kitemlistselectionmanager.h"
24 #include "kitemviews/private/kitemlistroleeditor.h"
25 #include "selectionmode/singleclickselectionproxystyle.h"
26 #include "settings/viewmodes/viewmodesettings.h"
27 #include "versioncontrol/versioncontrolobserver.h"
28 #include "viewproperties.h"
29 #include "views/tooltips/tooltipmanager.h"
30 #include "zoomlevelinfo.h"
33 #include <Baloo/IndexerConfig>
35 #include <KColorScheme>
36 #include <KDesktopFile>
38 #include <KFileItemListProperties>
40 #include <KIO/CopyJob>
41 #include <KIO/DeleteOrTrashJob>
42 #include <KIO/DropJob>
43 #include <KIO/JobUiDelegate>
45 #include <KIO/PasteJob>
46 #include <KIO/RenameFileDialog>
48 #include <KJobWidgets>
49 #include <KLocalizedString>
50 #include <KMessageBox>
51 #include <KProtocolManager>
52 #include <KUrlMimeData>
54 #include <kwidgetsaddons_version.h>
56 #include <QAbstractItemView>
57 #ifndef QT_NO_ACCESSIBILITY
58 #include <QAccessible>
60 #include <QActionGroup>
61 #include <QApplication>
64 #include <QGraphicsOpacityEffect>
65 #include <QGraphicsSceneDragDropEvent>
68 #include <QMimeDatabase>
69 #include <QPixmapCache>
74 #include <QVBoxLayout>
76 DolphinView::DolphinView(const QUrl
&url
, QWidget
*parent
)
79 , m_tabsForFiles(false)
80 , m_assureVisibleCurrentIndex(false)
81 , m_isFolderWritable(true)
83 , m_selectNextItem(false)
85 , m_viewPropertiesContext()
86 , m_mode(DolphinView::IconsView
)
88 , m_topLayout(nullptr)
91 , m_container(nullptr)
92 , m_toolTipManager(nullptr)
93 , m_selectionChangedTimer(nullptr)
95 , m_scrollToCurrentItem(false)
96 , m_restoredContentsPosition()
97 , m_controlWheelAccumulatedDelta(0)
99 , m_clearSelectionBeforeSelectingNewItems(false)
100 , m_markFirstNewlySelectedItemAsCurrent(false)
101 , m_versionControlObserver(nullptr)
102 , m_twoClicksRenamingTimer(nullptr)
103 , m_placeholderLabel(nullptr)
104 , m_showLoadingPlaceholderTimer(nullptr)
106 m_topLayout
= new QVBoxLayout(this);
107 m_topLayout
->setSpacing(0);
108 m_topLayout
->setContentsMargins(0, 0, 0, 0);
110 // When a new item has been created by the "Create New..." menu, the item should
111 // get selected and it must be assured that the item will get visible. As the
112 // creation is done asynchronously, several signals must be checked:
113 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
, this, &DolphinView::observeCreatedItem
);
115 m_selectionChangedTimer
= new QTimer(this);
116 m_selectionChangedTimer
->setSingleShot(true);
117 m_selectionChangedTimer
->setInterval(300);
118 connect(m_selectionChangedTimer
, &QTimer::timeout
, this, &DolphinView::emitSelectionChangedSignal
);
120 m_model
= new KFileItemModel(this);
121 m_view
= new DolphinItemListView();
122 m_view
->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::FollowSetting
);
123 m_view
->setVisibleRoles({"text"});
126 KItemListController
*controller
= new KItemListController(m_model
, m_view
, this);
127 controller
->setAutoActivationEnabled(GeneralSettings::autoExpandFolders());
128 connect(controller
, &KItemListController::doubleClickViewBackground
, this, &DolphinView::doubleClickViewBackground
);
130 // The EnlargeSmallPreviews setting can only be changed after the model
131 // has been set in the view by KItemListController.
132 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
134 m_container
= new KItemListContainer(controller
, this);
135 m_container
->installEventFilter(this);
136 #ifndef QT_NO_ACCESSIBILITY
137 m_view
->setAccessibleParentsObject(m_container
);
139 setFocusProxy(m_container
);
140 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [this] {
143 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [this] {
147 m_showLoadingPlaceholderTimer
= new QTimer(this);
148 m_showLoadingPlaceholderTimer
->setInterval(500);
149 m_showLoadingPlaceholderTimer
->setSingleShot(true);
150 connect(m_showLoadingPlaceholderTimer
, &QTimer::timeout
, this, &DolphinView::showLoadingPlaceholder
);
152 // Show some placeholder text for empty folders
153 // This is made using a heavily-modified QLabel rather than a KTitleWidget
154 // because KTitleWidget can't be told to turn off mouse-selectable text
155 m_placeholderLabel
= new QLabel(this);
156 // Don't consume mouse events
157 m_placeholderLabel
->setAttribute(Qt::WA_TransparentForMouseEvents
);
159 QFont placeholderLabelFont
;
160 // To match the size of a level 2 Heading/KTitleWidget
161 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
162 m_placeholderLabel
->setFont(placeholderLabelFont
);
163 m_placeholderLabel
->setWordWrap(true);
164 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
165 // Match opacity of QML placeholder label component
166 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
167 effect
->setOpacity(0.5);
168 m_placeholderLabel
->setGraphicsEffect(effect
);
169 // Set initial text and visibility
170 updatePlaceholderLabel();
172 auto *centeringLayout
= new QVBoxLayout(m_container
);
173 centeringLayout
->addWidget(m_placeholderLabel
);
174 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
176 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
177 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
178 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
179 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
180 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
181 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
182 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
183 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
184 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
185 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
186 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
187 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
188 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
189 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
190 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
191 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
192 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
193 connect(controller
, &KItemListController::selectionModeChangeRequested
, this, &DolphinView::selectionModeChangeRequested
);
195 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
196 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
197 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
198 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
199 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
200 connect(m_model
, &KFileItemModel::itemsChanged
, this, &DolphinView::slotItemsChanged
);
201 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
202 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
203 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
204 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
205 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
206 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
207 connect(m_model
, &KFileItemModel::fileItemsChanged
, this, &DolphinView::fileItemsChanged
);
208 connect(m_model
, &KFileItemModel::currentDirectoryRemoved
, this, &DolphinView::currentDirectoryRemoved
);
210 connect(this, &DolphinView::itemCountChanged
, this, &DolphinView::updatePlaceholderLabel
);
212 m_view
->installEventFilter(this);
213 connect(m_view
, &DolphinItemListView::sortOrderChanged
, this, &DolphinView::slotSortOrderChangedByHeader
);
214 connect(m_view
, &DolphinItemListView::sortRoleChanged
, this, &DolphinView::slotSortRoleChangedByHeader
);
215 connect(m_view
, &DolphinItemListView::visibleRolesChanged
, this, &DolphinView::slotVisibleRolesChangedByHeader
);
216 connect(m_view
, &DolphinItemListView::roleEditingCanceled
, this, &DolphinView::slotRoleEditingCanceled
);
218 connect(m_view
, &DolphinItemListView::columnHovered
, this, [this](int columnIndex
) {
219 m_hoveredColumnHeaderIndex
= columnIndex
;
221 connect(m_view
, &DolphinItemListView::columnUnHovered
, this, [this](int /* columnIndex */) {
222 m_hoveredColumnHeaderIndex
= std::nullopt
;
224 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
, this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
225 connect(m_view
->header(), &KItemListHeader::sidePaddingChanged
, this, &DolphinView::slotSidePaddingWidthChanged
);
227 KItemListSelectionManager
*selectionManager
= controller
->selectionManager();
228 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
, this, &DolphinView::slotSelectionChanged
);
231 m_toolTipManager
= new ToolTipManager(this);
232 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
235 m_versionControlObserver
= new VersionControlObserver(this);
236 m_versionControlObserver
->setView(this);
237 m_versionControlObserver
->setModel(m_model
);
238 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
239 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, [this](const QString
&message
) {
240 Q_EMIT
errorMessage(message
, KIO::ERR_UNKNOWN
);
242 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
244 m_twoClicksRenamingTimer
= new QTimer(this);
245 m_twoClicksRenamingTimer
->setSingleShot(true);
246 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
248 applyViewProperties();
249 m_topLayout
->addWidget(m_container
);
254 DolphinView::~DolphinView()
256 disconnect(m_container
->controller(), &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
259 QUrl
DolphinView::url() const
264 void DolphinView::setActive(bool active
)
266 if (active
== m_active
) {
275 m_container
->setFocus();
280 bool DolphinView::isActive() const
285 void DolphinView::setViewMode(Mode mode
)
287 if (mode
!= m_mode
) {
288 // Reset scrollbars before changing the view mode.
289 m_container
->horizontalScrollBar()->setValue(0);
290 m_container
->verticalScrollBar()->setValue(0);
292 ViewProperties
props(viewPropertiesUrl());
293 props
.setViewMode(mode
);
295 // We pass the new ViewProperties to applyViewProperties, rather than
296 // storing them on disk and letting applyViewProperties() read them
297 // from there, to prevent that changing the view mode fails if the
298 // .directory file is not writable (see bug 318534).
299 applyViewProperties(props
);
303 DolphinView::Mode
DolphinView::viewMode() const
308 void DolphinView::setSelectionModeEnabled(const bool enabled
)
312 m_proxyStyle
= std::make_unique
<SelectionMode::SingleClickSelectionProxyStyle
>();
314 setStyle(m_proxyStyle
.get());
315 m_view
->setStyle(m_proxyStyle
.get());
316 m_view
->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::False
);
319 m_view
->setStyle(nullptr);
320 m_view
->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::FollowSetting
);
322 m_container
->controller()->setSelectionModeEnabled(enabled
);
323 #ifndef QT_NO_ACCESSIBILITY
324 if (QAccessible::isActive()) {
325 auto accessibleViewInterface
= static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
));
326 accessibleViewInterface
->announceSelectionModeEnabled(enabled
);
331 bool DolphinView::selectionMode() const
333 return m_container
->controller()->selectionMode();
336 void DolphinView::setPreviewsShown(bool show
)
338 if (previewsShown() == show
) {
342 ViewProperties
props(viewPropertiesUrl());
343 props
.setPreviewsShown(show
);
345 const int oldZoomLevel
= m_view
->zoomLevel();
346 m_view
->setPreviewsShown(show
);
347 Q_EMIT
previewsShownChanged(show
);
349 const int newZoomLevel
= m_view
->zoomLevel();
350 if (newZoomLevel
!= oldZoomLevel
) {
351 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
355 bool DolphinView::previewsShown() const
357 return m_view
->previewsShown();
360 void DolphinView::setHiddenFilesShown(bool show
)
362 if (m_model
->showHiddenFiles() == show
) {
366 const KFileItemList itemList
= selectedItems();
367 m_selectedUrls
.clear();
368 m_selectedUrls
= itemList
.urlList();
370 ViewProperties
props(viewPropertiesUrl());
371 props
.setHiddenFilesShown(show
);
373 m_model
->setShowHiddenFiles(show
);
374 Q_EMIT
hiddenFilesShownChanged(show
);
377 bool DolphinView::hiddenFilesShown() const
379 return m_model
->showHiddenFiles();
382 void DolphinView::setGroupedSorting(bool grouped
)
384 if (grouped
== groupedSorting()) {
388 ViewProperties
props(viewPropertiesUrl());
389 props
.setGroupedSorting(grouped
);
391 m_model
->setGroupedSorting(grouped
);
393 Q_EMIT
groupedSortingChanged(grouped
);
396 bool DolphinView::groupedSorting() const
398 return m_model
->groupedSorting();
401 KFileItemList
DolphinView::items() const
404 const int itemCount
= m_model
->count();
405 list
.reserve(itemCount
);
407 for (int i
= 0; i
< itemCount
; ++i
) {
408 list
.append(m_model
->fileItem(i
));
414 int DolphinView::itemsCount() const
416 return m_model
->count();
419 KFileItemList
DolphinView::selectedItems() const
421 const KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
423 KFileItemList selectedItems
;
424 const auto items
= selectionManager
->selectedItems();
425 selectedItems
.reserve(items
.count());
426 for (int index
: items
) {
427 selectedItems
.append(m_model
->fileItem(index
));
429 return selectedItems
;
432 int DolphinView::selectedItemsCount() const
434 const KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
435 return selectionManager
->selectedItems().count();
438 void DolphinView::markUrlsAsSelected(const QList
<QUrl
> &urls
)
440 m_selectedUrls
= urls
;
441 m_selectJobCreatedItems
= false;
444 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
446 m_currentItemUrl
= url
;
447 m_scrollToCurrentItem
= true;
450 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
452 const KItemListSelectionManager::SelectionMode mode
= enabled
? KItemListSelectionManager::Select
: KItemListSelectionManager::Deselect
;
453 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
455 for (int index
= 0; index
< m_model
->count(); index
++) {
456 const KFileItem item
= m_model
->fileItem(index
);
457 if (regexp
.match(item
.text()).hasMatch()) {
458 // An alternative approach would be to store the matching items in a KItemSet and
459 // select them in one go after the loop, but we'd need a new function
460 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
462 selectionManager
->setSelected(index
, 1, mode
);
467 void DolphinView::setZoomLevel(int level
)
469 const int oldZoomLevel
= zoomLevel();
470 m_view
->setZoomLevel(level
);
471 if (zoomLevel() != oldZoomLevel
) {
473 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
477 int DolphinView::zoomLevel() const
479 return m_view
->zoomLevel();
482 void DolphinView::setSortRole(const QByteArray
&role
)
484 if (role
!= sortRole()) {
485 ViewProperties
props(viewPropertiesUrl());
486 props
.setSortRole(role
);
488 KItemModelBase
*model
= m_container
->controller()->model();
489 model
->setSortRole(role
);
491 Q_EMIT
sortRoleChanged(role
);
495 QByteArray
DolphinView::sortRole() const
497 const KItemModelBase
*model
= m_container
->controller()->model();
498 return model
->sortRole();
501 void DolphinView::setSortOrder(Qt::SortOrder order
)
503 if (sortOrder() != order
) {
504 ViewProperties
props(viewPropertiesUrl());
505 props
.setSortOrder(order
);
507 m_model
->setSortOrder(order
);
509 Q_EMIT
sortOrderChanged(order
);
513 Qt::SortOrder
DolphinView::sortOrder() const
515 return m_model
->sortOrder();
518 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
520 if (sortFoldersFirst() != foldersFirst
) {
521 updateSortFoldersFirst(foldersFirst
);
525 bool DolphinView::sortFoldersFirst() const
527 return m_model
->sortDirectoriesFirst();
530 void DolphinView::setSortHiddenLast(bool hiddenLast
)
532 if (sortHiddenLast() != hiddenLast
) {
533 updateSortHiddenLast(hiddenLast
);
537 bool DolphinView::sortHiddenLast() const
539 return m_model
->sortHiddenLast();
542 void DolphinView::setVisibleRoles(const QList
<QByteArray
> &roles
)
544 const QList
<QByteArray
> previousRoles
= roles
;
546 ViewProperties
props(viewPropertiesUrl());
547 props
.setVisibleRoles(roles
);
549 m_visibleRoles
= roles
;
550 m_view
->setVisibleRoles(roles
);
552 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
555 QList
<QByteArray
> DolphinView::visibleRoles() const
557 return m_visibleRoles
;
560 void DolphinView::reload()
562 QByteArray viewState
;
563 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
564 saveState(saveStream
);
567 loadDirectory(url(), true);
569 QDataStream
restoreStream(viewState
);
570 restoreState(restoreStream
);
573 void DolphinView::readSettings()
575 const int oldZoomLevel
= m_view
->zoomLevel();
577 GeneralSettings::self()->load();
578 m_view
->readSettings();
579 applyViewProperties();
581 m_container
->controller()->setAutoActivationEnabled(GeneralSettings::autoExpandFolders());
583 const int newZoomLevel
= m_view
->zoomLevel();
584 if (newZoomLevel
!= oldZoomLevel
) {
585 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
589 void DolphinView::writeSettings()
591 GeneralSettings::self()->save();
592 m_view
->writeSettings();
595 void DolphinView::setNameFilter(const QString
&nameFilter
)
597 m_model
->setNameFilter(nameFilter
);
600 QString
DolphinView::nameFilter() const
602 return m_model
->nameFilter();
605 void DolphinView::setMimeTypeFilters(const QStringList
&filters
)
607 return m_model
->setMimeTypeFilters(filters
);
610 QStringList
DolphinView::mimeTypeFilters() const
612 return m_model
->mimeTypeFilters();
615 void DolphinView::requestStatusBarText()
617 if (m_statJobForStatusBarText
) {
618 // Kill the pending request.
619 m_statJobForStatusBarText
->kill();
622 if (m_container
->controller()->selectionManager()->hasSelection()) {
625 KIO::filesize_t totalFileSize
= 0;
627 // Give a summary of the status of the selected files
628 const KFileItemList list
= selectedItems();
629 for (const KFileItem
&item
: list
) {
634 totalFileSize
+= item
.size();
638 if (folderCount
+ fileCount
== 1) {
639 // If only one item is selected, show info about it
640 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
642 // At least 2 items are selected
643 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
645 } else { // has no selection
646 if (!m_model
->rootItem().url().isValid()) {
650 m_statJobForStatusBarText
= KIO::stat(m_model
->rootItem().url(), KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
651 connect(m_statJobForStatusBarText
, &KJob::result
, this, &DolphinView::slotStatJobResult
);
652 m_statJobForStatusBarText
->start();
656 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
, KIO::filesize_t totalFileSize
, const Selection selection
)
662 if (selection
== HasSelection
) {
663 // At least 2 items are selected because the case of 1 selected item is handled in
664 // DolphinView::requestStatusBarText().
665 foldersText
= i18ncp("@info:status", "1 folder selected", "%1 folders selected", folderCount
);
666 filesText
= i18ncp("@info:status", "1 file selected", "%1 files selected", fileCount
);
668 foldersText
= i18ncp("@info:status", "1 folder", "%1 folders", folderCount
);
669 filesText
= i18ncp("@info:status", "1 file", "%1 files", fileCount
);
672 if (fileCount
> 0 && folderCount
> 0) {
673 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)", foldersText
, filesText
, KFormat().formatByteSize(totalFileSize
));
674 } else if (fileCount
> 0) {
675 summary
= i18nc("@info:status files (size)", "%1 (%2)", filesText
, KFormat().formatByteSize(totalFileSize
));
676 } else if (folderCount
> 0) {
677 summary
= foldersText
;
679 summary
= i18nc("@info:status", "0 folders, 0 files");
681 Q_EMIT
statusBarTextChanged(summary
);
684 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
&items
) const
686 QList
<QAction
*> actions
;
688 if (items
.isEmpty()) {
689 const KFileItem item
= m_model
->rootItem();
690 if (!item
.isNull()) {
691 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
694 actions
= m_versionControlObserver
->actions(items
);
700 void DolphinView::setUrl(const QUrl
&url
)
712 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
714 // It is important to clear the items from the model before
715 // applying the view properties, otherwise expensive operations
716 // might be done on the existing items although they get cleared
717 // anyhow afterwards by loadDirectory().
719 applyViewProperties();
722 Q_EMIT
urlChanged(url
);
725 void DolphinView::selectAll()
727 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
728 selectionManager
->setSelected(0, m_model
->count());
731 void DolphinView::invertSelection()
733 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
734 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
737 void DolphinView::clearSelection()
739 m_selectJobCreatedItems
= false;
740 m_selectedUrls
.clear();
741 m_container
->controller()->selectionManager()->clearSelection();
744 void DolphinView::renameSelectedItems()
746 const KFileItemList items
= selectedItems();
747 if (items
.isEmpty()) {
751 if (items
.count() == 1 && GeneralSettings::renameInline()) {
752 const int index
= m_model
->index(items
.first());
756 &KItemListView::scrollingStopped
,
759 m_view
->editRole(index
, "text");
763 connect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
765 Qt::SingleShotConnection
);
766 m_view
->scrollToItem(index
);
769 KIO::RenameFileDialog
*dialog
= new KIO::RenameFileDialog(items
, this);
770 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
, this, [this, items
](const QList
<QUrl
> &urls
) {
771 // The model may have already been updated, so it's possible that we don't find the old items.
772 for (int i
= 0; i
< items
.count(); ++i
) {
773 const int index
= m_model
->index(items
[i
]);
775 QHash
<QByteArray
, QVariant
> data
;
776 data
.insert("text", urls
[i
].fileName());
777 m_model
->setData(index
, data
);
781 forceUrlsSelection(urls
.first(), urls
);
782 updateSelectionState();
784 connect(dialog
, &KIO::RenameFileDialog::error
, this, [this](KJob
*job
) {
785 KMessageBox::error(this, job
->errorString());
791 // Assure that the current index remains visible when KFileItemModel
792 // will notify the view about changed items (which might result in
793 // a changed sorting).
794 m_assureVisibleCurrentIndex
= true;
797 void DolphinView::trashSelectedItems()
799 const QList
<QUrl
> list
= simplifiedSelectedUrls();
801 using Iface
= KIO::AskUserActionInterface
;
802 auto *trashJob
= new KIO::DeleteOrTrashJob(list
, Iface::Trash
, Iface::DefaultConfirmation
, this);
803 connect(trashJob
, &KJob::result
, this, &DolphinView::slotTrashFileFinished
);
804 m_selectNextItem
= true;
808 void DolphinView::deleteSelectedItems()
810 const QList
<QUrl
> list
= simplifiedSelectedUrls();
812 using Iface
= KIO::AskUserActionInterface
;
813 auto *trashJob
= new KIO::DeleteOrTrashJob(list
, Iface::Delete
, Iface::DefaultConfirmation
, this);
814 connect(trashJob
, &KJob::result
, this, &DolphinView::slotDeleteFileFinished
);
815 m_selectNextItem
= true;
819 void DolphinView::cutSelectedItemsToClipboard()
821 QMimeData
*mimeData
= selectionMimeData();
822 KIO::setClipboardDataCut(mimeData
, true);
823 KUrlMimeData::exportUrlsToPortal(mimeData
);
824 QApplication::clipboard()->setMimeData(mimeData
);
827 void DolphinView::copySelectedItemsToClipboard()
829 QMimeData
*mimeData
= selectionMimeData();
830 KUrlMimeData::exportUrlsToPortal(mimeData
);
831 QApplication::clipboard()->setMimeData(mimeData
);
834 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
836 if (selection
.isEmpty() || !destinationUrl
.isValid()) {
840 m_clearSelectionBeforeSelectingNewItems
= true;
841 m_markFirstNewlySelectedItemAsCurrent
= true;
842 m_selectJobCreatedItems
= true;
844 KIO::CopyJob
*job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
845 KJobWidgets::setWindow(job
, this);
847 connect(job
, &KIO::CopyJob::result
, this, &DolphinView::slotJobResult
);
848 connect(job
, &KIO::CopyJob::copying
, this, &DolphinView::slotItemCreatedFromJob
);
849 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotItemCreatedFromJob
);
850 connect(job
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /* warning */) {
851 Q_EMIT
errorMessage(job
->errorString(), job
->error());
853 KIO::FileUndoManager::self()->recordCopyJob(job
);
856 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
858 if (selection
.isEmpty() || !destinationUrl
.isValid()) {
862 m_clearSelectionBeforeSelectingNewItems
= true;
863 m_markFirstNewlySelectedItemAsCurrent
= true;
864 m_selectJobCreatedItems
= true;
866 KIO::CopyJob
*job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
867 KJobWidgets::setWindow(job
, this);
869 connect(job
, &KIO::CopyJob::result
, this, &DolphinView::slotJobResult
);
870 connect(job
, &KIO::CopyJob::moving
, this, &DolphinView::slotItemCreatedFromJob
);
871 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotItemCreatedFromJob
);
872 connect(job
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning */) {
873 Q_EMIT
errorMessage(job
->errorString(), job
->error());
875 KIO::FileUndoManager::self()->recordCopyJob(job
);
878 void DolphinView::paste()
883 void DolphinView::pasteIntoFolder()
885 const KFileItemList items
= selectedItems();
886 if ((items
.count() == 1) && items
.first().isDir()) {
887 pasteToUrl(items
.first().url());
891 void DolphinView::duplicateSelectedItems()
893 const KFileItemList itemList
= selectedItems();
894 if (itemList
.isEmpty()) {
898 const QMimeDatabase db
;
900 m_clearSelectionBeforeSelectingNewItems
= true;
901 m_markFirstNewlySelectedItemAsCurrent
= true;
902 m_selectJobCreatedItems
= true;
904 // Duplicate all selected items and append "copy" to the end of the file name
905 // but before the filename extension, if present
906 for (const auto &item
: itemList
) {
907 const QUrl originalURL
= item
.url();
908 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
909 const QString originalFileName
= item
.name();
911 QString extension
= db
.suffixForFileName(originalFileName
);
913 QUrl duplicateURL
= originalURL
;
915 // No extension; new filename is "<oldfilename> copy"
916 if (extension
.isEmpty()) {
917 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
918 // There's an extension; new filename is "<oldfilename> copy.<extension>"
920 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
921 extension
= QLatin1String(".") + extension
;
922 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
923 // Preserve file's original filename extension in case the casing differs
924 // from what QMimeDatabase::suffixForFileName() returned
925 const QString originalExtension
= originalFileName
.right(extension
.size());
926 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
929 KIO::CopyJob
*job
= KIO::copyAs(originalURL
, duplicateURL
);
930 job
->setAutoRename(true);
931 KJobWidgets::setWindow(job
, this);
933 connect(job
, &KIO::CopyJob::result
, this, &DolphinView::slotJobResult
);
934 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotItemCreatedFromJob
);
935 connect(job
, &KIO::CopyJob::copyingLinkDone
, this, &DolphinView::slotItemLinkCreatedFromJob
);
936 connect(job
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning*/) {
937 Q_EMIT
errorMessage(job
->errorString(), job
->error());
939 KIO::FileUndoManager::self()->recordCopyJob(job
);
943 void DolphinView::stopLoading()
945 m_model
->cancelDirectoryLoading();
948 void DolphinView::updatePalette()
950 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
955 QWidget
*viewport
= m_container
->viewport();
958 palette
.setColor(viewport
->backgroundRole(), color
);
959 viewport
->setPalette(palette
);
965 void DolphinView::abortTwoClicksRenaming()
967 m_twoClicksRenamingItemUrl
.clear();
968 m_twoClicksRenamingTimer
->stop();
971 bool DolphinView::eventFilter(QObject
*watched
, QEvent
*event
)
973 switch (event
->type()) {
974 case QEvent::PaletteChange
:
976 QPixmapCache::clear();
979 case QEvent::WindowActivate
:
980 case QEvent::WindowDeactivate
:
984 case QEvent::KeyPress
:
985 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
986 if (GeneralSettings::useTabForSwitchingSplitView()) {
987 QKeyEvent
*keyEvent
= static_cast<QKeyEvent
*>(event
);
988 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
989 Q_EMIT
toggleActiveViewRequested();
994 case QEvent::KeyRelease
:
995 if (static_cast<QKeyEvent
*>(event
)->key() == Qt::Key_Control
) {
996 m_controlWheelAccumulatedDelta
= 0;
999 case QEvent::FocusIn
:
1000 if (watched
== m_container
) {
1005 case QEvent::GraphicsSceneDragEnter
:
1006 if (watched
== m_view
) {
1008 abortTwoClicksRenaming();
1012 case QEvent::GraphicsSceneDragLeave
:
1013 if (watched
== m_view
) {
1018 case QEvent::GraphicsSceneDrop
:
1019 if (watched
== m_view
) {
1024 case QEvent::ToolTip
: {
1025 const auto helpEvent
= static_cast<QHelpEvent
*>(event
);
1026 if (tryShowNameToolTip(helpEvent
)) {
1029 } else if (m_hoveredColumnHeaderIndex
) {
1030 const auto rolesInfo
= KFileItemModel::rolesInformation();
1031 const auto visibleRole
= m_visibleRoles
.value(*m_hoveredColumnHeaderIndex
);
1033 for (const KFileItemModel::RoleInfo
&info
: rolesInfo
) {
1034 if (visibleRole
== info
.role
) {
1035 QToolTip::showText(helpEvent
->globalPos(), info
.tooltip
, this);
1046 return QWidget::eventFilter(watched
, event
);
1049 void DolphinView::wheelEvent(QWheelEvent
*event
)
1051 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
1052 m_controlWheelAccumulatedDelta
+= event
->angleDelta().y();
1054 if (m_controlWheelAccumulatedDelta
<= -QWheelEvent::DefaultDeltasPerStep
) {
1056 m_controlWheelAccumulatedDelta
+= QWheelEvent::DefaultDeltasPerStep
;
1057 } else if (m_controlWheelAccumulatedDelta
>= QWheelEvent::DefaultDeltasPerStep
) {
1059 m_controlWheelAccumulatedDelta
-= QWheelEvent::DefaultDeltasPerStep
;
1068 void DolphinView::hideEvent(QHideEvent
*event
)
1071 QWidget::hideEvent(event
);
1074 bool DolphinView::event(QEvent
*event
)
1076 if (event
->type() == QEvent::WindowDeactivate
) {
1078 * Dolphin leaves file preview tooltips open even when is not visible.
1080 * Hide tool-tip when Dolphin loses focus.
1083 abortTwoClicksRenaming();
1086 return QWidget::event(event
);
1089 void DolphinView::activate()
1094 void DolphinView::slotItemActivated(int index
)
1096 abortTwoClicksRenaming();
1098 const KFileItem item
= m_model
->fileItem(index
);
1099 if (!item
.isNull()) {
1100 Q_EMIT
itemActivated(item
);
1104 void DolphinView::slotItemsActivated(const KItemSet
&indexes
)
1106 Q_ASSERT(indexes
.count() >= 2);
1108 abortTwoClicksRenaming();
1110 const auto modifiers
= QGuiApplication::keyboardModifiers();
1112 if (indexes
.count() > 5) {
1113 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
1114 const int answer
= KMessageBox::warningContinueCancel(
1118 KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes
.count()), QStringLiteral("document-open")),
1119 KStandardGuiItem::cancel(),
1120 QStringLiteral("ConfirmOpenManyFolders"));
1121 if (answer
!= KMessageBox::PrimaryAction
&& answer
!= KMessageBox::Continue
) {
1126 KFileItemList items
;
1127 items
.reserve(indexes
.count());
1129 for (int index
: indexes
) {
1130 KFileItem item
= m_model
->fileItem(index
);
1131 const QUrl
&url
= openItemAsFolderUrl(item
);
1133 if (!url
.isEmpty()) {
1134 // Open folders in new tabs or in new windows depending on the modifier
1135 // The ctrl+shift behavior is ignored because we are handling multiple items
1136 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1137 if (modifiers
& Qt::ShiftModifier
&& !(modifiers
& Qt::ControlModifier
)) {
1138 Q_EMIT
windowRequested(url
);
1140 Q_EMIT
tabRequested(url
);
1147 if (items
.count() == 1) {
1148 Q_EMIT
itemActivated(items
.first());
1149 } else if (items
.count() > 1) {
1150 Q_EMIT
itemsActivated(items
);
1154 void DolphinView::slotItemMiddleClicked(int index
)
1156 const KFileItem
&item
= m_model
->fileItem(index
);
1157 const QUrl
&url
= openItemAsFolderUrl(item
, GeneralSettings::browseThroughArchives());
1158 const auto modifiers
= QGuiApplication::keyboardModifiers();
1159 if (!url
.isEmpty()) {
1160 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1161 if (modifiers
& Qt::ShiftModifier
) {
1162 Q_EMIT
activeTabRequested(url
);
1164 Q_EMIT
tabRequested(url
);
1166 } else if (isTabsForFilesEnabled()) {
1167 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1168 if (modifiers
& Qt::ShiftModifier
) {
1169 Q_EMIT
activeTabRequested(item
.url());
1171 Q_EMIT
tabRequested(item
.url());
1174 Q_EMIT
fileMiddleClickActivated(item
);
1178 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
&pos
)
1180 // Force emit of a selection changed signal before we request the
1181 // context menu, to update the edit-actions first. (See Bug 294013)
1182 if (m_selectionChangedTimer
->isActive()) {
1183 emitSelectionChangedSignal();
1185 if (m_twoClicksRenamingTimer
->isActive()) {
1186 abortTwoClicksRenaming();
1189 const KFileItem item
= m_model
->fileItem(index
);
1190 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, selectedItems(), url());
1193 void DolphinView::slotViewContextMenuRequested(const QPointF
&pos
)
1195 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), selectedItems(), url());
1198 void DolphinView::slotHeaderContextMenuRequested(const QPointF
&pos
)
1200 ViewProperties
props(viewPropertiesUrl());
1202 QPointer
<QMenu
> menu
= new QMenu(this);
1204 KItemListView
*view
= m_container
->controller()->view();
1205 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1207 bool indexingEnabled
= false;
1209 Baloo::IndexerConfig config
;
1210 indexingEnabled
= config
.fileIndexingEnabled();
1214 QMenu
*groupMenu
= nullptr;
1216 // Add all roles to the menu that can be shown or hidden by the user
1217 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1218 for (const KFileItemModel::RoleInfo
&info
: rolesInfo
) {
1219 if (info
.role
== "text") {
1220 // It should not be possible to hide the "text" role
1224 const QString text
= m_model
->roleDescription(info
.role
);
1225 QAction
*action
= nullptr;
1226 if (info
.group
.isEmpty()) {
1227 action
= menu
->addAction(text
);
1229 if (!groupMenu
|| info
.group
!= groupName
) {
1230 groupName
= info
.group
;
1231 groupMenu
= menu
->addMenu(groupName
);
1234 action
= groupMenu
->addAction(text
);
1237 action
->setCheckable(true);
1238 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1239 action
->setData(info
.role
);
1240 action
->setToolTip(info
.tooltip
);
1242 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) || (info
.requiresBaloo
) || (info
.requiresIndexer
&& indexingEnabled
);
1243 action
->setEnabled(enable
);
1246 menu
->addSeparator();
1248 QActionGroup
*widthsGroup
= new QActionGroup(menu
);
1249 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1251 QAction
*toggleSidePaddingAction
= menu
->addAction(i18nc("@action:inmenu", "Side Padding"));
1252 toggleSidePaddingAction
->setCheckable(true);
1253 toggleSidePaddingAction
->setChecked(layoutDirection() == Qt::LeftToRight
? view
->header()->leftPadding() > 0 : view
->header()->rightPadding() > 0);
1255 QAction
*autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1256 autoAdjustWidthsAction
->setCheckable(true);
1257 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1258 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1260 QAction
*customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1261 customWidthsAction
->setCheckable(true);
1262 customWidthsAction
->setChecked(!autoColumnWidths
);
1263 customWidthsAction
->setActionGroup(widthsGroup
);
1265 QAction
*action
= menu
->exec(pos
.toPoint());
1266 if (menu
&& action
) {
1267 KItemListHeader
*header
= view
->header();
1269 if (action
== autoAdjustWidthsAction
) {
1270 // Clear the column-widths from the viewproperties and turn on
1271 // the automatic resizing of the columns
1272 props
.setHeaderColumnWidths(QList
<int>());
1273 header
->setAutomaticColumnResizing(true);
1274 } else if (action
== customWidthsAction
) {
1275 // Apply the current column-widths as custom column-widths and turn
1276 // off the automatic resizing of the columns
1277 QList
<int> columnWidths
;
1278 const auto visibleRoles
= view
->visibleRoles();
1279 columnWidths
.reserve(visibleRoles
.count());
1280 for (const QByteArray
&role
: visibleRoles
) {
1281 columnWidths
.append(header
->columnWidth(role
));
1283 props
.setHeaderColumnWidths(columnWidths
);
1284 header
->setAutomaticColumnResizing(false);
1285 } else if (action
== toggleSidePaddingAction
) {
1286 if (toggleSidePaddingAction
->isChecked()) {
1287 header
->setSidePadding(20, 20);
1289 header
->setSidePadding(0, 0);
1292 // Show or hide the selected role
1293 const QByteArray selectedRole
= action
->data().toByteArray();
1295 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1296 if (action
->isChecked()) {
1297 visibleRoles
.append(selectedRole
);
1299 visibleRoles
.removeOne(selectedRole
);
1302 view
->setVisibleRoles(visibleRoles
);
1303 props
.setVisibleRoles(visibleRoles
);
1305 QList
<int> columnWidths
;
1306 if (!header
->automaticColumnResizing()) {
1307 const auto visibleRoles
= view
->visibleRoles();
1308 columnWidths
.reserve(visibleRoles
.count());
1309 for (const QByteArray
&role
: visibleRoles
) {
1310 columnWidths
.append(header
->columnWidth(role
));
1313 props
.setHeaderColumnWidths(columnWidths
);
1320 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
&role
, qreal current
)
1322 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1324 ViewProperties
props(viewPropertiesUrl());
1325 QList
<int> columnWidths
= props
.headerColumnWidths();
1326 if (columnWidths
.count() != visibleRoles
.count()) {
1327 columnWidths
.clear();
1328 columnWidths
.reserve(visibleRoles
.count());
1329 const KItemListHeader
*header
= m_view
->header();
1330 for (const QByteArray
&role
: visibleRoles
) {
1331 const int width
= header
->columnWidth(role
);
1332 columnWidths
.append(width
);
1336 const int roleIndex
= visibleRoles
.indexOf(role
);
1337 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1338 columnWidths
[roleIndex
] = current
;
1340 props
.setHeaderColumnWidths(columnWidths
);
1343 void DolphinView::slotSidePaddingWidthChanged(qreal leftPaddingWidth
, qreal rightPaddingWidth
)
1345 ViewProperties
props(viewPropertiesUrl());
1346 DetailsModeSettings::setLeftPadding(int(leftPaddingWidth
));
1347 DetailsModeSettings::setRightPadding(int(rightPaddingWidth
));
1348 m_view
->writeSettings();
1351 void DolphinView::slotItemHovered(int index
)
1353 const KFileItem item
= m_model
->fileItem(index
);
1355 if (GeneralSettings::showToolTips() && !m_dragging
) {
1356 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1357 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1358 itemRect
.moveTo(pos
);
1361 auto nativeParent
= nativeParentWidget();
1363 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParent
->windowHandle());
1368 Q_EMIT
requestItemInfo(item
);
1371 void DolphinView::slotItemUnhovered(int index
)
1375 Q_EMIT
requestItemInfo(KFileItem());
1378 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
*event
)
1381 KFileItem destItem
= m_model
->fileItem(index
);
1382 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1383 // Use the URL of the view as drop target if the item is no directory
1385 destItem
= m_model
->rootItem();
1388 // The item represents a directory or desktop-file
1389 destUrl
= destItem
.mostLocalUrl();
1392 QDropEvent
dropEvent(event
->pos().toPoint(), event
->possibleActions(), event
->mimeData(), event
->buttons(), event
->modifiers());
1393 dropUrls(destUrl
, &dropEvent
, this);
1398 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1400 KIO::DropJob
*job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1403 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1405 if (destUrl
== url()) {
1406 // Mark the dropped urls as selected.
1407 m_clearSelectionBeforeSelectingNewItems
= true;
1408 m_markFirstNewlySelectedItemAsCurrent
= true;
1409 m_selectJobCreatedItems
= true;
1410 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1411 connect(job
, &KIO::DropJob::copyJobStarted
, this, [this](const KIO::CopyJob
*copyJob
) {
1412 connect(copyJob
, &KIO::CopyJob::copying
, this, &DolphinView::slotItemCreatedFromJob
);
1413 connect(copyJob
, &KIO::CopyJob::moving
, this, &DolphinView::slotItemCreatedFromJob
);
1414 connect(copyJob
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning*/) {
1415 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1417 connect(copyJob
, &KIO::CopyJob::linking
, this, [this](KIO::Job
*job
, const QString
&src
, const QUrl
&dest
) {
1420 slotItemCreated(dest
);
1427 void DolphinView::slotModelChanged(KItemModelBase
*current
, KItemModelBase
*previous
)
1429 if (previous
!= nullptr) {
1430 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1431 KFileItemModel
*fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1432 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1433 m_versionControlObserver
->setModel(nullptr);
1437 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1438 KFileItemModel
*fileItemModel
= static_cast<KFileItemModel
*>(current
);
1439 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1440 m_versionControlObserver
->setModel(fileItemModel
);
1444 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1450 if (buttons
& Qt::BackButton
) {
1451 Q_EMIT
goBackRequested();
1452 } else if (buttons
& Qt::ForwardButton
) {
1453 Q_EMIT
goForwardRequested();
1457 void DolphinView::slotSelectedItemTextPressed(int index
)
1459 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1460 const KFileItem item
= m_model
->fileItem(index
);
1461 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1462 if (capabilities
.supportsMoving()) {
1463 m_twoClicksRenamingItemUrl
= item
.url();
1464 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1469 void DolphinView::slotItemCreatedFromJob(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1471 slotItemCreated(to
);
1474 void DolphinView::slotItemLinkCreatedFromJob(KIO::Job
*, const QUrl
&, const QString
&, const QUrl
&to
)
1476 slotItemCreated(to
);
1479 void DolphinView::slotItemCreated(const QUrl
&url
)
1481 if (m_markFirstNewlySelectedItemAsCurrent
) {
1482 markUrlAsCurrent(url
);
1483 m_markFirstNewlySelectedItemAsCurrent
= false;
1485 if (m_selectJobCreatedItems
&& !m_selectedUrls
.contains(url
)) {
1486 m_selectedUrls
<< url
;
1490 void DolphinView::onDirectoryLoadingCompletedAfterJob()
1492 // the model should now contain all the items created by the job
1493 m_selectJobCreatedItems
= true; // to make sure we overwrite selection
1494 // update the view: scroll into View and selection
1496 m_selectJobCreatedItems
= false;
1497 m_selectedUrls
.clear();
1500 void DolphinView::slotJobResult(KJob
*job
)
1502 if (job
->error() && job
->error() != KIO::ERR_USER_CANCELED
) {
1503 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1505 if (!m_selectJobCreatedItems
) {
1506 m_selectedUrls
.clear();
1509 if (!m_selectedUrls
.isEmpty()) {
1510 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1512 updateSelectionState();
1513 if (!m_selectedUrls
.isEmpty()) {
1514 // not all urls were found, the model may not be up to date
1515 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::onDirectoryLoadingCompletedAfterJob
, Qt::SingleShotConnection
);
1517 m_selectJobCreatedItems
= false;
1518 m_selectedUrls
.clear();
1523 void DolphinView::slotSelectionChanged(const KItemSet
¤t
, const KItemSet
&previous
)
1525 m_selectNextItem
= false;
1526 const int currentCount
= current
.count();
1527 const int previousCount
= previous
.count();
1528 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) || (currentCount
> 0 && previousCount
== 0);
1530 // If nothing has been selected before and something got selected (or if something
1531 // was selected before and now nothing is selected) the selectionChangedSignal must
1532 // be emitted asynchronously as fast as possible to update the edit-actions.
1533 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1534 m_selectionChangedTimer
->start();
1537 void DolphinView::emitSelectionChangedSignal()
1539 m_selectionChangedTimer
->stop();
1540 Q_EMIT
selectionChanged(selectedItems());
1543 void DolphinView::slotStatJobResult(KJob
*job
)
1545 int folderCount
= 0;
1547 KIO::filesize_t totalFileSize
= 0;
1548 bool countFileSize
= true;
1550 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1551 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1552 // We have a precomputed value.
1553 totalFileSize
= static_cast<KIO::filesize_t
>(entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1554 countFileSize
= false;
1557 const int itemCount
= m_model
->count();
1558 for (int i
= 0; i
< itemCount
; ++i
) {
1559 const KFileItem item
= m_model
->fileItem(i
);
1564 if (countFileSize
) {
1565 totalFileSize
+= item
.size();
1569 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1572 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1574 ViewProperties
props(viewPropertiesUrl());
1575 props
.setSortFoldersFirst(foldersFirst
);
1577 m_model
->setSortDirectoriesFirst(foldersFirst
);
1579 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1582 void DolphinView::updateSortHiddenLast(bool hiddenLast
)
1584 ViewProperties
props(viewPropertiesUrl());
1585 props
.setSortHiddenLast(hiddenLast
);
1587 m_model
->setSortHiddenLast(hiddenLast
);
1589 Q_EMIT
sortHiddenLastChanged(hiddenLast
);
1592 QPair
<bool, QString
> DolphinView::pasteInfo() const
1594 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1595 QPair
<bool, QString
> info
;
1596 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1600 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1602 m_tabsForFiles
= tabsForFiles
;
1605 bool DolphinView::isTabsForFilesEnabled() const
1607 return m_tabsForFiles
;
1610 bool DolphinView::itemsExpandable() const
1612 return m_mode
== DetailsView
;
1615 bool DolphinView::isExpanded(const KFileItem
&item
) const
1617 Q_ASSERT(item
.isDir());
1618 Q_ASSERT(items().contains(item
));
1619 if (!itemsExpandable()) {
1622 return m_model
->isExpanded(m_model
->index(item
));
1625 void DolphinView::restoreState(QDataStream
&stream
)
1627 // Read the version number of the view state and check if the version is supported.
1628 quint32 version
= 0;
1631 // The version of the view state isn't supported, we can't restore it.
1635 // Restore the current item that had the keyboard focus
1636 stream
>> m_currentItemUrl
;
1638 // Restore the previously selected items
1639 stream
>> m_selectedUrls
;
1641 // Restore the view position
1642 stream
>> m_restoredContentsPosition
;
1644 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1647 m_model
->restoreExpandedDirectories(urls
);
1650 void DolphinView::saveState(QDataStream
&stream
)
1652 stream
<< quint32(1); // View state version
1654 // Save the current item that has the keyboard focus
1655 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1656 if (currentIndex
!= -1) {
1657 KFileItem item
= m_model
->fileItem(currentIndex
);
1658 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1659 QUrl currentItemUrl
= item
.url();
1660 stream
<< currentItemUrl
;
1665 // Save the selected urls
1666 stream
<< selectedItems().urlList();
1668 // Save view position
1669 const qreal x
= m_container
->horizontalScrollBar()->value();
1670 const qreal y
= m_container
->verticalScrollBar()->value();
1671 stream
<< QPoint(x
, y
);
1673 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1674 stream
<< m_model
->expandedDirectories();
1677 KFileItem
DolphinView::rootItem() const
1679 return m_model
->rootItem();
1682 void DolphinView::setViewPropertiesContext(const QString
&context
)
1684 m_viewPropertiesContext
= context
;
1687 QString
DolphinView::viewPropertiesContext() const
1689 return m_viewPropertiesContext
;
1692 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
&item
, const bool browseThroughArchives
)
1694 if (item
.isNull()) {
1698 QUrl url
= item
.targetUrl();
1704 if (item
.isMimeTypeKnown()) {
1705 const QString
&mimetype
= item
.mimetype();
1707 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1708 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1709 // zip:/<path>/ when clicking on a zip file, etc.
1710 // The .protocol file specifies the mimetype that the kioslave handles.
1711 // Note that we don't use mimetype inheritance since we don't want to
1712 // open OpenDocument files as zip folders...
1713 const QString
&protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1714 if (!protocol
.isEmpty()) {
1715 url
.setScheme(protocol
);
1720 if (mimetype
== QLatin1String("application/x-desktop")) {
1721 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1722 KDesktopFile
desktopFile(url
.toLocalFile());
1723 if (desktopFile
.hasLinkType()) {
1724 const QString linkUrl
= desktopFile
.readUrl();
1725 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1726 return QUrl::fromUserInput(linkUrl
);
1735 void DolphinView::resetZoomLevel()
1737 ViewModeSettings settings
{m_mode
};
1738 settings
.useDefaults(true);
1739 const int defaultIconSize
= settings
.iconSize();
1740 settings
.useDefaults(false);
1742 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize
, defaultIconSize
)));
1745 void DolphinView::observeCreatedItem(const QUrl
&url
)
1748 forceUrlsSelection(url
, {url
});
1752 void DolphinView::slotDirectoryRedirection(const QUrl
&oldUrl
, const QUrl
&newUrl
)
1754 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1755 Q_EMIT
redirection(oldUrl
, newUrl
);
1756 m_url
= newUrl
; // #186947
1760 void DolphinView::updateSelectionState()
1762 if (!m_selectedUrls
.isEmpty()) {
1763 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1765 const bool shouldScrollToCurrentItem
= m_clearSelectionBeforeSelectingNewItems
;
1766 // if there is a selection already, leave it that way
1767 // unless some drop/paste job are in the process of creating items
1768 if (!selectionManager
->hasSelection() || m_selectJobCreatedItems
) {
1769 if (m_clearSelectionBeforeSelectingNewItems
) {
1770 selectionManager
->clearSelection();
1771 m_clearSelectionBeforeSelectingNewItems
= false;
1774 KItemSet selectedItems
= selectionManager
->selectedItems();
1776 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1777 while (it
!= m_selectedUrls
.end()) {
1778 const int index
= m_model
->index(*it
);
1780 selectedItems
.insert(index
);
1781 it
= m_selectedUrls
.erase(it
);
1787 if (!selectedItems
.isEmpty()) {
1788 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1789 selectionManager
->setSelectedItems(selectedItems
);
1790 if (shouldScrollToCurrentItem
) {
1791 m_view
->scrollToItem(selectedItems
.first());
1798 void DolphinView::updateViewState()
1800 if (m_currentItemUrl
!= QUrl()) {
1801 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1803 // if there is a selection already, leave it that way
1804 if (!selectionManager
->hasSelection()) {
1805 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1806 if (currentIndex
!= -1) {
1807 selectionManager
->setCurrentItem(currentIndex
);
1809 // scroll to current item and reset the state
1810 if (m_scrollToCurrentItem
) {
1811 m_view
->scrollToItem(currentIndex
, KItemListView::ViewItemPosition::Middle
);
1812 m_scrollToCurrentItem
= false;
1814 m_currentItemUrl
= QUrl();
1816 selectionManager
->setCurrentItem(0);
1819 m_currentItemUrl
= QUrl();
1823 if (!m_restoredContentsPosition
.isNull()) {
1824 const int x
= m_restoredContentsPosition
.x();
1825 const int y
= m_restoredContentsPosition
.y();
1826 m_restoredContentsPosition
= QPoint();
1828 m_container
->horizontalScrollBar()->setValue(x
);
1829 m_container
->verticalScrollBar()->setValue(y
);
1832 updateSelectionState();
1835 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1837 if (GeneralSettings::showToolTips()) {
1839 m_toolTipManager
->hideToolTip(behavior
);
1843 } else if (m_mode
== DolphinView::IconsView
) {
1844 QToolTip::hideText();
1848 bool DolphinView::handleSpaceAsNormalKey() const
1850 return !m_container
->hasFocus() || m_container
->controller()->isSearchAsYouTypeActive();
1853 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1855 const KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1857 // verify that only one item is selected
1858 if (selectionManager
->selectedItems().count() == 1) {
1859 const int index
= selectionManager
->currentItem();
1860 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1862 // check if the selected item was the same item that started the twoClicksRenaming
1863 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1864 renameSelectedItems();
1869 void DolphinView::slotTrashFileFinished(KJob
*job
)
1871 if (job
->error() == 0) {
1872 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1873 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1874 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1875 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1879 void DolphinView::slotDeleteFileFinished(KJob
*job
)
1881 if (job
->error() == 0) {
1882 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1883 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1884 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1885 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1889 void DolphinView::selectNextItem()
1891 if (m_active
&& m_selectNextItem
) {
1892 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1893 if (selectedItems().isEmpty()) {
1894 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1897 const auto lastSelectedIndex
= m_model
->index(selectedItems().constLast());
1898 if (lastSelectedIndex
< 0) {
1899 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1902 auto nextItem
= lastSelectedIndex
+ 1;
1903 if (nextItem
>= itemsCount()) {
1904 nextItem
= lastSelectedIndex
- selectedItemsCount();
1906 if (nextItem
>= 0) {
1907 selectionManager
->setSelected(nextItem
, 1);
1908 selectionManager
->beginAnchoredSelection(nextItem
);
1910 m_selectNextItem
= false;
1914 void DolphinView::slotRenamingResult(KJob
*job
)
1916 // Change model data after renaming has succeeded. On failure we do nothing.
1917 // If there is already an item with the newUrl, the copyjob will open a dialog for it, and
1918 // KFileItemModel will update the data when the dir lister signals that the file name has changed.
1919 if (!job
->error()) {
1920 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1922 const QUrl newUrl
= copyJob
->destUrl();
1923 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1924 const int index
= m_model
->index(newUrl
);
1925 if (m_model
->index(oldUrl
) == index
) {
1926 QHash
<QByteArray
, QVariant
> data
;
1927 data
.insert("text", newUrl
.fileName());
1928 m_model
->setData(index
, data
);
1933 void DolphinView::slotDirectoryLoadingStarted()
1935 m_loadingState
= LoadingState::Loading
;
1936 updatePlaceholderLabel();
1938 // Disable the writestate temporary until it can be determined in a fast way
1939 // in DolphinView::slotDirectoryLoadingCompleted()
1940 if (m_isFolderWritable
) {
1941 m_isFolderWritable
= false;
1942 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1945 Q_EMIT
directoryLoadingStarted();
1948 void DolphinView::slotDirectoryLoadingCompleted()
1950 m_loadingState
= LoadingState::Completed
;
1952 // Update the view-state. This has to be done asynchronously
1953 // because the view might not be in its final state yet.
1954 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1956 // Update the placeholder label in case we found that the folder was empty
1959 Q_EMIT
directoryLoadingCompleted();
1962 updatePlaceholderLabel();
1963 updateWritableState();
1966 void DolphinView::slotDirectoryLoadingCanceled()
1968 m_loadingState
= LoadingState::Canceled
;
1970 updatePlaceholderLabel();
1972 Q_EMIT
directoryLoadingCanceled();
1975 void DolphinView::slotItemsChanged()
1977 m_assureVisibleCurrentIndex
= false;
1980 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1983 Q_ASSERT(m_model
->sortOrder() == current
);
1985 ViewProperties
props(viewPropertiesUrl());
1986 props
.setSortOrder(current
);
1988 Q_EMIT
sortOrderChanged(current
);
1991 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
¤t
, const QByteArray
&previous
)
1994 Q_ASSERT(m_model
->sortRole() == current
);
1996 ViewProperties
props(viewPropertiesUrl());
1997 props
.setSortRole(current
);
1999 Q_EMIT
sortRoleChanged(current
);
2002 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
2005 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
2007 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
2009 m_visibleRoles
= current
;
2011 ViewProperties
props(viewPropertiesUrl());
2012 props
.setVisibleRoles(m_visibleRoles
);
2014 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
2017 void DolphinView::slotRoleEditingCanceled()
2019 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
2022 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
&role
, const QVariant
&value
)
2024 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
2026 const KFileItemList items
= selectedItems();
2027 if (items
.count() != 1) {
2031 if (role
== "text") {
2032 const KFileItem oldItem
= items
.first();
2033 const EditResult retVal
= value
.value
<EditResult
>();
2034 const QString newName
= retVal
.newName
;
2035 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
2036 const QUrl oldUrl
= oldItem
.url();
2038 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
2039 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
2042 // Confirm hiding file/directory by renaming inline
2043 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
2044 KGuiItem
yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden"));
2047 KMessageBox::questionTwoActions(this,
2048 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
2049 "Do you still want to rename it?")
2050 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
2051 "Do you still want to rename it?"),
2052 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
2054 KStandardGuiItem::cancel(),
2055 QStringLiteral("ConfirmHide"));
2057 if (code
== KMessageBox::SecondaryAction
) {
2063 KIO::Job
*job
= KIO::moveAs(oldUrl
, newUrl
);
2064 KJobWidgets::setWindow(job
, this);
2065 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
2066 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
2068 if (m_model
->index(newUrl
) < 0) {
2069 forceUrlsSelection(newUrl
, {newUrl
});
2070 updateSelectionState();
2072 // Only connect the result signal if there is no item with the new name
2073 // in the model yet, see bug 328262.
2074 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
2077 if (retVal
.direction
!= EditDone
) {
2078 const short indexShift
= retVal
.direction
== EditNext
? 1 : -1;
2079 m_container
->controller()->selectionManager()->setSelected(index
, 1, KItemListSelectionManager::Deselect
);
2080 m_container
->controller()->selectionManager()->setSelected(index
+ indexShift
, 1, KItemListSelectionManager::Select
);
2081 renameSelectedItems();
2086 void DolphinView::loadDirectory(const QUrl
&url
, bool reload
)
2088 if (!url
.isValid()) {
2089 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
2090 if (location
.isEmpty()) {
2091 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."), KIO::ERR_UNKNOWN
);
2093 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
), KIO::ERR_UNKNOWN
);
2099 m_model
->refreshDirectory(url
);
2101 m_model
->loadDirectory(url
);
2105 void DolphinView::applyViewProperties()
2107 const ViewProperties
props(viewPropertiesUrl());
2108 applyViewProperties(props
);
2111 void DolphinView::applyViewProperties(const ViewProperties
&props
)
2113 m_view
->beginTransaction();
2115 const Mode mode
= props
.viewMode();
2116 if (m_mode
!= mode
) {
2117 const Mode previousMode
= m_mode
;
2120 // Changing the mode might result in changing
2121 // the zoom level. Remember the old zoom level so
2122 // that zoomLevelChanged() can get emitted.
2123 const int oldZoomLevel
= m_view
->zoomLevel();
2126 Q_EMIT
modeChanged(m_mode
, previousMode
);
2128 if (m_view
->zoomLevel() != oldZoomLevel
) {
2129 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
2133 const bool hiddenFilesShown
= props
.hiddenFilesShown();
2134 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
2135 m_model
->setShowHiddenFiles(hiddenFilesShown
);
2136 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
2139 const bool groupedSorting
= props
.groupedSorting();
2140 if (groupedSorting
!= m_model
->groupedSorting()) {
2141 m_model
->setGroupedSorting(groupedSorting
);
2142 Q_EMIT
groupedSortingChanged(groupedSorting
);
2145 const QByteArray sortRole
= props
.sortRole();
2146 if (sortRole
!= m_model
->sortRole()) {
2147 m_model
->setSortRole(sortRole
);
2148 Q_EMIT
sortRoleChanged(sortRole
);
2151 const Qt::SortOrder sortOrder
= props
.sortOrder();
2152 if (sortOrder
!= m_model
->sortOrder()) {
2153 m_model
->setSortOrder(sortOrder
);
2154 Q_EMIT
sortOrderChanged(sortOrder
);
2157 const bool sortFoldersFirst
= props
.sortFoldersFirst();
2158 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
2159 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
2160 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
2163 const bool sortHiddenLast
= props
.sortHiddenLast();
2164 if (sortHiddenLast
!= m_model
->sortHiddenLast()) {
2165 m_model
->setSortHiddenLast(sortHiddenLast
);
2166 Q_EMIT
sortHiddenLastChanged(sortHiddenLast
);
2169 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
2170 if (visibleRoles
!= m_visibleRoles
) {
2171 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
2172 m_visibleRoles
= visibleRoles
;
2173 m_view
->setVisibleRoles(visibleRoles
);
2174 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
2177 const bool previewsShown
= props
.previewsShown();
2178 if (previewsShown
!= m_view
->previewsShown()) {
2179 const int oldZoomLevel
= zoomLevel();
2181 m_view
->setPreviewsShown(previewsShown
);
2182 Q_EMIT
previewsShownChanged(previewsShown
);
2184 // Changing the preview-state might result in a changed zoom-level
2185 if (oldZoomLevel
!= zoomLevel()) {
2186 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
2190 KItemListView
*itemListView
= m_container
->controller()->view();
2191 if (itemListView
->isHeaderVisible()) {
2192 KItemListHeader
*header
= itemListView
->header();
2193 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
2194 const int rolesCount
= m_visibleRoles
.count();
2195 if (headerColumnWidths
.count() == rolesCount
) {
2196 header
->setAutomaticColumnResizing(false);
2198 QHash
<QByteArray
, qreal
> columnWidths
;
2199 for (int i
= 0; i
< rolesCount
; ++i
) {
2200 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
2202 header
->setColumnWidths(columnWidths
);
2204 header
->setAutomaticColumnResizing(true);
2206 header
->setSidePadding(DetailsModeSettings::leftPadding(), DetailsModeSettings::rightPadding());
2209 m_view
->endTransaction();
2212 void DolphinView::applyModeToView()
2216 m_view
->setItemLayout(KFileItemListView::IconsLayout
);
2219 m_view
->setItemLayout(KFileItemListView::CompactLayout
);
2222 m_view
->setItemLayout(KFileItemListView::DetailsLayout
);
2230 void DolphinView::applyDynamicView()
2232 ViewProperties
props(viewPropertiesUrl());
2234 * - dynamic view is not enabled
2235 * - the current view mode is already Icon View
2236 * - dynamic view has previously changed the view mode
2238 if (!GeneralSettings::dynamicView() || m_mode
== IconsView
|| props
.dynamicViewPassed()) {
2242 uint imageAndVideoCount
= 0;
2243 uint checkedItems
= 0;
2244 const uint totalItems
= itemsCount();
2245 const KFileItemList itemList
= items();
2246 bool applyDynamicView
= false;
2248 for (const auto &file
: itemList
) {
2250 const QString type
= file
.mimetype().slice(0, 5);
2252 if (type
== "image" || type
== "video") {
2253 ++imageAndVideoCount
;
2254 // if 2/3 or more of the items are images/videos, dynamic view should be applied
2255 applyDynamicView
= imageAndVideoCount
>= (totalItems
* 2 / 3);
2256 if (applyDynamicView
) {
2259 } else if (checkedItems
- imageAndVideoCount
> totalItems
/ 3) {
2260 // if more than a third of the checked files are not media files, return
2265 if (!applyDynamicView
) {
2269 props
.setAutoSaveEnabled(!GeneralSettings::globalViewProps());
2270 props
.setDynamicViewPassed(true);
2271 props
.setViewMode(IconsView
);
2272 applyViewProperties(props
);
2275 void DolphinView::pasteToUrl(const QUrl
&url
)
2277 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
2278 KJobWidgets::setWindow(job
, this);
2279 m_clearSelectionBeforeSelectingNewItems
= true;
2280 m_markFirstNewlySelectedItemAsCurrent
= true;
2281 m_selectJobCreatedItems
= true;
2282 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
2283 connect(job
, &KIO::PasteJob::copyJobStarted
, this, [this](const KIO::CopyJob
*copyJob
) {
2284 connect(copyJob
, &KIO::CopyJob::copying
, this, &DolphinView::slotItemCreatedFromJob
);
2285 connect(copyJob
, &KIO::CopyJob::moving
, this, &DolphinView::slotItemCreatedFromJob
);
2286 connect(copyJob
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning*/) {
2287 Q_EMIT
errorMessage(job
->errorString(), job
->error());
2289 connect(copyJob
, &KIO::CopyJob::linking
, this, [this](KIO::Job
*job
, const QString
&src
, const QUrl
&dest
) {
2292 slotItemCreated(dest
);
2295 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
2298 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
2302 const KFileItemList items
= selectedItems();
2303 urls
.reserve(items
.count());
2304 for (const KFileItem
&item
: items
) {
2305 urls
.append(item
.url());
2308 if (itemsExpandable()) {
2309 // TODO: Check if we still need KDirModel for this in KDE 5.0
2310 urls
= KDirModel::simplifiedUrlList(urls
);
2316 QMimeData
*DolphinView::selectionMimeData() const
2318 const KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
2319 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
2321 return m_model
->createMimeData(selectedIndexes
);
2324 void DolphinView::updateWritableState()
2326 const bool wasFolderWritable
= m_isFolderWritable
;
2327 m_isFolderWritable
= false;
2329 KFileItem item
= m_model
->rootItem();
2330 if (item
.isNull()) {
2331 // Try to find out if the URL is writable even if the "root item" is
2332 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2333 item
= KFileItem(url());
2334 item
.setDelayedMimeTypes(true);
2337 KFileItemListProperties
capabilities(KFileItemList() << item
);
2338 m_isFolderWritable
= capabilities
.supportsWriting();
2340 if (m_isFolderWritable
!= wasFolderWritable
) {
2341 Q_EMIT
writeStateChanged(m_isFolderWritable
);
2345 bool DolphinView::isFolderWritable() const
2347 return m_isFolderWritable
;
2350 int DolphinView::horizontalScrollBarHeight() const
2352 if (m_container
&& m_container
->horizontalScrollBar() && m_container
->horizontalScrollBar()->isVisible()) {
2353 return m_container
->horizontalScrollBar()->height();
2358 void DolphinView::setStatusBarOffset(int offset
)
2360 KItemListView
*view
= m_container
->controller()->view();
2362 view
->setStatusBarOffset(offset
);
2366 QUrl
DolphinView::viewPropertiesUrl() const
2368 if (m_viewPropertiesContext
.isEmpty()) {
2373 url
.setScheme(m_url
.scheme());
2374 url
.setPath(m_viewPropertiesContext
);
2378 void DolphinView::forceUrlsSelection(const QUrl
¤t
, const QList
<QUrl
> &selected
)
2381 m_clearSelectionBeforeSelectingNewItems
= true;
2382 markUrlAsCurrent(current
);
2383 markUrlsAsSelected(selected
);
2386 void DolphinView::copyPathToClipboard()
2388 const KFileItemList list
= selectedItems();
2389 if (list
.isEmpty()) {
2392 const KFileItem
&item
= list
.at(0);
2393 QString path
= item
.localPath();
2394 if (path
.isEmpty()) {
2395 path
= item
.url().toDisplayString();
2397 QClipboard
*clipboard
= QApplication::clipboard();
2398 if (clipboard
== nullptr) {
2401 clipboard
->setText(QDir::toNativeSeparators(path
));
2404 void DolphinView::slotIncreaseZoom()
2406 setZoomLevel(zoomLevel() + 1);
2409 void DolphinView::slotDecreaseZoom()
2411 setZoomLevel(zoomLevel() - 1);
2414 void DolphinView::slotSwipeUp()
2416 Q_EMIT
goUpRequested();
2419 void DolphinView::showLoadingPlaceholder()
2421 m_placeholderLabel
->setText(i18n("Loading…"));
2422 m_placeholderLabel
->setVisible(true);
2423 #ifndef QT_NO_ACCESSIBILITY
2424 if (QAccessible::isActive()) {
2425 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
))->announceNewlyLoadedLocation(m_placeholderLabel
->text());
2430 void DolphinView::updatePlaceholderLabel()
2432 m_showLoadingPlaceholderTimer
->stop();
2433 if (itemsCount() > 0) {
2434 #ifndef QT_NO_ACCESSIBILITY
2435 if (QAccessible::isActive()) {
2436 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
))->announceNewlyLoadedLocation(QString());
2439 m_placeholderLabel
->setVisible(false);
2443 if (m_loadingState
== LoadingState::Loading
) {
2444 m_placeholderLabel
->setVisible(false);
2445 m_showLoadingPlaceholderTimer
->start();
2449 if (m_loadingState
== LoadingState::Canceled
) {
2450 m_placeholderLabel
->setText(i18n("Loading canceled"));
2451 } else if (!nameFilter().isEmpty()) {
2452 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2453 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2454 m_placeholderLabel
->setText(i18n("No items matching the search"));
2455 } else if (m_url
.scheme() == QLatin1String("trash") && m_url
.path() == QLatin1String("/")) {
2456 m_placeholderLabel
->setText(i18n("Trash is empty"));
2457 } else if (m_url
.scheme() == QLatin1String("tags")) {
2458 if (m_url
.path() == QLatin1Char('/')) {
2459 m_placeholderLabel
->setText(i18n("No tags"));
2461 const QString tagName
= m_url
.path().mid(1); // Remove leading /
2462 m_placeholderLabel
->setText(i18n("No files tagged with \"%1\"", tagName
));
2465 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2466 m_placeholderLabel
->setText(i18n("No recently used items"));
2467 } else if (m_url
.scheme() == QLatin1String("smb")) {
2468 m_placeholderLabel
->setText(i18n("No shared folders found"));
2469 } else if (m_url
.scheme() == QLatin1String("network")) {
2470 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2471 } else if (m_url
.scheme() == QLatin1String("mtp") && m_url
.path() == QLatin1String("/")) {
2472 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2473 } else if (m_url
.scheme() == QLatin1String("afc") && m_url
.path() == QLatin1String("/")) {
2474 m_placeholderLabel
->setText(i18n("No Apple devices found"));
2475 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2476 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2478 m_placeholderLabel
->setText(i18n("Folder is empty"));
2481 m_placeholderLabel
->setVisible(true);
2482 #ifndef QT_NO_ACCESSIBILITY
2483 if (QAccessible::isActive()) {
2484 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
))->announceNewlyLoadedLocation(m_placeholderLabel
->text());
2489 bool DolphinView::tryShowNameToolTip(QHelpEvent
*event
)
2491 if (!GeneralSettings::showToolTips() && m_mode
== DolphinView::IconsView
) {
2492 const std::optional
<int> index
= m_view
->itemAt(event
->pos());
2494 if (!index
.has_value()) {
2498 // Check whether the filename has been elided
2499 const bool isElided
= m_view
->isElided(index
.value());
2502 const KFileItem item
= m_model
->fileItem(index
.value());
2503 const QString text
= item
.text();
2504 const QPoint pos
= mapToGlobal(event
->pos());
2505 QToolTip::showText(pos
, text
, this);
2512 #include "moc_dolphinview.cpp"