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::setGroupRole(const QByteArray
&role
)
520 if (role
!= groupRole()) {
521 ViewProperties
props(viewPropertiesUrl());
522 props
.setGroupRole(role
);
524 KItemModelBase
*model
= m_container
->controller()->model();
525 model
->setGroupRole(role
);
527 Q_EMIT
groupRoleChanged(role
);
531 QByteArray
DolphinView::groupRole() const
533 const KItemModelBase
*model
= m_container
->controller()->model();
534 return model
->groupRole();
537 void DolphinView::setGroupOrder(Qt::SortOrder order
)
539 if (groupOrder() != order
) {
540 ViewProperties
props(viewPropertiesUrl());
541 props
.setGroupOrder(order
);
543 m_model
->setGroupOrder(order
);
545 Q_EMIT
groupOrderChanged(order
);
549 Qt::SortOrder
DolphinView::groupOrder() const
551 return m_model
->groupOrder();
554 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
556 if (sortFoldersFirst() != foldersFirst
) {
557 updateSortFoldersFirst(foldersFirst
);
561 bool DolphinView::sortFoldersFirst() const
563 return m_model
->sortDirectoriesFirst();
566 void DolphinView::setSortHiddenLast(bool hiddenLast
)
568 if (sortHiddenLast() != hiddenLast
) {
569 updateSortHiddenLast(hiddenLast
);
573 bool DolphinView::sortHiddenLast() const
575 return m_model
->sortHiddenLast();
578 void DolphinView::setVisibleRoles(const QList
<QByteArray
> &roles
)
580 const QList
<QByteArray
> previousRoles
= roles
;
582 ViewProperties
props(viewPropertiesUrl());
583 props
.setVisibleRoles(roles
);
585 m_visibleRoles
= roles
;
586 m_view
->setVisibleRoles(roles
);
588 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
591 QList
<QByteArray
> DolphinView::visibleRoles() const
593 return m_visibleRoles
;
596 void DolphinView::reload()
598 QByteArray viewState
;
599 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
600 saveState(saveStream
);
603 loadDirectory(url(), true);
605 QDataStream
restoreStream(viewState
);
606 restoreState(restoreStream
);
609 void DolphinView::readSettings()
611 const int oldZoomLevel
= m_view
->zoomLevel();
613 GeneralSettings::self()->load();
614 m_view
->readSettings();
615 applyViewProperties();
617 m_container
->controller()->setAutoActivationEnabled(GeneralSettings::autoExpandFolders());
619 const int newZoomLevel
= m_view
->zoomLevel();
620 if (newZoomLevel
!= oldZoomLevel
) {
621 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
625 void DolphinView::writeSettings()
627 GeneralSettings::self()->save();
628 m_view
->writeSettings();
631 void DolphinView::setNameFilter(const QString
&nameFilter
)
633 m_model
->setNameFilter(nameFilter
);
636 QString
DolphinView::nameFilter() const
638 return m_model
->nameFilter();
641 void DolphinView::setMimeTypeFilters(const QStringList
&filters
)
643 return m_model
->setMimeTypeFilters(filters
);
646 QStringList
DolphinView::mimeTypeFilters() const
648 return m_model
->mimeTypeFilters();
651 void DolphinView::requestStatusBarText()
653 if (m_statJobForStatusBarText
) {
654 // Kill the pending request.
655 m_statJobForStatusBarText
->kill();
658 if (m_container
->controller()->selectionManager()->hasSelection()) {
661 KIO::filesize_t totalFileSize
= 0;
663 // Give a summary of the status of the selected files
664 const KFileItemList list
= selectedItems();
665 for (const KFileItem
&item
: list
) {
670 totalFileSize
+= item
.size();
674 if (folderCount
+ fileCount
== 1) {
675 // If only one item is selected, show info about it
676 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
678 // At least 2 items are selected
679 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
681 } else { // has no selection
682 if (!m_model
->rootItem().url().isValid()) {
686 m_statJobForStatusBarText
= KIO::stat(m_model
->rootItem().url(), KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
687 connect(m_statJobForStatusBarText
, &KJob::result
, this, &DolphinView::slotStatJobResult
);
688 m_statJobForStatusBarText
->start();
692 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
, KIO::filesize_t totalFileSize
, const Selection selection
)
698 if (selection
== HasSelection
) {
699 // At least 2 items are selected because the case of 1 selected item is handled in
700 // DolphinView::requestStatusBarText().
701 foldersText
= i18ncp("@info:status", "1 folder selected", "%1 folders selected", folderCount
);
702 filesText
= i18ncp("@info:status", "1 file selected", "%1 files selected", fileCount
);
704 foldersText
= i18ncp("@info:status", "1 folder", "%1 folders", folderCount
);
705 filesText
= i18ncp("@info:status", "1 file", "%1 files", fileCount
);
708 if (fileCount
> 0 && folderCount
> 0) {
709 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)", foldersText
, filesText
, KFormat().formatByteSize(totalFileSize
));
710 } else if (fileCount
> 0) {
711 summary
= i18nc("@info:status files (size)", "%1 (%2)", filesText
, KFormat().formatByteSize(totalFileSize
));
712 } else if (folderCount
> 0) {
713 summary
= foldersText
;
715 summary
= i18nc("@info:status", "0 folders, 0 files");
717 Q_EMIT
statusBarTextChanged(summary
);
720 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
&items
) const
722 QList
<QAction
*> actions
;
724 if (items
.isEmpty()) {
725 const KFileItem item
= m_model
->rootItem();
726 if (!item
.isNull()) {
727 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
730 actions
= m_versionControlObserver
->actions(items
);
736 void DolphinView::setUrl(const QUrl
&url
)
748 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
750 // It is important to clear the items from the model before
751 // applying the view properties, otherwise expensive operations
752 // might be done on the existing items although they get cleared
753 // anyhow afterwards by loadDirectory().
755 applyViewProperties();
758 Q_EMIT
urlChanged(url
);
761 void DolphinView::selectAll()
763 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
764 selectionManager
->setSelected(0, m_model
->count());
767 void DolphinView::invertSelection()
769 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
770 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
773 void DolphinView::clearSelection()
775 m_selectJobCreatedItems
= false;
776 m_selectedUrls
.clear();
777 m_container
->controller()->selectionManager()->clearSelection();
780 void DolphinView::renameSelectedItems()
782 const KFileItemList items
= selectedItems();
783 if (items
.isEmpty()) {
787 if (items
.count() == 1 && GeneralSettings::renameInline()) {
788 const int index
= m_model
->index(items
.first());
792 &KItemListView::scrollingStopped
,
795 m_view
->editRole(index
, "text");
799 connect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
801 Qt::SingleShotConnection
);
802 m_view
->scrollToItem(index
);
805 KIO::RenameFileDialog
*dialog
= new KIO::RenameFileDialog(items
, this);
806 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
, this, [this, items
](const QList
<QUrl
> &urls
) {
807 // The model may have already been updated, so it's possible that we don't find the old items.
808 for (int i
= 0; i
< items
.count(); ++i
) {
809 const int index
= m_model
->index(items
[i
]);
811 QHash
<QByteArray
, QVariant
> data
;
812 data
.insert("text", urls
[i
].fileName());
813 m_model
->setData(index
, data
);
817 forceUrlsSelection(urls
.first(), urls
);
818 updateSelectionState();
820 connect(dialog
, &KIO::RenameFileDialog::error
, this, [this](KJob
*job
) {
821 KMessageBox::error(this, job
->errorString());
827 // Assure that the current index remains visible when KFileItemModel
828 // will notify the view about changed items (which might result in
829 // a changed sorting).
830 m_assureVisibleCurrentIndex
= true;
833 void DolphinView::trashSelectedItems()
835 const QList
<QUrl
> list
= simplifiedSelectedUrls();
837 using Iface
= KIO::AskUserActionInterface
;
838 auto *trashJob
= new KIO::DeleteOrTrashJob(list
, Iface::Trash
, Iface::DefaultConfirmation
, this);
839 connect(trashJob
, &KJob::result
, this, &DolphinView::slotTrashFileFinished
);
840 m_selectNextItem
= true;
844 void DolphinView::deleteSelectedItems()
846 const QList
<QUrl
> list
= simplifiedSelectedUrls();
848 using Iface
= KIO::AskUserActionInterface
;
849 auto *trashJob
= new KIO::DeleteOrTrashJob(list
, Iface::Delete
, Iface::DefaultConfirmation
, this);
850 connect(trashJob
, &KJob::result
, this, &DolphinView::slotDeleteFileFinished
);
851 m_selectNextItem
= true;
855 void DolphinView::cutSelectedItemsToClipboard()
857 QMimeData
*mimeData
= selectionMimeData();
858 KIO::setClipboardDataCut(mimeData
, true);
859 KUrlMimeData::exportUrlsToPortal(mimeData
);
860 QApplication::clipboard()->setMimeData(mimeData
);
863 void DolphinView::copySelectedItemsToClipboard()
865 QMimeData
*mimeData
= selectionMimeData();
866 KUrlMimeData::exportUrlsToPortal(mimeData
);
867 QApplication::clipboard()->setMimeData(mimeData
);
870 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
872 if (selection
.isEmpty() || !destinationUrl
.isValid()) {
876 m_clearSelectionBeforeSelectingNewItems
= true;
877 m_markFirstNewlySelectedItemAsCurrent
= true;
878 m_selectJobCreatedItems
= true;
880 KIO::CopyJob
*job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
881 KJobWidgets::setWindow(job
, this);
883 connect(job
, &KIO::CopyJob::result
, this, &DolphinView::slotJobResult
);
884 connect(job
, &KIO::CopyJob::copying
, this, &DolphinView::slotItemCreatedFromJob
);
885 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotItemCreatedFromJob
);
886 connect(job
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /* warning */) {
887 Q_EMIT
errorMessage(job
->errorString(), job
->error());
889 KIO::FileUndoManager::self()->recordCopyJob(job
);
892 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
894 if (selection
.isEmpty() || !destinationUrl
.isValid()) {
898 m_clearSelectionBeforeSelectingNewItems
= true;
899 m_markFirstNewlySelectedItemAsCurrent
= true;
900 m_selectJobCreatedItems
= true;
902 KIO::CopyJob
*job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
903 KJobWidgets::setWindow(job
, this);
905 connect(job
, &KIO::CopyJob::result
, this, &DolphinView::slotJobResult
);
906 connect(job
, &KIO::CopyJob::moving
, this, &DolphinView::slotItemCreatedFromJob
);
907 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotItemCreatedFromJob
);
908 connect(job
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning */) {
909 Q_EMIT
errorMessage(job
->errorString(), job
->error());
911 KIO::FileUndoManager::self()->recordCopyJob(job
);
914 void DolphinView::paste()
919 void DolphinView::pasteIntoFolder()
921 const KFileItemList items
= selectedItems();
922 if ((items
.count() == 1) && items
.first().isDir()) {
923 pasteToUrl(items
.first().url());
927 void DolphinView::duplicateSelectedItems()
929 const KFileItemList itemList
= selectedItems();
930 if (itemList
.isEmpty()) {
934 const QMimeDatabase db
;
936 m_clearSelectionBeforeSelectingNewItems
= true;
937 m_markFirstNewlySelectedItemAsCurrent
= true;
938 m_selectJobCreatedItems
= true;
940 // Duplicate all selected items and append "copy" to the end of the file name
941 // but before the filename extension, if present
942 for (const auto &item
: itemList
) {
943 const QUrl originalURL
= item
.url();
944 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
945 const QString originalFileName
= item
.name();
947 QString extension
= db
.suffixForFileName(originalFileName
);
949 QUrl duplicateURL
= originalURL
;
951 // No extension; new filename is "<oldfilename> copy"
952 if (extension
.isEmpty()) {
953 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
954 // There's an extension; new filename is "<oldfilename> copy.<extension>"
956 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
957 extension
= QLatin1String(".") + extension
;
958 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
959 // Preserve file's original filename extension in case the casing differs
960 // from what QMimeDatabase::suffixForFileName() returned
961 const QString originalExtension
= originalFileName
.right(extension
.size());
962 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
965 KIO::CopyJob
*job
= KIO::copyAs(originalURL
, duplicateURL
);
966 job
->setAutoRename(true);
967 KJobWidgets::setWindow(job
, this);
969 connect(job
, &KIO::CopyJob::result
, this, &DolphinView::slotJobResult
);
970 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotItemCreatedFromJob
);
971 connect(job
, &KIO::CopyJob::copyingLinkDone
, this, &DolphinView::slotItemLinkCreatedFromJob
);
972 connect(job
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning*/) {
973 Q_EMIT
errorMessage(job
->errorString(), job
->error());
975 KIO::FileUndoManager::self()->recordCopyJob(job
);
979 void DolphinView::stopLoading()
981 m_model
->cancelDirectoryLoading();
984 void DolphinView::updatePalette()
986 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
991 QWidget
*viewport
= m_container
->viewport();
994 palette
.setColor(viewport
->backgroundRole(), color
);
995 viewport
->setPalette(palette
);
1001 void DolphinView::abortTwoClicksRenaming()
1003 m_twoClicksRenamingItemUrl
.clear();
1004 m_twoClicksRenamingTimer
->stop();
1007 bool DolphinView::eventFilter(QObject
*watched
, QEvent
*event
)
1009 switch (event
->type()) {
1010 case QEvent::PaletteChange
:
1012 QPixmapCache::clear();
1015 case QEvent::WindowActivate
:
1016 case QEvent::WindowDeactivate
:
1020 case QEvent::KeyPress
:
1021 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
1022 if (GeneralSettings::useTabForSwitchingSplitView()) {
1023 QKeyEvent
*keyEvent
= static_cast<QKeyEvent
*>(event
);
1024 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
1025 Q_EMIT
toggleActiveViewRequested();
1030 case QEvent::KeyRelease
:
1031 if (static_cast<QKeyEvent
*>(event
)->key() == Qt::Key_Control
) {
1032 m_controlWheelAccumulatedDelta
= 0;
1035 case QEvent::FocusIn
:
1036 if (watched
== m_container
) {
1041 case QEvent::GraphicsSceneDragEnter
:
1042 if (watched
== m_view
) {
1044 abortTwoClicksRenaming();
1048 case QEvent::GraphicsSceneDragLeave
:
1049 if (watched
== m_view
) {
1054 case QEvent::GraphicsSceneDrop
:
1055 if (watched
== m_view
) {
1060 case QEvent::ToolTip
: {
1061 const auto helpEvent
= static_cast<QHelpEvent
*>(event
);
1062 if (tryShowNameToolTip(helpEvent
)) {
1065 } else if (m_hoveredColumnHeaderIndex
) {
1066 const auto rolesInfo
= KFileItemModel::rolesInformation();
1067 const auto visibleRole
= m_visibleRoles
.value(*m_hoveredColumnHeaderIndex
);
1069 for (const KFileItemModel::RoleInfo
&info
: rolesInfo
) {
1070 if (visibleRole
== info
.role
) {
1071 QToolTip::showText(helpEvent
->globalPos(), info
.tooltip
, this);
1082 return QWidget::eventFilter(watched
, event
);
1085 void DolphinView::wheelEvent(QWheelEvent
*event
)
1087 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
1088 m_controlWheelAccumulatedDelta
+= event
->angleDelta().y();
1090 if (m_controlWheelAccumulatedDelta
<= -QWheelEvent::DefaultDeltasPerStep
) {
1092 m_controlWheelAccumulatedDelta
+= QWheelEvent::DefaultDeltasPerStep
;
1093 } else if (m_controlWheelAccumulatedDelta
>= QWheelEvent::DefaultDeltasPerStep
) {
1095 m_controlWheelAccumulatedDelta
-= QWheelEvent::DefaultDeltasPerStep
;
1104 void DolphinView::hideEvent(QHideEvent
*event
)
1107 QWidget::hideEvent(event
);
1110 bool DolphinView::event(QEvent
*event
)
1112 if (event
->type() == QEvent::WindowDeactivate
) {
1114 * Dolphin leaves file preview tooltips open even when is not visible.
1116 * Hide tool-tip when Dolphin loses focus.
1119 abortTwoClicksRenaming();
1122 return QWidget::event(event
);
1125 void DolphinView::activate()
1130 void DolphinView::slotItemActivated(int index
)
1132 abortTwoClicksRenaming();
1134 const KFileItem item
= m_model
->fileItem(index
);
1135 if (!item
.isNull()) {
1136 Q_EMIT
itemActivated(item
);
1140 void DolphinView::slotItemsActivated(const KItemSet
&indexes
)
1142 Q_ASSERT(indexes
.count() >= 2);
1144 abortTwoClicksRenaming();
1146 const auto modifiers
= QGuiApplication::keyboardModifiers();
1148 if (indexes
.count() > 5) {
1149 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
1150 const int answer
= KMessageBox::warningContinueCancel(
1154 KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes
.count()), QStringLiteral("document-open")),
1155 KStandardGuiItem::cancel(),
1156 QStringLiteral("ConfirmOpenManyFolders"));
1157 if (answer
!= KMessageBox::PrimaryAction
&& answer
!= KMessageBox::Continue
) {
1162 KFileItemList items
;
1163 items
.reserve(indexes
.count());
1165 for (int index
: indexes
) {
1166 KFileItem item
= m_model
->fileItem(index
);
1167 const QUrl
&url
= openItemAsFolderUrl(item
);
1169 if (!url
.isEmpty()) {
1170 // Open folders in new tabs or in new windows depending on the modifier
1171 // The ctrl+shift behavior is ignored because we are handling multiple items
1172 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1173 if (modifiers
& Qt::ShiftModifier
&& !(modifiers
& Qt::ControlModifier
)) {
1174 Q_EMIT
windowRequested(url
);
1176 Q_EMIT
tabRequested(url
);
1183 if (items
.count() == 1) {
1184 Q_EMIT
itemActivated(items
.first());
1185 } else if (items
.count() > 1) {
1186 Q_EMIT
itemsActivated(items
);
1190 void DolphinView::slotItemMiddleClicked(int index
)
1192 const KFileItem
&item
= m_model
->fileItem(index
);
1193 const QUrl
&url
= openItemAsFolderUrl(item
, GeneralSettings::browseThroughArchives());
1194 const auto modifiers
= QGuiApplication::keyboardModifiers();
1195 if (!url
.isEmpty()) {
1196 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1197 if (modifiers
& Qt::ShiftModifier
) {
1198 Q_EMIT
activeTabRequested(url
);
1200 Q_EMIT
tabRequested(url
);
1202 } else if (isTabsForFilesEnabled()) {
1203 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1204 if (modifiers
& Qt::ShiftModifier
) {
1205 Q_EMIT
activeTabRequested(item
.url());
1207 Q_EMIT
tabRequested(item
.url());
1210 Q_EMIT
fileMiddleClickActivated(item
);
1214 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
&pos
)
1216 // Force emit of a selection changed signal before we request the
1217 // context menu, to update the edit-actions first. (See Bug 294013)
1218 if (m_selectionChangedTimer
->isActive()) {
1219 emitSelectionChangedSignal();
1221 if (m_twoClicksRenamingTimer
->isActive()) {
1222 abortTwoClicksRenaming();
1225 const KFileItem item
= m_model
->fileItem(index
);
1226 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, selectedItems(), url());
1229 void DolphinView::slotViewContextMenuRequested(const QPointF
&pos
)
1231 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), selectedItems(), url());
1234 void DolphinView::slotHeaderContextMenuRequested(const QPointF
&pos
)
1236 ViewProperties
props(viewPropertiesUrl());
1238 QPointer
<QMenu
> menu
= new QMenu(this);
1240 KItemListView
*view
= m_container
->controller()->view();
1241 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1243 bool indexingEnabled
= false;
1245 Baloo::IndexerConfig config
;
1246 indexingEnabled
= config
.fileIndexingEnabled();
1250 QMenu
*groupMenu
= nullptr;
1252 // Add all roles to the menu that can be shown or hidden by the user
1253 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1254 for (const KFileItemModel::RoleInfo
&info
: rolesInfo
) {
1255 if (info
.role
== "text") {
1256 // It should not be possible to hide the "text" role
1260 const QString text
= m_model
->roleDescription(info
.role
);
1261 QAction
*action
= nullptr;
1262 if (info
.group
.isEmpty()) {
1263 action
= menu
->addAction(text
);
1265 if (!groupMenu
|| info
.group
!= groupName
) {
1266 groupName
= info
.group
;
1267 groupMenu
= menu
->addMenu(groupName
);
1270 action
= groupMenu
->addAction(text
);
1273 action
->setCheckable(true);
1274 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1275 action
->setData(info
.role
);
1276 action
->setToolTip(info
.tooltip
);
1278 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) || (info
.requiresBaloo
) || (info
.requiresIndexer
&& indexingEnabled
);
1279 action
->setEnabled(enable
);
1282 menu
->addSeparator();
1284 QActionGroup
*widthsGroup
= new QActionGroup(menu
);
1285 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1287 QAction
*toggleSidePaddingAction
= menu
->addAction(i18nc("@action:inmenu", "Side Padding"));
1288 toggleSidePaddingAction
->setCheckable(true);
1289 toggleSidePaddingAction
->setChecked(layoutDirection() == Qt::LeftToRight
? view
->header()->leftPadding() > 0 : view
->header()->rightPadding() > 0);
1291 QAction
*autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1292 autoAdjustWidthsAction
->setCheckable(true);
1293 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1294 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1296 QAction
*customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1297 customWidthsAction
->setCheckable(true);
1298 customWidthsAction
->setChecked(!autoColumnWidths
);
1299 customWidthsAction
->setActionGroup(widthsGroup
);
1301 QAction
*action
= menu
->exec(pos
.toPoint());
1302 if (menu
&& action
) {
1303 KItemListHeader
*header
= view
->header();
1305 if (action
== autoAdjustWidthsAction
) {
1306 // Clear the column-widths from the viewproperties and turn on
1307 // the automatic resizing of the columns
1308 props
.setHeaderColumnWidths(QList
<int>());
1309 header
->setAutomaticColumnResizing(true);
1310 } else if (action
== customWidthsAction
) {
1311 // Apply the current column-widths as custom column-widths and turn
1312 // off the automatic resizing of the columns
1313 QList
<int> columnWidths
;
1314 const auto visibleRoles
= view
->visibleRoles();
1315 columnWidths
.reserve(visibleRoles
.count());
1316 for (const QByteArray
&role
: visibleRoles
) {
1317 columnWidths
.append(header
->columnWidth(role
));
1319 props
.setHeaderColumnWidths(columnWidths
);
1320 header
->setAutomaticColumnResizing(false);
1321 } else if (action
== toggleSidePaddingAction
) {
1322 if (toggleSidePaddingAction
->isChecked()) {
1323 header
->setSidePadding(20, 20);
1325 header
->setSidePadding(0, 0);
1328 // Show or hide the selected role
1329 const QByteArray selectedRole
= action
->data().toByteArray();
1331 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1332 if (action
->isChecked()) {
1333 visibleRoles
.append(selectedRole
);
1335 visibleRoles
.removeOne(selectedRole
);
1338 view
->setVisibleRoles(visibleRoles
);
1339 props
.setVisibleRoles(visibleRoles
);
1341 QList
<int> columnWidths
;
1342 if (!header
->automaticColumnResizing()) {
1343 const auto visibleRoles
= view
->visibleRoles();
1344 columnWidths
.reserve(visibleRoles
.count());
1345 for (const QByteArray
&role
: visibleRoles
) {
1346 columnWidths
.append(header
->columnWidth(role
));
1349 props
.setHeaderColumnWidths(columnWidths
);
1356 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
&role
, qreal current
)
1358 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1360 ViewProperties
props(viewPropertiesUrl());
1361 QList
<int> columnWidths
= props
.headerColumnWidths();
1362 if (columnWidths
.count() != visibleRoles
.count()) {
1363 columnWidths
.clear();
1364 columnWidths
.reserve(visibleRoles
.count());
1365 const KItemListHeader
*header
= m_view
->header();
1366 for (const QByteArray
&role
: visibleRoles
) {
1367 const int width
= header
->columnWidth(role
);
1368 columnWidths
.append(width
);
1372 const int roleIndex
= visibleRoles
.indexOf(role
);
1373 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1374 columnWidths
[roleIndex
] = current
;
1376 props
.setHeaderColumnWidths(columnWidths
);
1379 void DolphinView::slotSidePaddingWidthChanged(qreal leftPaddingWidth
, qreal rightPaddingWidth
)
1381 ViewProperties
props(viewPropertiesUrl());
1382 DetailsModeSettings::setLeftPadding(int(leftPaddingWidth
));
1383 DetailsModeSettings::setRightPadding(int(rightPaddingWidth
));
1384 m_view
->writeSettings();
1387 void DolphinView::slotItemHovered(int index
)
1389 const KFileItem item
= m_model
->fileItem(index
);
1391 if (GeneralSettings::showToolTips() && !m_dragging
) {
1392 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1393 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1394 itemRect
.moveTo(pos
);
1397 auto nativeParent
= nativeParentWidget();
1399 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParent
->windowHandle());
1404 Q_EMIT
requestItemInfo(item
);
1407 void DolphinView::slotItemUnhovered(int index
)
1411 Q_EMIT
requestItemInfo(KFileItem());
1414 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
*event
)
1417 KFileItem destItem
= m_model
->fileItem(index
);
1418 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1419 // Use the URL of the view as drop target if the item is no directory
1421 destItem
= m_model
->rootItem();
1424 // The item represents a directory or desktop-file
1425 destUrl
= destItem
.mostLocalUrl();
1428 QDropEvent
dropEvent(event
->pos().toPoint(), event
->possibleActions(), event
->mimeData(), event
->buttons(), event
->modifiers());
1429 dropUrls(destUrl
, &dropEvent
, this);
1434 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1436 KIO::DropJob
*job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1439 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1441 if (destUrl
== url()) {
1442 // Mark the dropped urls as selected.
1443 m_clearSelectionBeforeSelectingNewItems
= true;
1444 m_markFirstNewlySelectedItemAsCurrent
= true;
1445 m_selectJobCreatedItems
= true;
1446 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1447 connect(job
, &KIO::DropJob::copyJobStarted
, this, [this](const KIO::CopyJob
*copyJob
) {
1448 connect(copyJob
, &KIO::CopyJob::copying
, this, &DolphinView::slotItemCreatedFromJob
);
1449 connect(copyJob
, &KIO::CopyJob::moving
, this, &DolphinView::slotItemCreatedFromJob
);
1450 connect(copyJob
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning*/) {
1451 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1453 connect(copyJob
, &KIO::CopyJob::linking
, this, [this](KIO::Job
*job
, const QString
&src
, const QUrl
&dest
) {
1456 slotItemCreated(dest
);
1463 void DolphinView::slotModelChanged(KItemModelBase
*current
, KItemModelBase
*previous
)
1465 if (previous
!= nullptr) {
1466 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1467 KFileItemModel
*fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1468 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1469 m_versionControlObserver
->setModel(nullptr);
1473 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1474 KFileItemModel
*fileItemModel
= static_cast<KFileItemModel
*>(current
);
1475 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1476 m_versionControlObserver
->setModel(fileItemModel
);
1480 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1486 if (buttons
& Qt::BackButton
) {
1487 Q_EMIT
goBackRequested();
1488 } else if (buttons
& Qt::ForwardButton
) {
1489 Q_EMIT
goForwardRequested();
1493 void DolphinView::slotSelectedItemTextPressed(int index
)
1495 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1496 const KFileItem item
= m_model
->fileItem(index
);
1497 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1498 if (capabilities
.supportsMoving()) {
1499 m_twoClicksRenamingItemUrl
= item
.url();
1500 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1505 void DolphinView::slotItemCreatedFromJob(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1507 slotItemCreated(to
);
1510 void DolphinView::slotItemLinkCreatedFromJob(KIO::Job
*, const QUrl
&, const QString
&, const QUrl
&to
)
1512 slotItemCreated(to
);
1515 void DolphinView::slotItemCreated(const QUrl
&url
)
1517 if (m_markFirstNewlySelectedItemAsCurrent
) {
1518 markUrlAsCurrent(url
);
1519 m_markFirstNewlySelectedItemAsCurrent
= false;
1521 if (m_selectJobCreatedItems
&& !m_selectedUrls
.contains(url
)) {
1522 m_selectedUrls
<< url
;
1526 void DolphinView::onDirectoryLoadingCompletedAfterJob()
1528 // the model should now contain all the items created by the job
1529 m_selectJobCreatedItems
= true; // to make sure we overwrite selection
1530 // update the view: scroll into View and selection
1532 m_selectJobCreatedItems
= false;
1533 m_selectedUrls
.clear();
1536 void DolphinView::slotJobResult(KJob
*job
)
1538 if (job
->error() && job
->error() != KIO::ERR_USER_CANCELED
) {
1539 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1541 if (!m_selectJobCreatedItems
) {
1542 m_selectedUrls
.clear();
1545 if (!m_selectedUrls
.isEmpty()) {
1546 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1548 updateSelectionState();
1549 if (!m_selectedUrls
.isEmpty()) {
1550 // not all urls were found, the model may not be up to date
1551 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::onDirectoryLoadingCompletedAfterJob
, Qt::SingleShotConnection
);
1553 m_selectJobCreatedItems
= false;
1554 m_selectedUrls
.clear();
1559 void DolphinView::slotSelectionChanged(const KItemSet
¤t
, const KItemSet
&previous
)
1561 m_selectNextItem
= false;
1562 const int currentCount
= current
.count();
1563 const int previousCount
= previous
.count();
1564 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) || (currentCount
> 0 && previousCount
== 0);
1566 // If nothing has been selected before and something got selected (or if something
1567 // was selected before and now nothing is selected) the selectionChangedSignal must
1568 // be emitted asynchronously as fast as possible to update the edit-actions.
1569 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1570 m_selectionChangedTimer
->start();
1573 void DolphinView::emitSelectionChangedSignal()
1575 m_selectionChangedTimer
->stop();
1576 Q_EMIT
selectionChanged(selectedItems());
1579 void DolphinView::slotStatJobResult(KJob
*job
)
1581 int folderCount
= 0;
1583 KIO::filesize_t totalFileSize
= 0;
1584 bool countFileSize
= true;
1586 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1587 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1588 // We have a precomputed value.
1589 totalFileSize
= static_cast<KIO::filesize_t
>(entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1590 countFileSize
= false;
1593 const int itemCount
= m_model
->count();
1594 for (int i
= 0; i
< itemCount
; ++i
) {
1595 const KFileItem item
= m_model
->fileItem(i
);
1600 if (countFileSize
) {
1601 totalFileSize
+= item
.size();
1605 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1608 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1610 ViewProperties
props(viewPropertiesUrl());
1611 props
.setSortFoldersFirst(foldersFirst
);
1613 m_model
->setSortDirectoriesFirst(foldersFirst
);
1615 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1618 void DolphinView::updateSortHiddenLast(bool hiddenLast
)
1620 ViewProperties
props(viewPropertiesUrl());
1621 props
.setSortHiddenLast(hiddenLast
);
1623 m_model
->setSortHiddenLast(hiddenLast
);
1625 Q_EMIT
sortHiddenLastChanged(hiddenLast
);
1628 QPair
<bool, QString
> DolphinView::pasteInfo() const
1630 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1631 QPair
<bool, QString
> info
;
1632 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1636 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1638 m_tabsForFiles
= tabsForFiles
;
1641 bool DolphinView::isTabsForFilesEnabled() const
1643 return m_tabsForFiles
;
1646 bool DolphinView::itemsExpandable() const
1648 return m_mode
== DetailsView
;
1651 bool DolphinView::isExpanded(const KFileItem
&item
) const
1653 Q_ASSERT(item
.isDir());
1654 Q_ASSERT(items().contains(item
));
1655 if (!itemsExpandable()) {
1658 return m_model
->isExpanded(m_model
->index(item
));
1661 void DolphinView::restoreState(QDataStream
&stream
)
1663 // Read the version number of the view state and check if the version is supported.
1664 quint32 version
= 0;
1667 // The version of the view state isn't supported, we can't restore it.
1671 // Restore the current item that had the keyboard focus
1672 stream
>> m_currentItemUrl
;
1674 // Restore the previously selected items
1675 stream
>> m_selectedUrls
;
1677 // Restore the view position
1678 stream
>> m_restoredContentsPosition
;
1680 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1683 m_model
->restoreExpandedDirectories(urls
);
1686 void DolphinView::saveState(QDataStream
&stream
)
1688 stream
<< quint32(1); // View state version
1690 // Save the current item that has the keyboard focus
1691 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1692 if (currentIndex
!= -1) {
1693 KFileItem item
= m_model
->fileItem(currentIndex
);
1694 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1695 QUrl currentItemUrl
= item
.url();
1696 stream
<< currentItemUrl
;
1701 // Save the selected urls
1702 stream
<< selectedItems().urlList();
1704 // Save view position
1705 const qreal x
= m_container
->horizontalScrollBar()->value();
1706 const qreal y
= m_container
->verticalScrollBar()->value();
1707 stream
<< QPoint(x
, y
);
1709 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1710 stream
<< m_model
->expandedDirectories();
1713 KFileItem
DolphinView::rootItem() const
1715 return m_model
->rootItem();
1718 void DolphinView::setViewPropertiesContext(const QString
&context
)
1720 m_viewPropertiesContext
= context
;
1723 QString
DolphinView::viewPropertiesContext() const
1725 return m_viewPropertiesContext
;
1728 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
&item
, const bool browseThroughArchives
)
1730 if (item
.isNull()) {
1734 QUrl url
= item
.targetUrl();
1740 if (item
.isMimeTypeKnown()) {
1741 const QString
&mimetype
= item
.mimetype();
1743 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1744 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1745 // zip:/<path>/ when clicking on a zip file, etc.
1746 // The .protocol file specifies the mimetype that the kioslave handles.
1747 // Note that we don't use mimetype inheritance since we don't want to
1748 // open OpenDocument files as zip folders...
1749 const QString
&protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1750 if (!protocol
.isEmpty()) {
1751 url
.setScheme(protocol
);
1756 if (mimetype
== QLatin1String("application/x-desktop")) {
1757 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1758 KDesktopFile
desktopFile(url
.toLocalFile());
1759 if (desktopFile
.hasLinkType()) {
1760 const QString linkUrl
= desktopFile
.readUrl();
1761 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1762 return QUrl::fromUserInput(linkUrl
);
1771 void DolphinView::resetZoomLevel()
1773 ViewModeSettings settings
{m_mode
};
1774 settings
.useDefaults(true);
1775 const int defaultIconSize
= settings
.iconSize();
1776 settings
.useDefaults(false);
1778 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize
, defaultIconSize
)));
1781 void DolphinView::observeCreatedItem(const QUrl
&url
)
1784 forceUrlsSelection(url
, {url
});
1788 void DolphinView::slotDirectoryRedirection(const QUrl
&oldUrl
, const QUrl
&newUrl
)
1790 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1791 Q_EMIT
redirection(oldUrl
, newUrl
);
1792 m_url
= newUrl
; // #186947
1796 void DolphinView::updateSelectionState()
1798 if (!m_selectedUrls
.isEmpty()) {
1799 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1801 const bool shouldScrollToCurrentItem
= m_clearSelectionBeforeSelectingNewItems
;
1802 // if there is a selection already, leave it that way
1803 // unless some drop/paste job are in the process of creating items
1804 if (!selectionManager
->hasSelection() || m_selectJobCreatedItems
) {
1805 if (m_clearSelectionBeforeSelectingNewItems
) {
1806 selectionManager
->clearSelection();
1807 m_clearSelectionBeforeSelectingNewItems
= false;
1810 KItemSet selectedItems
= selectionManager
->selectedItems();
1812 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1813 while (it
!= m_selectedUrls
.end()) {
1814 const int index
= m_model
->index(*it
);
1816 selectedItems
.insert(index
);
1817 it
= m_selectedUrls
.erase(it
);
1823 if (!selectedItems
.isEmpty()) {
1824 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1825 selectionManager
->setSelectedItems(selectedItems
);
1826 if (shouldScrollToCurrentItem
) {
1827 m_view
->scrollToItem(selectedItems
.first());
1834 void DolphinView::updateViewState()
1836 if (m_currentItemUrl
!= QUrl()) {
1837 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1839 // if there is a selection already, leave it that way
1840 if (!selectionManager
->hasSelection()) {
1841 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1842 if (currentIndex
!= -1) {
1843 selectionManager
->setCurrentItem(currentIndex
);
1845 // scroll to current item and reset the state
1846 if (m_scrollToCurrentItem
) {
1847 m_view
->scrollToItem(currentIndex
, KItemListView::ViewItemPosition::Middle
);
1848 m_scrollToCurrentItem
= false;
1850 m_currentItemUrl
= QUrl();
1852 selectionManager
->setCurrentItem(0);
1855 m_currentItemUrl
= QUrl();
1859 if (!m_restoredContentsPosition
.isNull()) {
1860 const int x
= m_restoredContentsPosition
.x();
1861 const int y
= m_restoredContentsPosition
.y();
1862 m_restoredContentsPosition
= QPoint();
1864 m_container
->horizontalScrollBar()->setValue(x
);
1865 m_container
->verticalScrollBar()->setValue(y
);
1868 updateSelectionState();
1871 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1873 if (GeneralSettings::showToolTips()) {
1875 m_toolTipManager
->hideToolTip(behavior
);
1879 } else if (m_mode
== DolphinView::IconsView
) {
1880 QToolTip::hideText();
1884 bool DolphinView::handleSpaceAsNormalKey() const
1886 return !m_container
->hasFocus() || m_container
->controller()->isSearchAsYouTypeActive();
1889 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1891 const KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1893 // verify that only one item is selected
1894 if (selectionManager
->selectedItems().count() == 1) {
1895 const int index
= selectionManager
->currentItem();
1896 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1898 // check if the selected item was the same item that started the twoClicksRenaming
1899 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1900 renameSelectedItems();
1905 void DolphinView::slotTrashFileFinished(KJob
*job
)
1907 if (job
->error() == 0) {
1908 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1909 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1910 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1911 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1915 void DolphinView::slotDeleteFileFinished(KJob
*job
)
1917 if (job
->error() == 0) {
1918 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1919 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1920 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1921 Q_EMIT
errorMessage(job
->errorString(), job
->error());
1925 void DolphinView::selectNextItem()
1927 if (m_active
&& m_selectNextItem
) {
1928 KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
1929 if (selectedItems().isEmpty()) {
1930 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1933 const auto lastSelectedIndex
= m_model
->index(selectedItems().constLast());
1934 if (lastSelectedIndex
< 0) {
1935 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1938 auto nextItem
= lastSelectedIndex
+ 1;
1939 if (nextItem
>= itemsCount()) {
1940 nextItem
= lastSelectedIndex
- selectedItemsCount();
1942 if (nextItem
>= 0) {
1943 selectionManager
->setSelected(nextItem
, 1);
1944 selectionManager
->beginAnchoredSelection(nextItem
);
1946 m_selectNextItem
= false;
1950 void DolphinView::slotRenamingResult(KJob
*job
)
1952 // Change model data after renaming has succeeded. On failure we do nothing.
1953 // If there is already an item with the newUrl, the copyjob will open a dialog for it, and
1954 // KFileItemModel will update the data when the dir lister signals that the file name has changed.
1955 if (!job
->error()) {
1956 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1958 const QUrl newUrl
= copyJob
->destUrl();
1959 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1960 const int index
= m_model
->index(newUrl
);
1961 if (m_model
->index(oldUrl
) == index
) {
1962 QHash
<QByteArray
, QVariant
> data
;
1963 data
.insert("text", newUrl
.fileName());
1964 m_model
->setData(index
, data
);
1969 void DolphinView::slotDirectoryLoadingStarted()
1971 m_loadingState
= LoadingState::Loading
;
1972 updatePlaceholderLabel();
1974 // Disable the writestate temporary until it can be determined in a fast way
1975 // in DolphinView::slotDirectoryLoadingCompleted()
1976 if (m_isFolderWritable
) {
1977 m_isFolderWritable
= false;
1978 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1981 Q_EMIT
directoryLoadingStarted();
1984 void DolphinView::slotDirectoryLoadingCompleted()
1986 m_loadingState
= LoadingState::Completed
;
1988 // Update the view-state. This has to be done asynchronously
1989 // because the view might not be in its final state yet.
1990 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1992 // Update the placeholder label in case we found that the folder was empty
1995 Q_EMIT
directoryLoadingCompleted();
1998 updatePlaceholderLabel();
1999 updateWritableState();
2002 void DolphinView::slotDirectoryLoadingCanceled()
2004 m_loadingState
= LoadingState::Canceled
;
2006 updatePlaceholderLabel();
2008 Q_EMIT
directoryLoadingCanceled();
2011 void DolphinView::slotItemsChanged()
2013 m_assureVisibleCurrentIndex
= false;
2016 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
2019 Q_ASSERT(m_model
->sortOrder() == current
);
2021 ViewProperties
props(viewPropertiesUrl());
2022 props
.setSortOrder(current
);
2024 Q_EMIT
sortOrderChanged(current
);
2027 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
¤t
, const QByteArray
&previous
)
2030 Q_ASSERT(m_model
->sortRole() == current
);
2032 ViewProperties
props(viewPropertiesUrl());
2033 props
.setSortRole(current
);
2035 Q_EMIT
sortRoleChanged(current
);
2038 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
> ¤t
, const QList
<QByteArray
> &previous
)
2041 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
2043 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
2045 m_visibleRoles
= current
;
2047 ViewProperties
props(viewPropertiesUrl());
2048 props
.setVisibleRoles(m_visibleRoles
);
2050 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
2053 void DolphinView::slotRoleEditingCanceled()
2055 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
2058 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
&role
, const QVariant
&value
)
2060 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
, this, &DolphinView::slotRoleEditingFinished
);
2062 const KFileItemList items
= selectedItems();
2063 if (items
.count() != 1) {
2067 if (role
== "text") {
2068 const KFileItem oldItem
= items
.first();
2069 const EditResult retVal
= value
.value
<EditResult
>();
2070 const QString newName
= retVal
.newName
;
2071 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
2072 const QUrl oldUrl
= oldItem
.url();
2074 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
2075 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
2078 // Confirm hiding file/directory by renaming inline
2079 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
2080 KGuiItem
yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden"));
2083 KMessageBox::questionTwoActions(this,
2084 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
2085 "Do you still want to rename it?")
2086 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
2087 "Do you still want to rename it?"),
2088 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
2090 KStandardGuiItem::cancel(),
2091 QStringLiteral("ConfirmHide"));
2093 if (code
== KMessageBox::SecondaryAction
) {
2099 KIO::Job
*job
= KIO::moveAs(oldUrl
, newUrl
);
2100 KJobWidgets::setWindow(job
, this);
2101 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
2102 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
2104 if (m_model
->index(newUrl
) < 0) {
2105 forceUrlsSelection(newUrl
, {newUrl
});
2106 updateSelectionState();
2108 // Only connect the result signal if there is no item with the new name
2109 // in the model yet, see bug 328262.
2110 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
2113 if (retVal
.direction
!= EditDone
) {
2114 const short indexShift
= retVal
.direction
== EditNext
? 1 : -1;
2115 m_container
->controller()->selectionManager()->setSelected(index
, 1, KItemListSelectionManager::Deselect
);
2116 m_container
->controller()->selectionManager()->setSelected(index
+ indexShift
, 1, KItemListSelectionManager::Select
);
2117 renameSelectedItems();
2122 void DolphinView::loadDirectory(const QUrl
&url
, bool reload
)
2124 if (!url
.isValid()) {
2125 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
2126 if (location
.isEmpty()) {
2127 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."), KIO::ERR_UNKNOWN
);
2129 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
), KIO::ERR_UNKNOWN
);
2135 m_model
->refreshDirectory(url
);
2137 m_model
->loadDirectory(url
);
2141 void DolphinView::applyViewProperties()
2143 const ViewProperties
props(viewPropertiesUrl());
2144 applyViewProperties(props
);
2147 void DolphinView::applyViewProperties(const ViewProperties
&props
)
2149 m_view
->beginTransaction();
2151 const Mode mode
= props
.viewMode();
2152 if (m_mode
!= mode
) {
2153 const Mode previousMode
= m_mode
;
2156 // Changing the mode might result in changing
2157 // the zoom level. Remember the old zoom level so
2158 // that zoomLevelChanged() can get emitted.
2159 const int oldZoomLevel
= m_view
->zoomLevel();
2162 Q_EMIT
modeChanged(m_mode
, previousMode
);
2164 if (m_view
->zoomLevel() != oldZoomLevel
) {
2165 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
2169 const bool hiddenFilesShown
= props
.hiddenFilesShown();
2170 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
2171 m_model
->setShowHiddenFiles(hiddenFilesShown
);
2172 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
2175 const bool groupedSorting
= props
.groupedSorting();
2176 if (groupedSorting
!= m_model
->groupedSorting()) {
2177 m_model
->setGroupedSorting(groupedSorting
);
2178 Q_EMIT
groupedSortingChanged(groupedSorting
);
2181 const QByteArray sortRole
= props
.sortRole();
2182 if (sortRole
!= m_model
->sortRole()) {
2183 m_model
->setSortRole(sortRole
);
2184 Q_EMIT
sortRoleChanged(sortRole
);
2187 const Qt::SortOrder sortOrder
= props
.sortOrder();
2188 if (sortOrder
!= m_model
->sortOrder()) {
2189 m_model
->setSortOrder(sortOrder
);
2190 Q_EMIT
sortOrderChanged(sortOrder
);
2193 const QByteArray groupRole
= props
.groupRole();
2194 if (groupRole
!= m_model
->groupRole()) {
2195 m_model
->setGroupRole(groupRole
);
2196 Q_EMIT
groupRoleChanged(groupRole
);
2199 const Qt::SortOrder groupOrder
= props
.groupOrder();
2200 if (groupOrder
!= m_model
->groupOrder()) {
2201 m_model
->setGroupOrder(groupOrder
);
2202 Q_EMIT
groupOrderChanged(groupOrder
);
2205 const bool sortFoldersFirst
= props
.sortFoldersFirst();
2206 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
2207 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
2208 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
2211 const bool sortHiddenLast
= props
.sortHiddenLast();
2212 if (sortHiddenLast
!= m_model
->sortHiddenLast()) {
2213 m_model
->setSortHiddenLast(sortHiddenLast
);
2214 Q_EMIT
sortHiddenLastChanged(sortHiddenLast
);
2217 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
2218 if (visibleRoles
!= m_visibleRoles
) {
2219 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
2220 m_visibleRoles
= visibleRoles
;
2221 m_view
->setVisibleRoles(visibleRoles
);
2222 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
2225 const bool previewsShown
= props
.previewsShown();
2226 if (previewsShown
!= m_view
->previewsShown()) {
2227 const int oldZoomLevel
= zoomLevel();
2229 m_view
->setPreviewsShown(previewsShown
);
2230 Q_EMIT
previewsShownChanged(previewsShown
);
2232 // Changing the preview-state might result in a changed zoom-level
2233 if (oldZoomLevel
!= zoomLevel()) {
2234 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
2238 KItemListView
*itemListView
= m_container
->controller()->view();
2239 if (itemListView
->isHeaderVisible()) {
2240 KItemListHeader
*header
= itemListView
->header();
2241 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
2242 const int rolesCount
= m_visibleRoles
.count();
2243 if (headerColumnWidths
.count() == rolesCount
) {
2244 header
->setAutomaticColumnResizing(false);
2246 QHash
<QByteArray
, qreal
> columnWidths
;
2247 for (int i
= 0; i
< rolesCount
; ++i
) {
2248 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
2250 header
->setColumnWidths(columnWidths
);
2252 header
->setAutomaticColumnResizing(true);
2254 header
->setSidePadding(DetailsModeSettings::leftPadding(), DetailsModeSettings::rightPadding());
2257 m_view
->endTransaction();
2260 void DolphinView::applyModeToView()
2264 m_view
->setItemLayout(KFileItemListView::IconsLayout
);
2267 m_view
->setItemLayout(KFileItemListView::CompactLayout
);
2270 m_view
->setItemLayout(KFileItemListView::DetailsLayout
);
2278 void DolphinView::applyDynamicView()
2280 ViewProperties
props(viewPropertiesUrl());
2282 * - dynamic view is not enabled
2283 * - the current view mode is already Icon View
2284 * - dynamic view has previously changed the view mode
2286 if (!GeneralSettings::dynamicView() || m_mode
== IconsView
|| props
.dynamicViewPassed()) {
2290 uint imageAndVideoCount
= 0;
2291 uint checkedItems
= 0;
2292 const uint totalItems
= itemsCount();
2293 const KFileItemList itemList
= items();
2294 bool applyDynamicView
= false;
2296 for (const auto &file
: itemList
) {
2298 const QString type
= file
.mimetype().slice(0, 5);
2300 if (type
== "image" || type
== "video") {
2301 ++imageAndVideoCount
;
2302 // if 2/3 or more of the items are images/videos, dynamic view should be applied
2303 applyDynamicView
= imageAndVideoCount
>= (totalItems
* 2 / 3);
2304 if (applyDynamicView
) {
2307 } else if (checkedItems
- imageAndVideoCount
> totalItems
/ 3) {
2308 // if more than a third of the checked files are not media files, return
2313 if (!applyDynamicView
) {
2317 props
.setAutoSaveEnabled(!GeneralSettings::globalViewProps());
2318 props
.setDynamicViewPassed(true);
2319 props
.setViewMode(IconsView
);
2320 applyViewProperties(props
);
2323 void DolphinView::pasteToUrl(const QUrl
&url
)
2325 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
2326 KJobWidgets::setWindow(job
, this);
2327 m_clearSelectionBeforeSelectingNewItems
= true;
2328 m_markFirstNewlySelectedItemAsCurrent
= true;
2329 m_selectJobCreatedItems
= true;
2330 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
2331 connect(job
, &KIO::PasteJob::copyJobStarted
, this, [this](const KIO::CopyJob
*copyJob
) {
2332 connect(copyJob
, &KIO::CopyJob::copying
, this, &DolphinView::slotItemCreatedFromJob
);
2333 connect(copyJob
, &KIO::CopyJob::moving
, this, &DolphinView::slotItemCreatedFromJob
);
2334 connect(copyJob
, &KIO::CopyJob::warning
, this, [this](KJob
*job
, const QString
& /*warning*/) {
2335 Q_EMIT
errorMessage(job
->errorString(), job
->error());
2337 connect(copyJob
, &KIO::CopyJob::linking
, this, [this](KIO::Job
*job
, const QString
&src
, const QUrl
&dest
) {
2340 slotItemCreated(dest
);
2343 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
2346 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
2350 const KFileItemList items
= selectedItems();
2351 urls
.reserve(items
.count());
2352 for (const KFileItem
&item
: items
) {
2353 urls
.append(item
.url());
2356 if (itemsExpandable()) {
2357 // TODO: Check if we still need KDirModel for this in KDE 5.0
2358 urls
= KDirModel::simplifiedUrlList(urls
);
2364 QMimeData
*DolphinView::selectionMimeData() const
2366 const KItemListSelectionManager
*selectionManager
= m_container
->controller()->selectionManager();
2367 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
2369 return m_model
->createMimeData(selectedIndexes
);
2372 void DolphinView::updateWritableState()
2374 const bool wasFolderWritable
= m_isFolderWritable
;
2375 m_isFolderWritable
= false;
2377 KFileItem item
= m_model
->rootItem();
2378 if (item
.isNull()) {
2379 // Try to find out if the URL is writable even if the "root item" is
2380 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2381 item
= KFileItem(url());
2382 item
.setDelayedMimeTypes(true);
2385 KFileItemListProperties
capabilities(KFileItemList() << item
);
2386 m_isFolderWritable
= capabilities
.supportsWriting();
2388 if (m_isFolderWritable
!= wasFolderWritable
) {
2389 Q_EMIT
writeStateChanged(m_isFolderWritable
);
2393 bool DolphinView::isFolderWritable() const
2395 return m_isFolderWritable
;
2398 int DolphinView::horizontalScrollBarHeight() const
2400 if (m_container
&& m_container
->horizontalScrollBar() && m_container
->horizontalScrollBar()->isVisible()) {
2401 return m_container
->horizontalScrollBar()->height();
2406 void DolphinView::setStatusBarOffset(int offset
)
2408 KItemListView
*view
= m_container
->controller()->view();
2410 view
->setStatusBarOffset(offset
);
2414 QUrl
DolphinView::viewPropertiesUrl() const
2416 if (m_viewPropertiesContext
.isEmpty()) {
2421 url
.setScheme(m_url
.scheme());
2422 url
.setPath(m_viewPropertiesContext
);
2426 void DolphinView::forceUrlsSelection(const QUrl
¤t
, const QList
<QUrl
> &selected
)
2429 m_clearSelectionBeforeSelectingNewItems
= true;
2430 markUrlAsCurrent(current
);
2431 markUrlsAsSelected(selected
);
2434 void DolphinView::copyPathToClipboard()
2436 const KFileItemList list
= selectedItems();
2437 if (list
.isEmpty()) {
2440 const KFileItem
&item
= list
.at(0);
2441 QString path
= item
.localPath();
2442 if (path
.isEmpty()) {
2443 path
= item
.url().toDisplayString();
2445 QClipboard
*clipboard
= QApplication::clipboard();
2446 if (clipboard
== nullptr) {
2449 clipboard
->setText(QDir::toNativeSeparators(path
));
2452 void DolphinView::slotIncreaseZoom()
2454 setZoomLevel(zoomLevel() + 1);
2457 void DolphinView::slotDecreaseZoom()
2459 setZoomLevel(zoomLevel() - 1);
2462 void DolphinView::slotSwipeUp()
2464 Q_EMIT
goUpRequested();
2467 void DolphinView::showLoadingPlaceholder()
2469 m_placeholderLabel
->setText(i18n("Loading…"));
2470 m_placeholderLabel
->setVisible(true);
2471 #ifndef QT_NO_ACCESSIBILITY
2472 if (QAccessible::isActive()) {
2473 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
))->announceNewlyLoadedLocation(m_placeholderLabel
->text());
2478 void DolphinView::updatePlaceholderLabel()
2480 m_showLoadingPlaceholderTimer
->stop();
2481 if (itemsCount() > 0) {
2482 #ifndef QT_NO_ACCESSIBILITY
2483 if (QAccessible::isActive()) {
2484 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
))->announceNewlyLoadedLocation(QString());
2487 m_placeholderLabel
->setVisible(false);
2491 if (m_loadingState
== LoadingState::Loading
) {
2492 m_placeholderLabel
->setVisible(false);
2493 m_showLoadingPlaceholderTimer
->start();
2497 if (m_loadingState
== LoadingState::Canceled
) {
2498 m_placeholderLabel
->setText(i18n("Loading canceled"));
2499 } else if (!nameFilter().isEmpty()) {
2500 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2501 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2502 m_placeholderLabel
->setText(i18n("No items matching the search"));
2503 } else if (m_url
.scheme() == QLatin1String("trash") && m_url
.path() == QLatin1String("/")) {
2504 m_placeholderLabel
->setText(i18n("Trash is empty"));
2505 } else if (m_url
.scheme() == QLatin1String("tags")) {
2506 if (m_url
.path() == QLatin1Char('/')) {
2507 m_placeholderLabel
->setText(i18n("No tags"));
2509 const QString tagName
= m_url
.path().mid(1); // Remove leading /
2510 m_placeholderLabel
->setText(i18n("No files tagged with \"%1\"", tagName
));
2513 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2514 m_placeholderLabel
->setText(i18n("No recently used items"));
2515 } else if (m_url
.scheme() == QLatin1String("smb")) {
2516 m_placeholderLabel
->setText(i18n("No shared folders found"));
2517 } else if (m_url
.scheme() == QLatin1String("network")) {
2518 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2519 } else if (m_url
.scheme() == QLatin1String("mtp") && m_url
.path() == QLatin1String("/")) {
2520 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2521 } else if (m_url
.scheme() == QLatin1String("afc") && m_url
.path() == QLatin1String("/")) {
2522 m_placeholderLabel
->setText(i18n("No Apple devices found"));
2523 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2524 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2526 m_placeholderLabel
->setText(i18n("Folder is empty"));
2529 m_placeholderLabel
->setVisible(true);
2530 #ifndef QT_NO_ACCESSIBILITY
2531 if (QAccessible::isActive()) {
2532 static_cast<KItemListViewAccessible
*>(QAccessible::queryAccessibleInterface(m_view
))->announceNewlyLoadedLocation(m_placeholderLabel
->text());
2537 bool DolphinView::tryShowNameToolTip(QHelpEvent
*event
)
2539 if (!GeneralSettings::showToolTips() && m_mode
== DolphinView::IconsView
) {
2540 const std::optional
<int> index
= m_view
->itemAt(event
->pos());
2542 if (!index
.has_value()) {
2546 // Check whether the filename has been elided
2547 const bool isElided
= m_view
->isElided(index
.value());
2550 const KFileItem item
= m_model
->fileItem(index
.value());
2551 const QString text
= item
.text();
2552 const QPoint pos
= mapToGlobal(event
->pos());
2553 QToolTip::showText(pos
, text
, this);
2560 #include "moc_dolphinview.cpp"