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_generalsettings.h"
11 #include "dolphinitemlistview.h"
12 #include "dolphinnewfilemenuobserver.h"
13 #include "draganddrophelper.h"
14 #include "kitemviews/kfileitemlistview.h"
15 #include "kitemviews/kfileitemmodel.h"
16 #include "kitemviews/kitemlistcontainer.h"
17 #include "kitemviews/kitemlistcontroller.h"
18 #include "kitemviews/kitemlistheader.h"
19 #include "kitemviews/kitemlistselectionmanager.h"
20 #include "kitemviews/private/kitemlistroleeditor.h"
21 #include "settings/viewmodes/viewmodesettings.h"
22 #include "versioncontrol/versioncontrolobserver.h"
23 #include "viewproperties.h"
24 #include "views/tooltips/tooltipmanager.h"
25 #include "zoomlevelinfo.h"
28 #include <Baloo/IndexerConfig>
30 #include <KColorScheme>
31 #include <KDesktopFile>
33 #include <KFileItemListProperties>
35 #include <KIO/CopyJob>
36 #include <KIO/DeleteJob>
37 #include <KIO/DropJob>
38 #include <KIO/JobUiDelegate>
40 #include <KIO/PasteJob>
41 #include <KIO/PreviewJob>
42 #include <KIO/RenameFileDialog>
43 #include <KJobWidgets>
44 #include <KLocalizedString>
45 #include <KMessageBox>
46 #include <KProtocolManager>
48 #include <QAbstractItemView>
49 #include <QActionGroup>
50 #include <QApplication>
53 #include <QGraphicsOpacityEffect>
54 #include <QGraphicsSceneDragDropEvent>
57 #include <QMimeDatabase>
58 #include <QPixmapCache>
62 #include <QVBoxLayout>
64 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
67 m_tabsForFiles(false),
68 m_assureVisibleCurrentIndex(false),
69 m_isFolderWritable(true),
73 m_viewPropertiesContext(),
74 m_mode(DolphinView::IconsView
),
80 m_toolTipManager(nullptr),
81 m_selectionChangedTimer(nullptr),
83 m_scrollToCurrentItem(false),
84 m_restoredContentsPosition(),
86 m_clearSelectionBeforeSelectingNewItems(false),
87 m_markFirstNewlySelectedItemAsCurrent(false),
88 m_versionControlObserver(nullptr),
89 m_twoClicksRenamingTimer(nullptr),
90 m_placeholderLabel(nullptr),
91 m_showLoadingPlaceholderTimer(nullptr)
93 m_topLayout
= new QVBoxLayout(this);
94 m_topLayout
->setSpacing(0);
95 m_topLayout
->setContentsMargins(0, 0, 0, 0);
97 // When a new item has been created by the "Create New..." menu, the item should
98 // get selected and it must be assured that the item will get visible. As the
99 // creation is done asynchronously, several signals must be checked:
100 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
101 this, &DolphinView::observeCreatedItem
);
103 m_selectionChangedTimer
= new QTimer(this);
104 m_selectionChangedTimer
->setSingleShot(true);
105 m_selectionChangedTimer
->setInterval(300);
106 connect(m_selectionChangedTimer
, &QTimer::timeout
,
107 this, &DolphinView::emitSelectionChangedSignal
);
109 m_model
= new KFileItemModel(this);
110 m_view
= new DolphinItemListView();
111 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
112 m_view
->setVisibleRoles({"text"});
115 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
116 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
117 controller
->setAutoActivationDelay(delay
);
119 // The EnlargeSmallPreviews setting can only be changed after the model
120 // has been set in the view by KItemListController.
121 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
123 m_container
= new KItemListContainer(controller
, this);
124 m_container
->installEventFilter(this);
125 setFocusProxy(m_container
);
126 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
127 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
129 m_showLoadingPlaceholderTimer
= new QTimer(this);
130 m_showLoadingPlaceholderTimer
->setInterval(500);
131 m_showLoadingPlaceholderTimer
->setSingleShot(true);
132 connect(m_showLoadingPlaceholderTimer
, &QTimer::timeout
, this, &DolphinView::showLoadingPlaceholder
);
134 // Show some placeholder text for empty folders
135 // This is made using a heavily-modified QLabel rather than a KTitleWidget
136 // because KTitleWidget can't be told to turn off mouse-selectable text
137 m_placeholderLabel
= new QLabel(this);
138 QFont placeholderLabelFont
;
139 // To match the size of a level 2 Heading/KTitleWidget
140 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
141 m_placeholderLabel
->setFont(placeholderLabelFont
);
142 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
143 m_placeholderLabel
->setWordWrap(true);
144 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
145 // Match opacity of QML placeholder label component
146 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
147 effect
->setOpacity(0.5);
148 m_placeholderLabel
->setGraphicsEffect(effect
);
149 // Set initial text and visibility
150 updatePlaceholderLabel();
152 auto *centeringLayout
= new QVBoxLayout(m_container
);
153 centeringLayout
->addWidget(m_placeholderLabel
);
154 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
156 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
157 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
158 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
159 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
160 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
161 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
162 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
163 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
164 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
165 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
166 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
167 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
168 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
169 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
170 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
171 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
172 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
174 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
175 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
176 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
177 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
178 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
179 connect(m_model
, &KFileItemModel::itemsChanged
,
180 this, &DolphinView::slotItemsChanged
);
181 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
182 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
183 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
184 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
185 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
186 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
187 connect(m_model
, &KFileItemModel::fileItemsChanged
, this, &DolphinView::fileItemsChanged
);
189 connect(this, &DolphinView::itemCountChanged
,
190 this, &DolphinView::updatePlaceholderLabel
);
192 m_view
->installEventFilter(this);
193 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
194 this, &DolphinView::slotSortOrderChangedByHeader
);
195 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
196 this, &DolphinView::slotSortRoleChangedByHeader
);
197 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
198 this, &DolphinView::slotVisibleRolesChangedByHeader
);
199 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
200 this, &DolphinView::slotRoleEditingCanceled
);
201 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
202 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
204 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
205 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
206 this, &DolphinView::slotSelectionChanged
);
209 m_toolTipManager
= new ToolTipManager(this);
210 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
213 m_versionControlObserver
= new VersionControlObserver(this);
214 m_versionControlObserver
->setView(this);
215 m_versionControlObserver
->setModel(m_model
);
216 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
217 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
218 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
220 m_twoClicksRenamingTimer
= new QTimer(this);
221 m_twoClicksRenamingTimer
->setSingleShot(true);
222 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
224 applyViewProperties();
225 m_topLayout
->addWidget(m_container
);
230 DolphinView::~DolphinView()
234 QUrl
DolphinView::url() const
239 void DolphinView::setActive(bool active
)
241 if (active
== m_active
) {
250 m_container
->setFocus();
252 Q_EMIT
writeStateChanged(m_isFolderWritable
);
256 bool DolphinView::isActive() const
261 void DolphinView::setMode(Mode mode
)
263 if (mode
!= m_mode
) {
264 ViewProperties
props(viewPropertiesUrl());
265 props
.setViewMode(mode
);
267 // We pass the new ViewProperties to applyViewProperties, rather than
268 // storing them on disk and letting applyViewProperties() read them
269 // from there, to prevent that changing the view mode fails if the
270 // .directory file is not writable (see bug 318534).
271 applyViewProperties(props
);
275 DolphinView::Mode
DolphinView::mode() const
280 void DolphinView::setPreviewsShown(bool show
)
282 if (previewsShown() == show
) {
286 ViewProperties
props(viewPropertiesUrl());
287 props
.setPreviewsShown(show
);
289 const int oldZoomLevel
= m_view
->zoomLevel();
290 m_view
->setPreviewsShown(show
);
291 Q_EMIT
previewsShownChanged(show
);
293 const int newZoomLevel
= m_view
->zoomLevel();
294 if (newZoomLevel
!= oldZoomLevel
) {
295 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
299 bool DolphinView::previewsShown() const
301 return m_view
->previewsShown();
304 void DolphinView::setHiddenFilesShown(bool show
)
306 if (m_model
->showHiddenFiles() == show
) {
310 const KFileItemList itemList
= selectedItems();
311 m_selectedUrls
.clear();
312 m_selectedUrls
= itemList
.urlList();
314 ViewProperties
props(viewPropertiesUrl());
315 props
.setHiddenFilesShown(show
);
317 m_model
->setShowHiddenFiles(show
);
318 Q_EMIT
hiddenFilesShownChanged(show
);
321 bool DolphinView::hiddenFilesShown() const
323 return m_model
->showHiddenFiles();
326 void DolphinView::setGroupedSorting(bool grouped
)
328 if (grouped
== groupedSorting()) {
332 ViewProperties
props(viewPropertiesUrl());
333 props
.setGroupedSorting(grouped
);
336 m_container
->controller()->model()->setGroupedSorting(grouped
);
338 Q_EMIT
groupedSortingChanged(grouped
);
341 bool DolphinView::groupedSorting() const
343 return m_model
->groupedSorting();
346 KFileItemList
DolphinView::items() const
349 const int itemCount
= m_model
->count();
350 list
.reserve(itemCount
);
352 for (int i
= 0; i
< itemCount
; ++i
) {
353 list
.append(m_model
->fileItem(i
));
359 int DolphinView::itemsCount() const
361 return m_model
->count();
364 KFileItemList
DolphinView::selectedItems() const
366 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
368 KFileItemList selectedItems
;
369 const auto items
= selectionManager
->selectedItems();
370 selectedItems
.reserve(items
.count());
371 for (int index
: items
) {
372 selectedItems
.append(m_model
->fileItem(index
));
374 return selectedItems
;
377 int DolphinView::selectedItemsCount() const
379 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
380 return selectionManager
->selectedItems().count();
383 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
385 m_selectedUrls
= urls
;
388 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
390 m_currentItemUrl
= url
;
391 m_scrollToCurrentItem
= true;
394 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
396 const KItemListSelectionManager::SelectionMode mode
= enabled
397 ? KItemListSelectionManager::Select
398 : KItemListSelectionManager::Deselect
;
399 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
401 for (int index
= 0; index
< m_model
->count(); index
++) {
402 const KFileItem item
= m_model
->fileItem(index
);
403 if (regexp
.match(item
.text()).hasMatch()) {
404 // An alternative approach would be to store the matching items in a KItemSet and
405 // select them in one go after the loop, but we'd need a new function
406 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
408 selectionManager
->setSelected(index
, 1, mode
);
413 void DolphinView::setZoomLevel(int level
)
415 const int oldZoomLevel
= zoomLevel();
416 m_view
->setZoomLevel(level
);
417 if (zoomLevel() != oldZoomLevel
) {
419 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
423 int DolphinView::zoomLevel() const
425 return m_view
->zoomLevel();
428 void DolphinView::setSortRole(const QByteArray
& role
)
430 if (role
!= sortRole()) {
431 updateSortRole(role
);
435 QByteArray
DolphinView::sortRole() const
437 const KItemModelBase
* model
= m_container
->controller()->model();
438 return model
->sortRole();
441 void DolphinView::setSortOrder(Qt::SortOrder order
)
443 if (sortOrder() != order
) {
444 updateSortOrder(order
);
448 Qt::SortOrder
DolphinView::sortOrder() const
450 return m_model
->sortOrder();
453 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
455 if (sortFoldersFirst() != foldersFirst
) {
456 updateSortFoldersFirst(foldersFirst
);
460 bool DolphinView::sortFoldersFirst() const
462 return m_model
->sortDirectoriesFirst();
465 void DolphinView::setSortHiddenLast(bool hiddenLast
)
467 if (sortHiddenLast() != hiddenLast
) {
468 updateSortHiddenLast(hiddenLast
);
472 bool DolphinView::sortHiddenLast() const
474 return m_model
->sortHiddenLast();
477 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
479 const QList
<QByteArray
> previousRoles
= roles
;
481 ViewProperties
props(viewPropertiesUrl());
482 props
.setVisibleRoles(roles
);
484 m_visibleRoles
= roles
;
485 m_view
->setVisibleRoles(roles
);
487 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
490 QList
<QByteArray
> DolphinView::visibleRoles() const
492 return m_visibleRoles
;
495 void DolphinView::reload()
497 QByteArray viewState
;
498 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
499 saveState(saveStream
);
502 loadDirectory(url(), true);
504 QDataStream
restoreStream(viewState
);
505 restoreState(restoreStream
);
508 void DolphinView::readSettings()
510 const int oldZoomLevel
= m_view
->zoomLevel();
512 GeneralSettings::self()->load();
513 m_view
->readSettings();
514 applyViewProperties();
516 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
517 m_container
->controller()->setAutoActivationDelay(delay
);
519 const int newZoomLevel
= m_view
->zoomLevel();
520 if (newZoomLevel
!= oldZoomLevel
) {
521 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
525 void DolphinView::writeSettings()
527 GeneralSettings::self()->save();
528 m_view
->writeSettings();
531 void DolphinView::setNameFilter(const QString
& nameFilter
)
533 m_model
->setNameFilter(nameFilter
);
536 QString
DolphinView::nameFilter() const
538 return m_model
->nameFilter();
541 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
543 return m_model
->setMimeTypeFilters(filters
);
546 QStringList
DolphinView::mimeTypeFilters() const
548 return m_model
->mimeTypeFilters();
551 void DolphinView::requestStatusBarText()
553 if (m_statJobForStatusBarText
) {
554 // Kill the pending request.
555 m_statJobForStatusBarText
->kill();
558 if (m_container
->controller()->selectionManager()->hasSelection()) {
561 KIO::filesize_t totalFileSize
= 0;
563 // Give a summary of the status of the selected files
564 const KFileItemList list
= selectedItems();
565 for (const KFileItem
& item
: list
) {
570 totalFileSize
+= item
.size();
574 if (folderCount
+ fileCount
== 1) {
575 // If only one item is selected, show info about it
576 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
578 // At least 2 items are selected
579 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
581 } else { // has no selection
582 if (!m_model
->rootItem().url().isValid()) {
586 m_statJobForStatusBarText
= KIO::statDetails(m_model
->rootItem().url(),
587 KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
588 connect(m_statJobForStatusBarText
, &KJob::result
,
589 this, &DolphinView::slotStatJobResult
);
590 m_statJobForStatusBarText
->start();
594 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
,
595 KIO::filesize_t totalFileSize
, const Selection selection
)
601 if (selection
== HasSelection
) {
602 // At least 2 items are selected because the case of 1 selected item is handled in
603 // DolphinView::requestStatusBarText().
604 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
605 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
607 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
608 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
611 if (fileCount
> 0 && folderCount
> 0) {
612 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
613 foldersText
, filesText
,
614 KFormat().formatByteSize(totalFileSize
));
615 } else if (fileCount
> 0) {
616 summary
= i18nc("@info:status files (size)", "%1 (%2)",
618 KFormat().formatByteSize(totalFileSize
));
619 } else if (folderCount
> 0) {
620 summary
= foldersText
;
622 summary
= i18nc("@info:status", "0 Folders, 0 Files");
624 Q_EMIT
statusBarTextChanged(summary
);
627 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
629 QList
<QAction
*> actions
;
631 if (items
.isEmpty()) {
632 const KFileItem item
= m_model
->rootItem();
633 if (!item
.isNull()) {
634 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
637 actions
= m_versionControlObserver
->actions(items
);
643 void DolphinView::setUrl(const QUrl
& url
)
655 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
656 this, &DolphinView::slotRoleEditingFinished
);
658 // It is important to clear the items from the model before
659 // applying the view properties, otherwise expensive operations
660 // might be done on the existing items although they get cleared
661 // anyhow afterwards by loadDirectory().
663 applyViewProperties();
666 Q_EMIT
urlChanged(url
);
669 void DolphinView::selectAll()
671 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
672 selectionManager
->setSelected(0, m_model
->count());
675 void DolphinView::invertSelection()
677 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
678 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
681 void DolphinView::clearSelection()
683 m_selectedUrls
.clear();
684 m_container
->controller()->selectionManager()->clearSelection();
687 void DolphinView::renameSelectedItems()
689 const KFileItemList items
= selectedItems();
690 if (items
.isEmpty()) {
694 if (items
.count() == 1 && GeneralSettings::renameInline()) {
695 const int index
= m_model
->index(items
.first());
697 QMetaObject::Connection
* const connection
= new QMetaObject::Connection
;
698 *connection
= connect(m_view
, &KItemListView::scrollingStopped
, this, [=](){
699 QObject::disconnect(*connection
);
702 m_view
->editRole(index
, "text");
706 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
707 this, &DolphinView::slotRoleEditingFinished
);
709 m_view
->scrollToItem(index
);
712 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
713 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
714 this, &DolphinView::slotRenameDialogRenamingFinished
);
719 // Assure that the current index remains visible when KFileItemModel
720 // will notify the view about changed items (which might result in
721 // a changed sorting).
722 m_assureVisibleCurrentIndex
= true;
725 void DolphinView::trashSelectedItems()
727 const QList
<QUrl
> list
= simplifiedSelectedUrls();
728 KIO::JobUiDelegate uiDelegate
;
729 uiDelegate
.setWindow(window());
730 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
731 KIO::Job
* job
= KIO::trash(list
);
732 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
733 KJobWidgets::setWindow(job
, this);
734 connect(job
, &KIO::Job::result
,
735 this, &DolphinView::slotTrashFileFinished
);
739 void DolphinView::deleteSelectedItems()
741 const QList
<QUrl
> list
= simplifiedSelectedUrls();
743 KIO::JobUiDelegate uiDelegate
;
744 uiDelegate
.setWindow(window());
745 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
746 KIO::Job
* job
= KIO::del(list
);
747 KJobWidgets::setWindow(job
, this);
748 connect(job
, &KIO::Job::result
,
749 this, &DolphinView::slotDeleteFileFinished
);
753 void DolphinView::cutSelectedItemsToClipboard()
755 QMimeData
* mimeData
= selectionMimeData();
756 KIO::setClipboardDataCut(mimeData
, true);
757 QApplication::clipboard()->setMimeData(mimeData
);
760 void DolphinView::copySelectedItemsToClipboard()
762 QMimeData
* mimeData
= selectionMimeData();
763 QApplication::clipboard()->setMimeData(mimeData
);
766 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
768 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
769 KJobWidgets::setWindow(job
, this);
771 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
772 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
773 KIO::FileUndoManager::self()->recordCopyJob(job
);
776 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
778 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
779 KJobWidgets::setWindow(job
, this);
781 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
782 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
783 KIO::FileUndoManager::self()->recordCopyJob(job
);
787 void DolphinView::paste()
792 void DolphinView::pasteIntoFolder()
794 const KFileItemList items
= selectedItems();
795 if ((items
.count() == 1) && items
.first().isDir()) {
796 pasteToUrl(items
.first().url());
800 void DolphinView::duplicateSelectedItems()
802 const KFileItemList itemList
= selectedItems();
803 if (itemList
.isEmpty()) {
807 const QMimeDatabase db
;
809 // Duplicate all selected items and append "copy" to the end of the file name
810 // but before the filename extension, if present
811 QList
<QUrl
> newSelection
;
812 for (const auto &item
: itemList
) {
813 const QUrl originalURL
= item
.url();
814 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
815 const QString originalFileName
= item
.name();
817 QString extension
= db
.suffixForFileName(originalFileName
);
819 QUrl duplicateURL
= originalURL
;
821 // No extension; new filename is "<oldfilename> copy"
822 if (extension
.isEmpty()) {
823 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
824 // There's an extension; new filename is "<oldfilename> copy.<extension>"
826 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
827 extension
= QLatin1String(".") + extension
;
828 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
829 // Preserve file's original filename extension in case the casing differs
830 // from what QMimeDatabase::suffixForFileName() returned
831 const QString originalExtension
= originalFileName
.right(extension
.size());
832 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
835 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
836 KJobWidgets::setWindow(job
, this);
839 newSelection
<< duplicateURL
;
840 KIO::FileUndoManager::self()->recordCopyJob(job
);
844 forceUrlsSelection(newSelection
.first(), newSelection
);
847 void DolphinView::stopLoading()
849 m_model
->cancelDirectoryLoading();
852 void DolphinView::updatePalette()
854 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
859 QWidget
* viewport
= m_container
->viewport();
862 palette
.setColor(viewport
->backgroundRole(), color
);
863 viewport
->setPalette(palette
);
869 void DolphinView::abortTwoClicksRenaming()
871 m_twoClicksRenamingItemUrl
.clear();
872 m_twoClicksRenamingTimer
->stop();
875 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
877 switch (event
->type()) {
878 case QEvent::PaletteChange
:
880 QPixmapCache::clear();
883 case QEvent::WindowActivate
:
884 case QEvent::WindowDeactivate
:
888 case QEvent::KeyPress
:
889 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
890 if (GeneralSettings::useTabForSwitchingSplitView()) {
891 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
892 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
893 Q_EMIT
toggleActiveViewRequested();
898 case QEvent::FocusIn
:
899 if (watched
== m_container
) {
904 case QEvent::GraphicsSceneDragEnter
:
905 if (watched
== m_view
) {
907 abortTwoClicksRenaming();
911 case QEvent::GraphicsSceneDragLeave
:
912 if (watched
== m_view
) {
917 case QEvent::GraphicsSceneDrop
:
918 if (watched
== m_view
) {
925 return QWidget::eventFilter(watched
, event
);
928 void DolphinView::wheelEvent(QWheelEvent
* event
)
930 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
931 const QPoint numDegrees
= event
->angleDelta() / 8;
932 const QPoint numSteps
= numDegrees
/ 15;
934 setZoomLevel(zoomLevel() + numSteps
.y());
941 void DolphinView::hideEvent(QHideEvent
* event
)
944 QWidget::hideEvent(event
);
947 bool DolphinView::event(QEvent
* event
)
949 if (event
->type() == QEvent::WindowDeactivate
) {
951 * Dolphin leaves file preview tooltips open even when is not visible.
953 * Hide tool-tip when Dolphin loses focus.
956 abortTwoClicksRenaming();
959 return QWidget::event(event
);
962 void DolphinView::activate()
967 void DolphinView::slotItemActivated(int index
)
969 abortTwoClicksRenaming();
971 const KFileItem item
= m_model
->fileItem(index
);
972 if (!item
.isNull()) {
973 Q_EMIT
itemActivated(item
);
977 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
979 Q_ASSERT(indexes
.count() >= 2);
981 abortTwoClicksRenaming();
983 if (indexes
.count() > 5) {
984 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
985 const int answer
= KMessageBox::warningYesNo(this, question
);
986 if (answer
!= KMessageBox::Yes
) {
992 items
.reserve(indexes
.count());
994 for (int index
: indexes
) {
995 KFileItem item
= m_model
->fileItem(index
);
996 const QUrl
& url
= openItemAsFolderUrl(item
);
998 if (!url
.isEmpty()) { // Open folders in new tabs
999 Q_EMIT
tabRequested(url
);
1005 if (items
.count() == 1) {
1006 Q_EMIT
itemActivated(items
.first());
1007 } else if (items
.count() > 1) {
1008 Q_EMIT
itemsActivated(items
);
1012 void DolphinView::slotItemMiddleClicked(int index
)
1014 const KFileItem
& item
= m_model
->fileItem(index
);
1015 const QUrl
& url
= openItemAsFolderUrl(item
);
1016 if (!url
.isEmpty()) {
1017 Q_EMIT
tabRequested(url
);
1018 } else if (isTabsForFilesEnabled()) {
1019 Q_EMIT
tabRequested(item
.url());
1023 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
1025 // Force emit of a selection changed signal before we request the
1026 // context menu, to update the edit-actions first. (See Bug 294013)
1027 if (m_selectionChangedTimer
->isActive()) {
1028 emitSelectionChangedSignal();
1031 const KFileItem item
= m_model
->fileItem(index
);
1032 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
1035 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
1037 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
1040 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
1042 ViewProperties
props(viewPropertiesUrl());
1044 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
1046 KItemListView
* view
= m_container
->controller()->view();
1047 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1049 bool indexingEnabled
= false;
1051 Baloo::IndexerConfig config
;
1052 indexingEnabled
= config
.fileIndexingEnabled();
1056 QMenu
* groupMenu
= nullptr;
1058 // Add all roles to the menu that can be shown or hidden by the user
1059 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1060 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1061 if (info
.role
== "text") {
1062 // It should not be possible to hide the "text" role
1066 const QString text
= m_model
->roleDescription(info
.role
);
1067 QAction
* action
= nullptr;
1068 if (info
.group
.isEmpty()) {
1069 action
= menu
->addAction(text
);
1071 if (!groupMenu
|| info
.group
!= groupName
) {
1072 groupName
= info
.group
;
1073 groupMenu
= menu
->addMenu(groupName
);
1076 action
= groupMenu
->addAction(text
);
1079 action
->setCheckable(true);
1080 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1081 action
->setData(info
.role
);
1083 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1084 (info
.requiresBaloo
) ||
1085 (info
.requiresIndexer
&& indexingEnabled
);
1086 action
->setEnabled(enable
);
1089 menu
->addSeparator();
1091 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1092 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1094 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1095 autoAdjustWidthsAction
->setCheckable(true);
1096 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1097 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1099 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1100 customWidthsAction
->setCheckable(true);
1101 customWidthsAction
->setChecked(!autoColumnWidths
);
1102 customWidthsAction
->setActionGroup(widthsGroup
);
1104 QAction
* action
= menu
->exec(pos
.toPoint());
1105 if (menu
&& action
) {
1106 KItemListHeader
* header
= view
->header();
1108 if (action
== autoAdjustWidthsAction
) {
1109 // Clear the column-widths from the viewproperties and turn on
1110 // the automatic resizing of the columns
1111 props
.setHeaderColumnWidths(QList
<int>());
1112 header
->setAutomaticColumnResizing(true);
1113 } else if (action
== customWidthsAction
) {
1114 // Apply the current column-widths as custom column-widths and turn
1115 // off the automatic resizing of the columns
1116 QList
<int> columnWidths
;
1117 const auto visibleRoles
= view
->visibleRoles();
1118 columnWidths
.reserve(visibleRoles
.count());
1119 for (const QByteArray
& role
: visibleRoles
) {
1120 columnWidths
.append(header
->columnWidth(role
));
1122 props
.setHeaderColumnWidths(columnWidths
);
1123 header
->setAutomaticColumnResizing(false);
1125 // Show or hide the selected role
1126 const QByteArray selectedRole
= action
->data().toByteArray();
1128 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1129 if (action
->isChecked()) {
1130 visibleRoles
.append(selectedRole
);
1132 visibleRoles
.removeOne(selectedRole
);
1135 view
->setVisibleRoles(visibleRoles
);
1136 props
.setVisibleRoles(visibleRoles
);
1138 QList
<int> columnWidths
;
1139 if (!header
->automaticColumnResizing()) {
1140 const auto visibleRoles
= view
->visibleRoles();
1141 columnWidths
.reserve(visibleRoles
.count());
1142 for (const QByteArray
& role
: visibleRoles
) {
1143 columnWidths
.append(header
->columnWidth(role
));
1146 props
.setHeaderColumnWidths(columnWidths
);
1153 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1155 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1157 ViewProperties
props(viewPropertiesUrl());
1158 QList
<int> columnWidths
= props
.headerColumnWidths();
1159 if (columnWidths
.count() != visibleRoles
.count()) {
1160 columnWidths
.clear();
1161 columnWidths
.reserve(visibleRoles
.count());
1162 const KItemListHeader
* header
= m_view
->header();
1163 for (const QByteArray
& role
: visibleRoles
) {
1164 const int width
= header
->columnWidth(role
);
1165 columnWidths
.append(width
);
1169 const int roleIndex
= visibleRoles
.indexOf(role
);
1170 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1171 columnWidths
[roleIndex
] = current
;
1173 props
.setHeaderColumnWidths(columnWidths
);
1176 void DolphinView::slotItemHovered(int index
)
1178 const KFileItem item
= m_model
->fileItem(index
);
1180 if (GeneralSettings::showToolTips() && !m_dragging
) {
1181 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1182 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1183 itemRect
.moveTo(pos
);
1186 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1190 Q_EMIT
requestItemInfo(item
);
1193 void DolphinView::slotItemUnhovered(int index
)
1197 Q_EMIT
requestItemInfo(KFileItem());
1200 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1203 KFileItem destItem
= m_model
->fileItem(index
);
1204 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1205 // Use the URL of the view as drop target if the item is no directory
1207 destItem
= m_model
->rootItem();
1210 // The item represents a directory or desktop-file
1211 destUrl
= destItem
.mostLocalUrl();
1214 QDropEvent
dropEvent(event
->pos().toPoint(),
1215 event
->possibleActions(),
1218 event
->modifiers());
1219 dropUrls(destUrl
, &dropEvent
, this);
1224 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1226 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1229 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1231 if (destUrl
== url()) {
1232 // Mark the dropped urls as selected.
1233 m_clearSelectionBeforeSelectingNewItems
= true;
1234 m_markFirstNewlySelectedItemAsCurrent
= true;
1235 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1240 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1242 if (previous
!= nullptr) {
1243 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1244 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1245 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1246 m_versionControlObserver
->setModel(nullptr);
1250 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1251 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1252 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1253 m_versionControlObserver
->setModel(fileItemModel
);
1257 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1263 if (buttons
& Qt::BackButton
) {
1264 Q_EMIT
goBackRequested();
1265 } else if (buttons
& Qt::ForwardButton
) {
1266 Q_EMIT
goForwardRequested();
1270 void DolphinView::slotSelectedItemTextPressed(int index
)
1272 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1273 const KFileItem item
= m_model
->fileItem(index
);
1274 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1275 if (capabilities
.supportsMoving()) {
1276 m_twoClicksRenamingItemUrl
= item
.url();
1277 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1282 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1284 slotItemCreated(to
);
1287 void DolphinView::slotItemCreated(const QUrl
& url
)
1289 if (m_markFirstNewlySelectedItemAsCurrent
) {
1290 markUrlAsCurrent(url
);
1291 m_markFirstNewlySelectedItemAsCurrent
= false;
1293 m_selectedUrls
<< url
;
1296 void DolphinView::slotJobResult(KJob
*job
)
1299 Q_EMIT
errorMessage(job
->errorString());
1301 if (!m_selectedUrls
.isEmpty()) {
1302 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1306 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1308 const int currentCount
= current
.count();
1309 const int previousCount
= previous
.count();
1310 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1311 (currentCount
> 0 && previousCount
== 0);
1313 // If nothing has been selected before and something got selected (or if something
1314 // was selected before and now nothing is selected) the selectionChangedSignal must
1315 // be emitted asynchronously as fast as possible to update the edit-actions.
1316 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1317 m_selectionChangedTimer
->start();
1320 void DolphinView::emitSelectionChangedSignal()
1322 m_selectionChangedTimer
->stop();
1323 Q_EMIT
selectionChanged(selectedItems());
1326 void DolphinView::slotStatJobResult(KJob
*job
)
1328 int folderCount
= 0;
1330 KIO::filesize_t totalFileSize
= 0;
1331 bool countFileSize
= true;
1333 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1334 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1335 // We have a precomputed value.
1336 totalFileSize
= static_cast<KIO::filesize_t
>(
1337 entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1338 countFileSize
= false;
1341 const int itemCount
= m_model
->count();
1342 for (int i
= 0; i
< itemCount
; ++i
) {
1343 const KFileItem item
= m_model
->fileItem(i
);
1348 if (countFileSize
) {
1349 totalFileSize
+= item
.size();
1353 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1356 void DolphinView::updateSortRole(const QByteArray
& role
)
1358 ViewProperties
props(viewPropertiesUrl());
1359 props
.setSortRole(role
);
1361 KItemModelBase
* model
= m_container
->controller()->model();
1362 model
->setSortRole(role
);
1364 Q_EMIT
sortRoleChanged(role
);
1367 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1369 ViewProperties
props(viewPropertiesUrl());
1370 props
.setSortOrder(order
);
1372 m_model
->setSortOrder(order
);
1374 Q_EMIT
sortOrderChanged(order
);
1377 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1379 ViewProperties
props(viewPropertiesUrl());
1380 props
.setSortFoldersFirst(foldersFirst
);
1382 m_model
->setSortDirectoriesFirst(foldersFirst
);
1384 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1387 void DolphinView::updateSortHiddenLast(bool hiddenLast
)
1389 ViewProperties
props(viewPropertiesUrl());
1390 props
.setSortHiddenLast(hiddenLast
);
1392 m_model
->setSortHiddenLast(hiddenLast
);
1394 Q_EMIT
sortHiddenLastChanged(hiddenLast
);
1398 QPair
<bool, QString
> DolphinView::pasteInfo() const
1400 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1401 QPair
<bool, QString
> info
;
1402 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1406 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1408 m_tabsForFiles
= tabsForFiles
;
1411 bool DolphinView::isTabsForFilesEnabled() const
1413 return m_tabsForFiles
;
1416 bool DolphinView::itemsExpandable() const
1418 return m_mode
== DetailsView
;
1421 void DolphinView::restoreState(QDataStream
& stream
)
1423 // Read the version number of the view state and check if the version is supported.
1424 quint32 version
= 0;
1427 // The version of the view state isn't supported, we can't restore it.
1431 // Restore the current item that had the keyboard focus
1432 stream
>> m_currentItemUrl
;
1434 // Restore the previously selected items
1435 stream
>> m_selectedUrls
;
1437 // Restore the view position
1438 stream
>> m_restoredContentsPosition
;
1440 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1443 m_model
->restoreExpandedDirectories(urls
);
1446 void DolphinView::saveState(QDataStream
& stream
)
1448 stream
<< quint32(1); // View state version
1450 // Save the current item that has the keyboard focus
1451 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1452 if (currentIndex
!= -1) {
1453 KFileItem item
= m_model
->fileItem(currentIndex
);
1454 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1455 QUrl currentItemUrl
= item
.url();
1456 stream
<< currentItemUrl
;
1461 // Save the selected urls
1462 stream
<< selectedItems().urlList();
1464 // Save view position
1465 const qreal x
= m_container
->horizontalScrollBar()->value();
1466 const qreal y
= m_container
->verticalScrollBar()->value();
1467 stream
<< QPoint(x
, y
);
1469 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1470 stream
<< m_model
->expandedDirectories();
1473 KFileItem
DolphinView::rootItem() const
1475 return m_model
->rootItem();
1478 void DolphinView::setViewPropertiesContext(const QString
& context
)
1480 m_viewPropertiesContext
= context
;
1483 QString
DolphinView::viewPropertiesContext() const
1485 return m_viewPropertiesContext
;
1488 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1490 if (item
.isNull()) {
1494 QUrl url
= item
.targetUrl();
1500 if (item
.isMimeTypeKnown()) {
1501 const QString
& mimetype
= item
.mimetype();
1503 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1504 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1505 // zip:/<path>/ when clicking on a zip file, etc.
1506 // The .protocol file specifies the mimetype that the kioslave handles.
1507 // Note that we don't use mimetype inheritance since we don't want to
1508 // open OpenDocument files as zip folders...
1509 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1510 if (!protocol
.isEmpty()) {
1511 url
.setScheme(protocol
);
1516 if (mimetype
== QLatin1String("application/x-desktop")) {
1517 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1518 KDesktopFile
desktopFile(url
.toLocalFile());
1519 if (desktopFile
.hasLinkType()) {
1520 const QString linkUrl
= desktopFile
.readUrl();
1521 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1522 return QUrl::fromUserInput(linkUrl
);
1531 void DolphinView::resetZoomLevel()
1533 ViewModeSettings settings
{m_mode
};
1534 settings
.useDefaults(true);
1535 const int defaultIconSize
= settings
.iconSize();
1536 settings
.useDefaults(false);
1538 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize
, defaultIconSize
)));
1541 void DolphinView::observeCreatedItem(const QUrl
& url
)
1544 forceUrlsSelection(url
, {url
});
1548 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1550 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1551 Q_EMIT
redirection(oldUrl
, newUrl
);
1552 m_url
= newUrl
; // #186947
1556 void DolphinView::updateViewState()
1558 if (m_currentItemUrl
!= QUrl()) {
1559 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1561 // if there is a selection already, leave it that way
1562 if (!selectionManager
->hasSelection()) {
1563 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1564 if (currentIndex
!= -1) {
1565 selectionManager
->setCurrentItem(currentIndex
);
1567 // scroll to current item and reset the state
1568 if (m_scrollToCurrentItem
) {
1569 m_view
->scrollToItem(currentIndex
);
1570 m_scrollToCurrentItem
= false;
1573 selectionManager
->setCurrentItem(0);
1577 m_currentItemUrl
= QUrl();
1580 if (!m_restoredContentsPosition
.isNull()) {
1581 const int x
= m_restoredContentsPosition
.x();
1582 const int y
= m_restoredContentsPosition
.y();
1583 m_restoredContentsPosition
= QPoint();
1585 m_container
->horizontalScrollBar()->setValue(x
);
1586 m_container
->verticalScrollBar()->setValue(y
);
1589 if (!m_selectedUrls
.isEmpty()) {
1590 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1592 // if there is a selection already, leave it that way
1593 if (!selectionManager
->hasSelection()) {
1594 if (m_clearSelectionBeforeSelectingNewItems
) {
1595 selectionManager
->clearSelection();
1596 m_clearSelectionBeforeSelectingNewItems
= false;
1599 KItemSet selectedItems
= selectionManager
->selectedItems();
1601 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1602 while (it
!= m_selectedUrls
.end()) {
1603 const int index
= m_model
->index(*it
);
1605 selectedItems
.insert(index
);
1606 it
= m_selectedUrls
.erase(it
);
1612 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1613 selectionManager
->setSelectedItems(selectedItems
);
1618 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1621 if (GeneralSettings::showToolTips()) {
1622 m_toolTipManager
->hideToolTip(behavior
);
1629 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1631 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1633 // verify that only one item is selected
1634 if (selectionManager
->selectedItems().count() == 1) {
1635 const int index
= selectionManager
->currentItem();
1636 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1638 // check if the selected item was the same item that started the twoClicksRenaming
1639 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1640 renameSelectedItems();
1645 void DolphinView::slotTrashFileFinished(KJob
* job
)
1647 if (job
->error() == 0) {
1648 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1649 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1650 Q_EMIT
errorMessage(job
->errorString());
1654 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1656 if (job
->error() == 0) {
1657 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1658 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1659 Q_EMIT
errorMessage(job
->errorString());
1663 void DolphinView::slotRenamingResult(KJob
* job
)
1666 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1668 const QUrl newUrl
= copyJob
->destUrl();
1669 const int index
= m_model
->index(newUrl
);
1671 QHash
<QByteArray
, QVariant
> data
;
1672 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1673 data
.insert("text", oldUrl
.fileName());
1674 m_model
->setData(index
, data
);
1679 void DolphinView::slotDirectoryLoadingStarted()
1682 updatePlaceholderLabel();
1684 // Disable the writestate temporary until it can be determined in a fast way
1685 // in DolphinView::slotDirectoryLoadingCompleted()
1686 if (m_isFolderWritable
) {
1687 m_isFolderWritable
= false;
1688 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1691 Q_EMIT
directoryLoadingStarted();
1694 void DolphinView::slotDirectoryLoadingCompleted()
1698 // Update the view-state. This has to be done asynchronously
1699 // because the view might not be in its final state yet.
1700 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1702 // Update the placeholder label in case we found that the folder was empty
1705 Q_EMIT
directoryLoadingCompleted();
1707 updatePlaceholderLabel();
1708 updateWritableState();
1711 void DolphinView::slotDirectoryLoadingCanceled()
1715 updatePlaceholderLabel();
1717 Q_EMIT
directoryLoadingCanceled();
1720 void DolphinView::slotItemsChanged()
1722 m_assureVisibleCurrentIndex
= false;
1725 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1728 Q_ASSERT(m_model
->sortOrder() == current
);
1730 ViewProperties
props(viewPropertiesUrl());
1731 props
.setSortOrder(current
);
1733 Q_EMIT
sortOrderChanged(current
);
1736 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1739 Q_ASSERT(m_model
->sortRole() == current
);
1741 ViewProperties
props(viewPropertiesUrl());
1742 props
.setSortRole(current
);
1744 Q_EMIT
sortRoleChanged(current
);
1747 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1748 const QList
<QByteArray
>& previous
)
1751 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1753 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1755 m_visibleRoles
= current
;
1757 ViewProperties
props(viewPropertiesUrl());
1758 props
.setVisibleRoles(m_visibleRoles
);
1760 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1763 void DolphinView::slotRoleEditingCanceled()
1765 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1766 this, &DolphinView::slotRoleEditingFinished
);
1769 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1771 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1772 this, &DolphinView::slotRoleEditingFinished
);
1774 const KFileItemList items
= selectedItems();
1775 if (items
.count() != 1) {
1779 if (role
== "text") {
1780 const KFileItem oldItem
= items
.first();
1781 const EditResult retVal
= value
.value
<EditResult
>();
1782 const QString newName
= retVal
.newName
;
1783 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1784 const QUrl oldUrl
= oldItem
.url();
1786 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1787 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1790 //Confirm hiding file/directory by renaming inline
1791 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1792 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1793 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1795 const auto code
= KMessageBox::questionYesNo(this,
1796 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1797 "Do you still want to rename it?")
1798 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1799 "Do you still want to rename it?"),
1800 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1802 KStandardGuiItem::cancel(),
1803 QStringLiteral("ConfirmHide")
1806 if (code
== KMessageBox::No
) {
1812 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1813 if (!newNameExistsAlready
&& m_model
->index(oldUrl
) == index
) {
1814 // Only change the data in the model if no item with the new name
1815 // is in the model yet. If there is an item with the new name
1816 // already, calling KIO::CopyJob will open a dialog
1817 // asking for a new name, and KFileItemModel will update the
1818 // data when the dir lister signals that the file name has changed.
1819 QHash
<QByteArray
, QVariant
> data
;
1820 data
.insert(role
, retVal
.newName
);
1821 m_model
->setData(index
, data
);
1824 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1825 KJobWidgets::setWindow(job
, this);
1826 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1827 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1829 forceUrlsSelection(newUrl
, {newUrl
});
1831 if (!newNameExistsAlready
) {
1832 // Only connect the result signal if there is no item with the new name
1833 // in the model yet, see bug 328262.
1834 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1837 if (retVal
.direction
!= EditDone
) {
1838 const short indexShift
= retVal
.direction
== EditNext
? 1 : -1;
1839 m_container
->controller()->selectionManager()->setSelected(index
, 1, KItemListSelectionManager::Deselect
);
1840 m_container
->controller()->selectionManager()->setSelected(index
+ indexShift
, 1,
1841 KItemListSelectionManager::Select
);
1842 renameSelectedItems();
1847 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1849 if (!url
.isValid()) {
1850 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1851 if (location
.isEmpty()) {
1852 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1854 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1860 m_model
->refreshDirectory(url
);
1862 m_model
->loadDirectory(url
);
1866 void DolphinView::applyViewProperties()
1868 const ViewProperties
props(viewPropertiesUrl());
1869 applyViewProperties(props
);
1872 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1874 m_view
->beginTransaction();
1876 const Mode mode
= props
.viewMode();
1877 if (m_mode
!= mode
) {
1878 const Mode previousMode
= m_mode
;
1881 // Changing the mode might result in changing
1882 // the zoom level. Remember the old zoom level so
1883 // that zoomLevelChanged() can get emitted.
1884 const int oldZoomLevel
= m_view
->zoomLevel();
1887 Q_EMIT
modeChanged(m_mode
, previousMode
);
1889 if (m_view
->zoomLevel() != oldZoomLevel
) {
1890 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1894 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1895 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1896 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1897 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1900 const bool groupedSorting
= props
.groupedSorting();
1901 if (groupedSorting
!= m_model
->groupedSorting()) {
1902 m_model
->setGroupedSorting(groupedSorting
);
1903 Q_EMIT
groupedSortingChanged(groupedSorting
);
1906 const QByteArray sortRole
= props
.sortRole();
1907 if (sortRole
!= m_model
->sortRole()) {
1908 m_model
->setSortRole(sortRole
);
1909 Q_EMIT
sortRoleChanged(sortRole
);
1912 const Qt::SortOrder sortOrder
= props
.sortOrder();
1913 if (sortOrder
!= m_model
->sortOrder()) {
1914 m_model
->setSortOrder(sortOrder
);
1915 Q_EMIT
sortOrderChanged(sortOrder
);
1918 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1919 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1920 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1921 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1924 const bool sortHiddenLast
= props
.sortHiddenLast();
1925 if (sortHiddenLast
!= m_model
->sortHiddenLast()) {
1926 m_model
->setSortHiddenLast(sortHiddenLast
);
1927 Q_EMIT
sortHiddenLastChanged(sortHiddenLast
);
1930 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1931 if (visibleRoles
!= m_visibleRoles
) {
1932 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1933 m_visibleRoles
= visibleRoles
;
1934 m_view
->setVisibleRoles(visibleRoles
);
1935 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1938 const bool previewsShown
= props
.previewsShown();
1939 if (previewsShown
!= m_view
->previewsShown()) {
1940 const int oldZoomLevel
= zoomLevel();
1942 m_view
->setPreviewsShown(previewsShown
);
1943 Q_EMIT
previewsShownChanged(previewsShown
);
1945 // Changing the preview-state might result in a changed zoom-level
1946 if (oldZoomLevel
!= zoomLevel()) {
1947 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1951 KItemListView
* itemListView
= m_container
->controller()->view();
1952 if (itemListView
->isHeaderVisible()) {
1953 KItemListHeader
* header
= itemListView
->header();
1954 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1955 const int rolesCount
= m_visibleRoles
.count();
1956 if (headerColumnWidths
.count() == rolesCount
) {
1957 header
->setAutomaticColumnResizing(false);
1959 QHash
<QByteArray
, qreal
> columnWidths
;
1960 for (int i
= 0; i
< rolesCount
; ++i
) {
1961 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1963 header
->setColumnWidths(columnWidths
);
1965 header
->setAutomaticColumnResizing(true);
1969 m_view
->endTransaction();
1972 void DolphinView::applyModeToView()
1975 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1976 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1977 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1978 default: Q_ASSERT(false); break;
1982 void DolphinView::pasteToUrl(const QUrl
& url
)
1984 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1985 KJobWidgets::setWindow(job
, this);
1986 m_clearSelectionBeforeSelectingNewItems
= true;
1987 m_markFirstNewlySelectedItemAsCurrent
= true;
1988 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1989 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1992 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1996 const KFileItemList items
= selectedItems();
1997 urls
.reserve(items
.count());
1998 for (const KFileItem
& item
: items
) {
1999 urls
.append(item
.url());
2002 if (itemsExpandable()) {
2003 // TODO: Check if we still need KDirModel for this in KDE 5.0
2004 urls
= KDirModel::simplifiedUrlList(urls
);
2010 QMimeData
* DolphinView::selectionMimeData() const
2012 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
2013 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
2015 return m_model
->createMimeData(selectedIndexes
);
2018 void DolphinView::updateWritableState()
2020 const bool wasFolderWritable
= m_isFolderWritable
;
2021 m_isFolderWritable
= false;
2023 KFileItem item
= m_model
->rootItem();
2024 if (item
.isNull()) {
2025 // Try to find out if the URL is writable even if the "root item" is
2026 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2027 item
= KFileItem(url());
2028 item
.setDelayedMimeTypes(true);
2031 KFileItemListProperties
capabilities(KFileItemList() << item
);
2032 m_isFolderWritable
= capabilities
.supportsWriting();
2034 if (m_isFolderWritable
!= wasFolderWritable
) {
2035 Q_EMIT
writeStateChanged(m_isFolderWritable
);
2039 QUrl
DolphinView::viewPropertiesUrl() const
2041 if (m_viewPropertiesContext
.isEmpty()) {
2046 url
.setScheme(m_url
.scheme());
2047 url
.setPath(m_viewPropertiesContext
);
2051 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
2053 forceUrlsSelection(urls
.first(), urls
);
2056 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
2059 m_clearSelectionBeforeSelectingNewItems
= true;
2060 markUrlAsCurrent(current
);
2061 markUrlsAsSelected(selected
);
2064 void DolphinView::copyPathToClipboard()
2066 const KFileItemList list
= selectedItems();
2067 if (list
.isEmpty()) {
2070 const KFileItem
& item
= list
.at(0);
2071 QString path
= item
.localPath();
2072 if (path
.isEmpty()) {
2073 path
= item
.url().toDisplayString();
2075 QClipboard
* clipboard
= QApplication::clipboard();
2076 if (clipboard
== nullptr) {
2079 clipboard
->setText(path
);
2082 void DolphinView::slotIncreaseZoom()
2084 setZoomLevel(zoomLevel() + 1);
2087 void DolphinView::slotDecreaseZoom()
2089 setZoomLevel(zoomLevel() - 1);
2092 void DolphinView::slotSwipeUp()
2094 Q_EMIT
goUpRequested();
2097 void DolphinView::showLoadingPlaceholder()
2099 m_placeholderLabel
->setText(i18n("Loading..."));
2100 m_placeholderLabel
->setVisible(true);
2103 void DolphinView::updatePlaceholderLabel()
2105 m_showLoadingPlaceholderTimer
->stop();
2106 if (itemsCount() > 0) {
2107 m_placeholderLabel
->setVisible(false);
2112 m_placeholderLabel
->setVisible(false);
2113 m_showLoadingPlaceholderTimer
->start();
2117 if (!nameFilter().isEmpty()) {
2118 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2119 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2120 m_placeholderLabel
->setText(i18n("No items matching the search"));
2121 } else if (m_url
.scheme() == QLatin1String("trash") && m_url
.path() == QLatin1String("/")) {
2122 m_placeholderLabel
->setText(i18n("Trash is empty"));
2123 } else if (m_url
.scheme() == QLatin1String("tags")) {
2124 m_placeholderLabel
->setText(i18n("No tags"));
2125 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2126 m_placeholderLabel
->setText(i18n("No recently used items"));
2127 } else if (m_url
.scheme() == QLatin1String("smb")) {
2128 m_placeholderLabel
->setText(i18n("No shared folders found"));
2129 } else if (m_url
.scheme() == QLatin1String("network")) {
2130 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2131 } else if (m_url
.scheme() == QLatin1String("mtp") && m_url
.path() == QLatin1String("/")) {
2132 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2133 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2134 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2136 m_placeholderLabel
->setText(i18n("Folder is empty"));
2139 m_placeholderLabel
->setVisible(true);