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 #include "kitemviews/kfileitemlistview.h"
16 #include "kitemviews/kfileitemmodel.h"
17 #include "kitemviews/kitemlistcontainer.h"
18 #include "kitemviews/kitemlistcontroller.h"
19 #include "kitemviews/kitemlistheader.h"
20 #include "kitemviews/kitemlistselectionmanager.h"
21 #include "versioncontrol/versioncontrolobserver.h"
22 #include "viewproperties.h"
23 #include "views/tooltips/tooltipmanager.h"
24 #include "zoomlevelinfo.h"
27 #include <Baloo/IndexerConfig>
29 #include <KColorScheme>
30 #include <KDesktopFile>
32 #include <KFileItemListProperties>
34 #include <KIO/CopyJob>
35 #include <KIO/DeleteJob>
36 #include <KIO/DropJob>
37 #include <KIO/JobUiDelegate>
39 #include <KIO/PasteJob>
40 #include <KIO/PreviewJob>
41 #include <KIO/RenameFileDialog>
42 #include <KJobWidgets>
43 #include <KLocalizedString>
44 #include <KMessageBox>
45 #include <KProtocolManager>
47 #include <QAbstractItemView>
48 #include <QApplication>
51 #include <QGraphicsOpacityEffect>
52 #include <QGraphicsSceneDragDropEvent>
55 #include <QMimeDatabase>
56 #include <QPixmapCache>
61 #include <QVBoxLayout>
63 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
66 m_tabsForFiles(false),
67 m_assureVisibleCurrentIndex(false),
68 m_isFolderWritable(true),
72 m_viewPropertiesContext(),
73 m_mode(DolphinView::IconsView
),
79 m_toolTipManager(nullptr),
80 m_selectionChangedTimer(nullptr),
82 m_scrollToCurrentItem(false),
83 m_restoredContentsPosition(),
85 m_clearSelectionBeforeSelectingNewItems(false),
86 m_markFirstNewlySelectedItemAsCurrent(false),
87 m_versionControlObserver(nullptr),
88 m_twoClicksRenamingTimer(nullptr),
89 m_placeholderLabel(nullptr)
91 m_topLayout
= new QVBoxLayout(this);
92 m_topLayout
->setSpacing(0);
93 m_topLayout
->setContentsMargins(0, 0, 0, 0);
95 // When a new item has been created by the "Create New..." menu, the item should
96 // get selected and it must be assured that the item will get visible. As the
97 // creation is done asynchronously, several signals must be checked:
98 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
99 this, &DolphinView::observeCreatedItem
);
101 m_selectionChangedTimer
= new QTimer(this);
102 m_selectionChangedTimer
->setSingleShot(true);
103 m_selectionChangedTimer
->setInterval(300);
104 connect(m_selectionChangedTimer
, &QTimer::timeout
,
105 this, &DolphinView::emitSelectionChangedSignal
);
107 m_model
= new KFileItemModel(this);
108 m_view
= new DolphinItemListView();
109 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
110 m_view
->setVisibleRoles({"text"});
113 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
114 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
115 controller
->setAutoActivationDelay(delay
);
117 // The EnlargeSmallPreviews setting can only be changed after the model
118 // has been set in the view by KItemListController.
119 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
121 m_container
= new KItemListContainer(controller
, this);
122 m_container
->installEventFilter(this);
123 setFocusProxy(m_container
);
124 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
125 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
127 // Show some placeholder text for empty folders
128 // This is made using a heavily-modified QLabel rather than a KTitleWidget
129 // because KTitleWidget can't be told to turn off mouse-selectable text
130 m_placeholderLabel
= new QLabel(this);
131 QFont placeholderLabelFont
;
132 // To match the size of a level 2 Heading/KTitleWidget
133 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
134 m_placeholderLabel
->setFont(placeholderLabelFont
);
135 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
136 m_placeholderLabel
->setWordWrap(true);
137 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
138 // Match opacity of QML placeholder label component
139 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
140 effect
->setOpacity(0.5);
141 m_placeholderLabel
->setGraphicsEffect(effect
);
142 // Set initial text and visibility
143 updatePlaceholderLabel();
145 auto *centeringLayout
= new QVBoxLayout(m_container
);
146 centeringLayout
->addWidget(m_placeholderLabel
);
147 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
149 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
150 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
151 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
152 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
153 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
154 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
155 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
156 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
157 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
158 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
159 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
160 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
161 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
162 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
163 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
164 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
165 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
167 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
168 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
169 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
170 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
171 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
172 connect(m_model
, &KFileItemModel::itemsChanged
,
173 this, &DolphinView::slotItemsChanged
);
174 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
175 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
176 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
177 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
178 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
179 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
181 connect(this, &DolphinView::itemCountChanged
,
182 this, &DolphinView::updatePlaceholderLabel
);
184 m_view
->installEventFilter(this);
185 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
186 this, &DolphinView::slotSortOrderChangedByHeader
);
187 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
188 this, &DolphinView::slotSortRoleChangedByHeader
);
189 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
190 this, &DolphinView::slotVisibleRolesChangedByHeader
);
191 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
192 this, &DolphinView::slotRoleEditingCanceled
);
193 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
194 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
196 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
197 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
198 this, &DolphinView::slotSelectionChanged
);
201 m_toolTipManager
= new ToolTipManager(this);
202 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
205 m_versionControlObserver
= new VersionControlObserver(this);
206 m_versionControlObserver
->setView(this);
207 m_versionControlObserver
->setModel(m_model
);
208 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
209 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
210 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
212 m_twoClicksRenamingTimer
= new QTimer(this);
213 m_twoClicksRenamingTimer
->setSingleShot(true);
214 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
216 applyViewProperties();
217 m_topLayout
->addWidget(m_container
);
222 DolphinView::~DolphinView()
226 QUrl
DolphinView::url() const
231 void DolphinView::setActive(bool active
)
233 if (active
== m_active
) {
242 m_container
->setFocus();
244 Q_EMIT
writeStateChanged(m_isFolderWritable
);
248 bool DolphinView::isActive() const
253 void DolphinView::setMode(Mode mode
)
255 if (mode
!= m_mode
) {
256 ViewProperties
props(viewPropertiesUrl());
257 props
.setViewMode(mode
);
259 // We pass the new ViewProperties to applyViewProperties, rather than
260 // storing them on disk and letting applyViewProperties() read them
261 // from there, to prevent that changing the view mode fails if the
262 // .directory file is not writable (see bug 318534).
263 applyViewProperties(props
);
267 DolphinView::Mode
DolphinView::mode() const
272 void DolphinView::setPreviewsShown(bool show
)
274 if (previewsShown() == show
) {
278 ViewProperties
props(viewPropertiesUrl());
279 props
.setPreviewsShown(show
);
281 const int oldZoomLevel
= m_view
->zoomLevel();
282 m_view
->setPreviewsShown(show
);
283 Q_EMIT
previewsShownChanged(show
);
285 const int newZoomLevel
= m_view
->zoomLevel();
286 if (newZoomLevel
!= oldZoomLevel
) {
287 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
291 bool DolphinView::previewsShown() const
293 return m_view
->previewsShown();
296 void DolphinView::setHiddenFilesShown(bool show
)
298 if (m_model
->showHiddenFiles() == show
) {
302 const KFileItemList itemList
= selectedItems();
303 m_selectedUrls
.clear();
304 m_selectedUrls
= itemList
.urlList();
306 ViewProperties
props(viewPropertiesUrl());
307 props
.setHiddenFilesShown(show
);
309 m_model
->setShowHiddenFiles(show
);
310 Q_EMIT
hiddenFilesShownChanged(show
);
313 bool DolphinView::hiddenFilesShown() const
315 return m_model
->showHiddenFiles();
318 void DolphinView::setGroupedSorting(bool grouped
)
320 if (grouped
== groupedSorting()) {
324 ViewProperties
props(viewPropertiesUrl());
325 props
.setGroupedSorting(grouped
);
328 m_container
->controller()->model()->setGroupedSorting(grouped
);
330 Q_EMIT
groupedSortingChanged(grouped
);
333 bool DolphinView::groupedSorting() const
335 return m_model
->groupedSorting();
338 KFileItemList
DolphinView::items() const
341 const int itemCount
= m_model
->count();
342 list
.reserve(itemCount
);
344 for (int i
= 0; i
< itemCount
; ++i
) {
345 list
.append(m_model
->fileItem(i
));
351 int DolphinView::itemsCount() const
353 return m_model
->count();
356 KFileItemList
DolphinView::selectedItems() const
358 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
360 KFileItemList selectedItems
;
361 const auto items
= selectionManager
->selectedItems();
362 selectedItems
.reserve(items
.count());
363 for (int index
: items
) {
364 selectedItems
.append(m_model
->fileItem(index
));
366 return selectedItems
;
369 int DolphinView::selectedItemsCount() const
371 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
372 return selectionManager
->selectedItems().count();
375 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
377 m_selectedUrls
= urls
;
380 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
382 m_currentItemUrl
= url
;
383 m_scrollToCurrentItem
= true;
386 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
388 const KItemListSelectionManager::SelectionMode mode
= enabled
389 ? KItemListSelectionManager::Select
390 : KItemListSelectionManager::Deselect
;
391 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
393 for (int index
= 0; index
< m_model
->count(); index
++) {
394 const KFileItem item
= m_model
->fileItem(index
);
395 if (regexp
.match(item
.text()).hasMatch()) {
396 // An alternative approach would be to store the matching items in a KItemSet and
397 // select them in one go after the loop, but we'd need a new function
398 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
400 selectionManager
->setSelected(index
, 1, mode
);
405 void DolphinView::setZoomLevel(int level
)
407 const int oldZoomLevel
= zoomLevel();
408 m_view
->setZoomLevel(level
);
409 if (zoomLevel() != oldZoomLevel
) {
411 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
415 int DolphinView::zoomLevel() const
417 return m_view
->zoomLevel();
420 void DolphinView::setSortRole(const QByteArray
& role
)
422 if (role
!= sortRole()) {
423 updateSortRole(role
);
427 QByteArray
DolphinView::sortRole() const
429 const KItemModelBase
* model
= m_container
->controller()->model();
430 return model
->sortRole();
433 void DolphinView::setSortOrder(Qt::SortOrder order
)
435 if (sortOrder() != order
) {
436 updateSortOrder(order
);
440 Qt::SortOrder
DolphinView::sortOrder() const
442 return m_model
->sortOrder();
445 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
447 if (sortFoldersFirst() != foldersFirst
) {
448 updateSortFoldersFirst(foldersFirst
);
452 bool DolphinView::sortFoldersFirst() const
454 return m_model
->sortDirectoriesFirst();
457 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
459 const QList
<QByteArray
> previousRoles
= roles
;
461 ViewProperties
props(viewPropertiesUrl());
462 props
.setVisibleRoles(roles
);
464 m_visibleRoles
= roles
;
465 m_view
->setVisibleRoles(roles
);
467 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
470 QList
<QByteArray
> DolphinView::visibleRoles() const
472 return m_visibleRoles
;
475 void DolphinView::reload()
477 QByteArray viewState
;
478 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
479 saveState(saveStream
);
482 loadDirectory(url(), true);
484 QDataStream
restoreStream(viewState
);
485 restoreState(restoreStream
);
488 void DolphinView::readSettings()
490 const int oldZoomLevel
= m_view
->zoomLevel();
492 GeneralSettings::self()->load();
493 m_view
->readSettings();
494 applyViewProperties();
496 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
497 m_container
->controller()->setAutoActivationDelay(delay
);
499 const int newZoomLevel
= m_view
->zoomLevel();
500 if (newZoomLevel
!= oldZoomLevel
) {
501 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
505 void DolphinView::writeSettings()
507 GeneralSettings::self()->save();
508 m_view
->writeSettings();
511 void DolphinView::setNameFilter(const QString
& nameFilter
)
513 m_model
->setNameFilter(nameFilter
);
516 QString
DolphinView::nameFilter() const
518 return m_model
->nameFilter();
521 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
523 return m_model
->setMimeTypeFilters(filters
);
526 QStringList
DolphinView::mimeTypeFilters() const
528 return m_model
->mimeTypeFilters();
531 void DolphinView::requestStatusBarText()
533 if (m_statJobForStatusBarText
) {
534 // Kill the pending request.
535 m_statJobForStatusBarText
->kill();
538 if (m_container
->controller()->selectionManager()->hasSelection()) {
541 KIO::filesize_t totalFileSize
= 0;
543 // Give a summary of the status of the selected files
544 const KFileItemList list
= selectedItems();
545 for (const KFileItem
& item
: list
) {
550 totalFileSize
+= item
.size();
554 if (folderCount
+ fileCount
== 1) {
555 // If only one item is selected, show info about it
556 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
558 // At least 2 items are selected
559 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
561 } else { // has no selection
562 if (!m_model
->rootItem().url().isValid()) {
566 m_statJobForStatusBarText
= KIO::statDetails(m_model
->rootItem().url(),
567 KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
568 connect(m_statJobForStatusBarText
, &KJob::result
,
569 this, &DolphinView::slotStatJobResult
);
570 m_statJobForStatusBarText
->start();
574 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
,
575 KIO::filesize_t totalFileSize
, const Selection selection
)
581 if (selection
== HasSelection
) {
582 // At least 2 items are selected because the case of 1 selected item is handled in
583 // DolphinView::requestStatusBarText().
584 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
585 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
587 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
588 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
591 if (fileCount
> 0 && folderCount
> 0) {
592 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
593 foldersText
, filesText
,
594 KFormat().formatByteSize(totalFileSize
));
595 } else if (fileCount
> 0) {
596 summary
= i18nc("@info:status files (size)", "%1 (%2)",
598 KFormat().formatByteSize(totalFileSize
));
599 } else if (folderCount
> 0) {
600 summary
= foldersText
;
602 summary
= i18nc("@info:status", "0 Folders, 0 Files");
604 Q_EMIT
statusBarTextChanged(summary
);
607 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
609 QList
<QAction
*> actions
;
611 if (items
.isEmpty()) {
612 const KFileItem item
= m_model
->rootItem();
613 if (!item
.isNull()) {
614 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
617 actions
= m_versionControlObserver
->actions(items
);
623 void DolphinView::setUrl(const QUrl
& url
)
635 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
636 this, &DolphinView::slotRoleEditingFinished
);
638 // It is important to clear the items from the model before
639 // applying the view properties, otherwise expensive operations
640 // might be done on the existing items although they get cleared
641 // anyhow afterwards by loadDirectory().
643 applyViewProperties();
646 Q_EMIT
urlChanged(url
);
649 void DolphinView::selectAll()
651 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
652 selectionManager
->setSelected(0, m_model
->count());
655 void DolphinView::invertSelection()
657 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
658 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
661 void DolphinView::clearSelection()
663 m_selectedUrls
.clear();
664 m_container
->controller()->selectionManager()->clearSelection();
667 void DolphinView::renameSelectedItems()
669 const KFileItemList items
= selectedItems();
670 if (items
.isEmpty()) {
674 if (items
.count() == 1 && GeneralSettings::renameInline()) {
675 const int index
= m_model
->index(items
.first());
676 m_view
->editRole(index
, "text");
680 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
681 this, &DolphinView::slotRoleEditingFinished
);
683 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
684 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
685 this, &DolphinView::slotRenameDialogRenamingFinished
);
690 // Assure that the current index remains visible when KFileItemModel
691 // will notify the view about changed items (which might result in
692 // a changed sorting).
693 m_assureVisibleCurrentIndex
= true;
696 void DolphinView::trashSelectedItems()
698 const QList
<QUrl
> list
= simplifiedSelectedUrls();
699 KIO::JobUiDelegate uiDelegate
;
700 uiDelegate
.setWindow(window());
701 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
702 KIO::Job
* job
= KIO::trash(list
);
703 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
704 KJobWidgets::setWindow(job
, this);
705 connect(job
, &KIO::Job::result
,
706 this, &DolphinView::slotTrashFileFinished
);
710 void DolphinView::deleteSelectedItems()
712 const QList
<QUrl
> list
= simplifiedSelectedUrls();
714 KIO::JobUiDelegate uiDelegate
;
715 uiDelegate
.setWindow(window());
716 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
717 KIO::Job
* job
= KIO::del(list
);
718 KJobWidgets::setWindow(job
, this);
719 connect(job
, &KIO::Job::result
,
720 this, &DolphinView::slotDeleteFileFinished
);
724 void DolphinView::cutSelectedItemsToClipboard()
726 QMimeData
* mimeData
= selectionMimeData();
727 KIO::setClipboardDataCut(mimeData
, true);
728 QApplication::clipboard()->setMimeData(mimeData
);
731 void DolphinView::copySelectedItemsToClipboard()
733 QMimeData
* mimeData
= selectionMimeData();
734 QApplication::clipboard()->setMimeData(mimeData
);
737 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
739 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
740 KJobWidgets::setWindow(job
, this);
742 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
743 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
744 KIO::FileUndoManager::self()->recordCopyJob(job
);
747 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
749 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
750 KJobWidgets::setWindow(job
, this);
752 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
753 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
754 KIO::FileUndoManager::self()->recordCopyJob(job
);
758 void DolphinView::paste()
763 void DolphinView::pasteIntoFolder()
765 const KFileItemList items
= selectedItems();
766 if ((items
.count() == 1) && items
.first().isDir()) {
767 pasteToUrl(items
.first().url());
771 void DolphinView::duplicateSelectedItems()
773 const KFileItemList itemList
= selectedItems();
774 if (itemList
.isEmpty()) {
778 const QMimeDatabase db
;
780 // Duplicate all selected items and append "copy" to the end of the file name
781 // but before the filename extension, if present
782 QList
<QUrl
> newSelection
;
783 for (const auto &item
: itemList
) {
784 const QUrl originalURL
= item
.url();
785 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
786 const QString originalFileName
= item
.name();
788 QString extension
= db
.suffixForFileName(originalFileName
);
790 QUrl duplicateURL
= originalURL
;
792 // No extension; new filename is "<oldfilename> copy"
793 if (extension
.isEmpty()) {
794 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
795 // There's an extension; new filename is "<oldfilename> copy.<extension>"
797 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
798 extension
= QLatin1String(".") + extension
;
799 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
800 // Preserve file's original filename extension in case the casing differs
801 // from what QMimeDatabase::suffixForFileName() returned
802 const QString originalExtension
= originalFileName
.right(extension
.size());
803 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
806 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
807 KJobWidgets::setWindow(job
, this);
810 newSelection
<< duplicateURL
;
811 KIO::FileUndoManager::self()->recordCopyJob(job
);
815 forceUrlsSelection(newSelection
.first(), newSelection
);
818 void DolphinView::stopLoading()
820 m_model
->cancelDirectoryLoading();
823 void DolphinView::updatePalette()
825 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
830 QWidget
* viewport
= m_container
->viewport();
833 palette
.setColor(viewport
->backgroundRole(), color
);
834 viewport
->setPalette(palette
);
840 void DolphinView::abortTwoClicksRenaming()
842 m_twoClicksRenamingItemUrl
.clear();
843 m_twoClicksRenamingTimer
->stop();
846 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
848 switch (event
->type()) {
849 case QEvent::PaletteChange
:
851 QPixmapCache::clear();
854 case QEvent::WindowActivate
:
855 case QEvent::WindowDeactivate
:
859 case QEvent::KeyPress
:
860 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
861 if (GeneralSettings::useTabForSwitchingSplitView()) {
862 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
863 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
864 Q_EMIT
toggleActiveViewRequested();
869 case QEvent::FocusIn
:
870 if (watched
== m_container
) {
875 case QEvent::GraphicsSceneDragEnter
:
876 if (watched
== m_view
) {
878 abortTwoClicksRenaming();
882 case QEvent::GraphicsSceneDragLeave
:
883 if (watched
== m_view
) {
888 case QEvent::GraphicsSceneDrop
:
889 if (watched
== m_view
) {
896 return QWidget::eventFilter(watched
, event
);
899 void DolphinView::wheelEvent(QWheelEvent
* event
)
901 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
902 const QPoint numDegrees
= event
->angleDelta() / 8;
903 const QPoint numSteps
= numDegrees
/ 15;
905 setZoomLevel(zoomLevel() + numSteps
.y());
912 void DolphinView::hideEvent(QHideEvent
* event
)
915 QWidget::hideEvent(event
);
918 bool DolphinView::event(QEvent
* event
)
920 if (event
->type() == QEvent::WindowDeactivate
) {
922 * Dolphin leaves file preview tooltips open even when is not visible.
924 * Hide tool-tip when Dolphin loses focus.
927 abortTwoClicksRenaming();
930 return QWidget::event(event
);
933 void DolphinView::activate()
938 void DolphinView::slotItemActivated(int index
)
940 abortTwoClicksRenaming();
942 const KFileItem item
= m_model
->fileItem(index
);
943 if (!item
.isNull()) {
944 Q_EMIT
itemActivated(item
);
948 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
950 Q_ASSERT(indexes
.count() >= 2);
952 abortTwoClicksRenaming();
954 if (indexes
.count() > 5) {
955 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
956 const int answer
= KMessageBox::warningYesNo(this, question
);
957 if (answer
!= KMessageBox::Yes
) {
963 items
.reserve(indexes
.count());
965 for (int index
: indexes
) {
966 KFileItem item
= m_model
->fileItem(index
);
967 const QUrl
& url
= openItemAsFolderUrl(item
);
969 if (!url
.isEmpty()) { // Open folders in new tabs
970 Q_EMIT
tabRequested(url
);
976 if (items
.count() == 1) {
977 Q_EMIT
itemActivated(items
.first());
978 } else if (items
.count() > 1) {
979 Q_EMIT
itemsActivated(items
);
983 void DolphinView::slotItemMiddleClicked(int index
)
985 const KFileItem
& item
= m_model
->fileItem(index
);
986 const QUrl
& url
= openItemAsFolderUrl(item
);
987 if (!url
.isEmpty()) {
988 Q_EMIT
tabRequested(url
);
989 } else if (isTabsForFilesEnabled()) {
990 Q_EMIT
tabRequested(item
.url());
994 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
996 // Force emit of a selection changed signal before we request the
997 // context menu, to update the edit-actions first. (See Bug 294013)
998 if (m_selectionChangedTimer
->isActive()) {
999 emitSelectionChangedSignal();
1002 const KFileItem item
= m_model
->fileItem(index
);
1003 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
1006 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
1008 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
1011 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
1013 ViewProperties
props(viewPropertiesUrl());
1015 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
1017 KItemListView
* view
= m_container
->controller()->view();
1018 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1020 bool indexingEnabled
= false;
1022 Baloo::IndexerConfig config
;
1023 indexingEnabled
= config
.fileIndexingEnabled();
1027 QMenu
* groupMenu
= nullptr;
1029 // Add all roles to the menu that can be shown or hidden by the user
1030 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1031 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1032 if (info
.role
== "text") {
1033 // It should not be possible to hide the "text" role
1037 const QString text
= m_model
->roleDescription(info
.role
);
1038 QAction
* action
= nullptr;
1039 if (info
.group
.isEmpty()) {
1040 action
= menu
->addAction(text
);
1042 if (!groupMenu
|| info
.group
!= groupName
) {
1043 groupName
= info
.group
;
1044 groupMenu
= menu
->addMenu(groupName
);
1047 action
= groupMenu
->addAction(text
);
1050 action
->setCheckable(true);
1051 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1052 action
->setData(info
.role
);
1054 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1055 (info
.requiresBaloo
) ||
1056 (info
.requiresIndexer
&& indexingEnabled
);
1057 action
->setEnabled(enable
);
1060 menu
->addSeparator();
1062 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1063 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1065 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1066 autoAdjustWidthsAction
->setCheckable(true);
1067 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1068 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1070 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1071 customWidthsAction
->setCheckable(true);
1072 customWidthsAction
->setChecked(!autoColumnWidths
);
1073 customWidthsAction
->setActionGroup(widthsGroup
);
1075 QAction
* action
= menu
->exec(pos
.toPoint());
1076 if (menu
&& action
) {
1077 KItemListHeader
* header
= view
->header();
1079 if (action
== autoAdjustWidthsAction
) {
1080 // Clear the column-widths from the viewproperties and turn on
1081 // the automatic resizing of the columns
1082 props
.setHeaderColumnWidths(QList
<int>());
1083 header
->setAutomaticColumnResizing(true);
1084 } else if (action
== customWidthsAction
) {
1085 // Apply the current column-widths as custom column-widths and turn
1086 // off the automatic resizing of the columns
1087 QList
<int> columnWidths
;
1088 const auto visibleRoles
= view
->visibleRoles();
1089 columnWidths
.reserve(visibleRoles
.count());
1090 for (const QByteArray
& role
: visibleRoles
) {
1091 columnWidths
.append(header
->columnWidth(role
));
1093 props
.setHeaderColumnWidths(columnWidths
);
1094 header
->setAutomaticColumnResizing(false);
1096 // Show or hide the selected role
1097 const QByteArray selectedRole
= action
->data().toByteArray();
1099 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1100 if (action
->isChecked()) {
1101 visibleRoles
.append(selectedRole
);
1103 visibleRoles
.removeOne(selectedRole
);
1106 view
->setVisibleRoles(visibleRoles
);
1107 props
.setVisibleRoles(visibleRoles
);
1109 QList
<int> columnWidths
;
1110 if (!header
->automaticColumnResizing()) {
1111 const auto visibleRoles
= view
->visibleRoles();
1112 columnWidths
.reserve(visibleRoles
.count());
1113 for (const QByteArray
& role
: visibleRoles
) {
1114 columnWidths
.append(header
->columnWidth(role
));
1117 props
.setHeaderColumnWidths(columnWidths
);
1124 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1126 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1128 ViewProperties
props(viewPropertiesUrl());
1129 QList
<int> columnWidths
= props
.headerColumnWidths();
1130 if (columnWidths
.count() != visibleRoles
.count()) {
1131 columnWidths
.clear();
1132 columnWidths
.reserve(visibleRoles
.count());
1133 const KItemListHeader
* header
= m_view
->header();
1134 for (const QByteArray
& role
: visibleRoles
) {
1135 const int width
= header
->columnWidth(role
);
1136 columnWidths
.append(width
);
1140 const int roleIndex
= visibleRoles
.indexOf(role
);
1141 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1142 columnWidths
[roleIndex
] = current
;
1144 props
.setHeaderColumnWidths(columnWidths
);
1147 void DolphinView::slotItemHovered(int index
)
1149 const KFileItem item
= m_model
->fileItem(index
);
1151 if (GeneralSettings::showToolTips() && !m_dragging
) {
1152 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1153 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1154 itemRect
.moveTo(pos
);
1157 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1161 Q_EMIT
requestItemInfo(item
);
1164 void DolphinView::slotItemUnhovered(int index
)
1168 Q_EMIT
requestItemInfo(KFileItem());
1171 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1174 KFileItem destItem
= m_model
->fileItem(index
);
1175 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1176 // Use the URL of the view as drop target if the item is no directory
1178 destItem
= m_model
->rootItem();
1181 // The item represents a directory or desktop-file
1182 destUrl
= destItem
.mostLocalUrl();
1185 QDropEvent
dropEvent(event
->pos().toPoint(),
1186 event
->possibleActions(),
1189 event
->modifiers());
1190 dropUrls(destUrl
, &dropEvent
, this);
1195 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1197 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1200 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1202 if (destUrl
== url()) {
1203 // Mark the dropped urls as selected.
1204 m_clearSelectionBeforeSelectingNewItems
= true;
1205 m_markFirstNewlySelectedItemAsCurrent
= true;
1206 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1211 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1213 if (previous
!= nullptr) {
1214 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1215 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1216 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1217 m_versionControlObserver
->setModel(nullptr);
1221 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1222 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1223 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1224 m_versionControlObserver
->setModel(fileItemModel
);
1228 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1234 if (buttons
& Qt::BackButton
) {
1235 Q_EMIT
goBackRequested();
1236 } else if (buttons
& Qt::ForwardButton
) {
1237 Q_EMIT
goForwardRequested();
1241 void DolphinView::slotSelectedItemTextPressed(int index
)
1243 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1244 const KFileItem item
= m_model
->fileItem(index
);
1245 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1246 if (capabilities
.supportsMoving()) {
1247 m_twoClicksRenamingItemUrl
= item
.url();
1248 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1253 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1255 slotItemCreated(to
);
1258 void DolphinView::slotItemCreated(const QUrl
& url
)
1260 if (m_markFirstNewlySelectedItemAsCurrent
) {
1261 markUrlAsCurrent(url
);
1262 m_markFirstNewlySelectedItemAsCurrent
= false;
1264 m_selectedUrls
<< url
;
1267 void DolphinView::slotJobResult(KJob
*job
)
1270 Q_EMIT
errorMessage(job
->errorString());
1272 if (!m_selectedUrls
.isEmpty()) {
1273 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1277 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1279 const int currentCount
= current
.count();
1280 const int previousCount
= previous
.count();
1281 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1282 (currentCount
> 0 && previousCount
== 0);
1284 // If nothing has been selected before and something got selected (or if something
1285 // was selected before and now nothing is selected) the selectionChangedSignal must
1286 // be emitted asynchronously as fast as possible to update the edit-actions.
1287 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1288 m_selectionChangedTimer
->start();
1291 void DolphinView::emitSelectionChangedSignal()
1293 m_selectionChangedTimer
->stop();
1294 Q_EMIT
selectionChanged(selectedItems());
1297 void DolphinView::slotStatJobResult(KJob
*job
)
1299 int folderCount
= 0;
1301 KIO::filesize_t totalFileSize
= 0;
1302 bool countFileSize
= true;
1304 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1305 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1306 // We have a precomputed value.
1307 totalFileSize
= static_cast<KIO::filesize_t
>(
1308 entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1309 countFileSize
= false;
1312 const int itemCount
= m_model
->count();
1313 for (int i
= 0; i
< itemCount
; ++i
) {
1314 const KFileItem item
= m_model
->fileItem(i
);
1319 if (countFileSize
) {
1320 totalFileSize
+= item
.size();
1324 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1327 void DolphinView::updateSortRole(const QByteArray
& role
)
1329 ViewProperties
props(viewPropertiesUrl());
1330 props
.setSortRole(role
);
1332 KItemModelBase
* model
= m_container
->controller()->model();
1333 model
->setSortRole(role
);
1335 Q_EMIT
sortRoleChanged(role
);
1338 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1340 ViewProperties
props(viewPropertiesUrl());
1341 props
.setSortOrder(order
);
1343 m_model
->setSortOrder(order
);
1345 Q_EMIT
sortOrderChanged(order
);
1348 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1350 ViewProperties
props(viewPropertiesUrl());
1351 props
.setSortFoldersFirst(foldersFirst
);
1353 m_model
->setSortDirectoriesFirst(foldersFirst
);
1355 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1358 QPair
<bool, QString
> DolphinView::pasteInfo() const
1360 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1361 QPair
<bool, QString
> info
;
1362 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1366 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1368 m_tabsForFiles
= tabsForFiles
;
1371 bool DolphinView::isTabsForFilesEnabled() const
1373 return m_tabsForFiles
;
1376 bool DolphinView::itemsExpandable() const
1378 return m_mode
== DetailsView
;
1381 void DolphinView::restoreState(QDataStream
& stream
)
1383 // Read the version number of the view state and check if the version is supported.
1384 quint32 version
= 0;
1387 // The version of the view state isn't supported, we can't restore it.
1391 // Restore the current item that had the keyboard focus
1392 stream
>> m_currentItemUrl
;
1394 // Restore the previously selected items
1395 stream
>> m_selectedUrls
;
1397 // Restore the view position
1398 stream
>> m_restoredContentsPosition
;
1400 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1403 m_model
->restoreExpandedDirectories(urls
);
1406 void DolphinView::saveState(QDataStream
& stream
)
1408 stream
<< quint32(1); // View state version
1410 // Save the current item that has the keyboard focus
1411 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1412 if (currentIndex
!= -1) {
1413 KFileItem item
= m_model
->fileItem(currentIndex
);
1414 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1415 QUrl currentItemUrl
= item
.url();
1416 stream
<< currentItemUrl
;
1421 // Save the selected urls
1422 stream
<< selectedItems().urlList();
1424 // Save view position
1425 const qreal x
= m_container
->horizontalScrollBar()->value();
1426 const qreal y
= m_container
->verticalScrollBar()->value();
1427 stream
<< QPoint(x
, y
);
1429 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1430 stream
<< m_model
->expandedDirectories();
1433 KFileItem
DolphinView::rootItem() const
1435 return m_model
->rootItem();
1438 void DolphinView::setViewPropertiesContext(const QString
& context
)
1440 m_viewPropertiesContext
= context
;
1443 QString
DolphinView::viewPropertiesContext() const
1445 return m_viewPropertiesContext
;
1448 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1450 if (item
.isNull()) {
1454 QUrl url
= item
.targetUrl();
1460 if (item
.isMimeTypeKnown()) {
1461 const QString
& mimetype
= item
.mimetype();
1463 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1464 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1465 // zip:/<path>/ when clicking on a zip file, etc.
1466 // The .protocol file specifies the mimetype that the kioslave handles.
1467 // Note that we don't use mimetype inheritance since we don't want to
1468 // open OpenDocument files as zip folders...
1469 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1470 if (!protocol
.isEmpty()) {
1471 url
.setScheme(protocol
);
1476 if (mimetype
== QLatin1String("application/x-desktop")) {
1477 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1478 KDesktopFile
desktopFile(url
.toLocalFile());
1479 if (desktopFile
.hasLinkType()) {
1480 const QString linkUrl
= desktopFile
.readUrl();
1481 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1482 return QUrl::fromUserInput(linkUrl
);
1491 void DolphinView::resetZoomLevel()
1493 ViewModeSettings::ViewMode mode
;
1496 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1497 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1498 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1500 const ViewModeSettings
settings(mode
);
1501 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1502 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1505 void DolphinView::observeCreatedItem(const QUrl
& url
)
1508 forceUrlsSelection(url
, {url
});
1512 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1514 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1515 Q_EMIT
redirection(oldUrl
, newUrl
);
1516 m_url
= newUrl
; // #186947
1520 void DolphinView::updateViewState()
1522 if (m_currentItemUrl
!= QUrl()) {
1523 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1525 // if there is a selection already, leave it that way
1526 if (!selectionManager
->hasSelection()) {
1527 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1528 if (currentIndex
!= -1) {
1529 selectionManager
->setCurrentItem(currentIndex
);
1531 // scroll to current item and reset the state
1532 if (m_scrollToCurrentItem
) {
1533 m_view
->scrollToItem(currentIndex
);
1534 m_scrollToCurrentItem
= false;
1537 selectionManager
->setCurrentItem(0);
1541 m_currentItemUrl
= QUrl();
1544 if (!m_restoredContentsPosition
.isNull()) {
1545 const int x
= m_restoredContentsPosition
.x();
1546 const int y
= m_restoredContentsPosition
.y();
1547 m_restoredContentsPosition
= QPoint();
1549 m_container
->horizontalScrollBar()->setValue(x
);
1550 m_container
->verticalScrollBar()->setValue(y
);
1553 if (!m_selectedUrls
.isEmpty()) {
1554 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1556 // if there is a selection already, leave it that way
1557 if (!selectionManager
->hasSelection()) {
1558 if (m_clearSelectionBeforeSelectingNewItems
) {
1559 selectionManager
->clearSelection();
1560 m_clearSelectionBeforeSelectingNewItems
= false;
1563 KItemSet selectedItems
= selectionManager
->selectedItems();
1565 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1566 while (it
!= m_selectedUrls
.end()) {
1567 const int index
= m_model
->index(*it
);
1569 selectedItems
.insert(index
);
1570 it
= m_selectedUrls
.erase(it
);
1576 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1577 selectionManager
->setSelectedItems(selectedItems
);
1582 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1585 if (GeneralSettings::showToolTips()) {
1586 m_toolTipManager
->hideToolTip(behavior
);
1593 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1595 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1597 // verify that only one item is selected
1598 if (selectionManager
->selectedItems().count() == 1) {
1599 const int index
= selectionManager
->currentItem();
1600 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1602 // check if the selected item was the same item that started the twoClicksRenaming
1603 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1604 renameSelectedItems();
1609 void DolphinView::slotTrashFileFinished(KJob
* job
)
1611 if (job
->error() == 0) {
1612 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1613 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1614 Q_EMIT
errorMessage(job
->errorString());
1618 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1620 if (job
->error() == 0) {
1621 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1622 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1623 Q_EMIT
errorMessage(job
->errorString());
1627 void DolphinView::slotRenamingResult(KJob
* job
)
1630 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1632 const QUrl newUrl
= copyJob
->destUrl();
1633 const int index
= m_model
->index(newUrl
);
1635 QHash
<QByteArray
, QVariant
> data
;
1636 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1637 data
.insert("text", oldUrl
.fileName());
1638 m_model
->setData(index
, data
);
1643 void DolphinView::slotDirectoryLoadingStarted()
1646 updatePlaceholderLabel();
1648 // Disable the writestate temporary until it can be determined in a fast way
1649 // in DolphinView::slotDirectoryLoadingCompleted()
1650 if (m_isFolderWritable
) {
1651 m_isFolderWritable
= false;
1652 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1655 Q_EMIT
directoryLoadingStarted();
1658 void DolphinView::slotDirectoryLoadingCompleted()
1662 // Update the view-state. This has to be done asynchronously
1663 // because the view might not be in its final state yet.
1664 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1666 // Update the placeholder label in case we found that the folder was empty
1669 Q_EMIT
directoryLoadingCompleted();
1671 updatePlaceholderLabel();
1672 updateWritableState();
1675 void DolphinView::slotDirectoryLoadingCanceled()
1679 updatePlaceholderLabel();
1681 Q_EMIT
directoryLoadingCanceled();
1684 void DolphinView::slotItemsChanged()
1686 m_assureVisibleCurrentIndex
= false;
1689 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1692 Q_ASSERT(m_model
->sortOrder() == current
);
1694 ViewProperties
props(viewPropertiesUrl());
1695 props
.setSortOrder(current
);
1697 Q_EMIT
sortOrderChanged(current
);
1700 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1703 Q_ASSERT(m_model
->sortRole() == current
);
1705 ViewProperties
props(viewPropertiesUrl());
1706 props
.setSortRole(current
);
1708 Q_EMIT
sortRoleChanged(current
);
1711 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1712 const QList
<QByteArray
>& previous
)
1715 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1717 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1719 m_visibleRoles
= current
;
1721 ViewProperties
props(viewPropertiesUrl());
1722 props
.setVisibleRoles(m_visibleRoles
);
1724 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1727 void DolphinView::slotRoleEditingCanceled()
1729 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1730 this, &DolphinView::slotRoleEditingFinished
);
1733 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1735 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1736 this, &DolphinView::slotRoleEditingFinished
);
1738 if (index
< 0 || index
>= m_model
->count()) {
1742 if (role
== "text") {
1743 const KFileItem oldItem
= m_model
->fileItem(index
);
1744 const QString newName
= value
.toString();
1745 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1746 const QUrl oldUrl
= oldItem
.url();
1748 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1749 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1752 //Confirm hiding file/directory by renaming inline
1753 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1754 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1755 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1757 const auto code
= KMessageBox::questionYesNo(this,
1758 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1759 "Do you still want to rename it?")
1760 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1761 "Do you still want to rename it?"),
1762 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1764 KStandardGuiItem::cancel(),
1765 QStringLiteral("ConfirmHide")
1768 if (code
== KMessageBox::No
) {
1774 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1775 if (!newNameExistsAlready
) {
1776 // Only change the data in the model if no item with the new name
1777 // is in the model yet. If there is an item with the new name
1778 // already, calling KIO::CopyJob will open a dialog
1779 // asking for a new name, and KFileItemModel will update the
1780 // data when the dir lister signals that the file name has changed.
1781 QHash
<QByteArray
, QVariant
> data
;
1782 data
.insert(role
, value
);
1783 m_model
->setData(index
, data
);
1786 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1787 KJobWidgets::setWindow(job
, this);
1788 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1789 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1791 forceUrlsSelection(newUrl
, {newUrl
});
1793 if (!newNameExistsAlready
) {
1794 // Only connect the result signal if there is no item with the new name
1795 // in the model yet, see bug 328262.
1796 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1802 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1804 if (!url
.isValid()) {
1805 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1806 if (location
.isEmpty()) {
1807 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1809 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1815 m_model
->refreshDirectory(url
);
1817 m_model
->loadDirectory(url
);
1821 void DolphinView::applyViewProperties()
1823 const ViewProperties
props(viewPropertiesUrl());
1824 applyViewProperties(props
);
1827 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1829 m_view
->beginTransaction();
1831 const Mode mode
= props
.viewMode();
1832 if (m_mode
!= mode
) {
1833 const Mode previousMode
= m_mode
;
1836 // Changing the mode might result in changing
1837 // the zoom level. Remember the old zoom level so
1838 // that zoomLevelChanged() can get emitted.
1839 const int oldZoomLevel
= m_view
->zoomLevel();
1842 Q_EMIT
modeChanged(m_mode
, previousMode
);
1844 if (m_view
->zoomLevel() != oldZoomLevel
) {
1845 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1849 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1850 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1851 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1852 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1855 const bool groupedSorting
= props
.groupedSorting();
1856 if (groupedSorting
!= m_model
->groupedSorting()) {
1857 m_model
->setGroupedSorting(groupedSorting
);
1858 Q_EMIT
groupedSortingChanged(groupedSorting
);
1861 const QByteArray sortRole
= props
.sortRole();
1862 if (sortRole
!= m_model
->sortRole()) {
1863 m_model
->setSortRole(sortRole
);
1864 Q_EMIT
sortRoleChanged(sortRole
);
1867 const Qt::SortOrder sortOrder
= props
.sortOrder();
1868 if (sortOrder
!= m_model
->sortOrder()) {
1869 m_model
->setSortOrder(sortOrder
);
1870 Q_EMIT
sortOrderChanged(sortOrder
);
1873 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1874 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1875 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1876 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1879 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1880 if (visibleRoles
!= m_visibleRoles
) {
1881 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1882 m_visibleRoles
= visibleRoles
;
1883 m_view
->setVisibleRoles(visibleRoles
);
1884 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1887 const bool previewsShown
= props
.previewsShown();
1888 if (previewsShown
!= m_view
->previewsShown()) {
1889 const int oldZoomLevel
= zoomLevel();
1891 m_view
->setPreviewsShown(previewsShown
);
1892 Q_EMIT
previewsShownChanged(previewsShown
);
1894 // Changing the preview-state might result in a changed zoom-level
1895 if (oldZoomLevel
!= zoomLevel()) {
1896 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1900 KItemListView
* itemListView
= m_container
->controller()->view();
1901 if (itemListView
->isHeaderVisible()) {
1902 KItemListHeader
* header
= itemListView
->header();
1903 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1904 const int rolesCount
= m_visibleRoles
.count();
1905 if (headerColumnWidths
.count() == rolesCount
) {
1906 header
->setAutomaticColumnResizing(false);
1908 QHash
<QByteArray
, qreal
> columnWidths
;
1909 for (int i
= 0; i
< rolesCount
; ++i
) {
1910 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1912 header
->setColumnWidths(columnWidths
);
1914 header
->setAutomaticColumnResizing(true);
1918 m_view
->endTransaction();
1921 void DolphinView::applyModeToView()
1924 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1925 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1926 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1927 default: Q_ASSERT(false); break;
1931 void DolphinView::pasteToUrl(const QUrl
& url
)
1933 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1934 KJobWidgets::setWindow(job
, this);
1935 m_clearSelectionBeforeSelectingNewItems
= true;
1936 m_markFirstNewlySelectedItemAsCurrent
= true;
1937 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1938 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1941 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1945 const KFileItemList items
= selectedItems();
1946 urls
.reserve(items
.count());
1947 for (const KFileItem
& item
: items
) {
1948 urls
.append(item
.url());
1951 if (itemsExpandable()) {
1952 // TODO: Check if we still need KDirModel for this in KDE 5.0
1953 urls
= KDirModel::simplifiedUrlList(urls
);
1959 QMimeData
* DolphinView::selectionMimeData() const
1961 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1962 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1964 return m_model
->createMimeData(selectedIndexes
);
1967 void DolphinView::updateWritableState()
1969 const bool wasFolderWritable
= m_isFolderWritable
;
1970 m_isFolderWritable
= false;
1972 KFileItem item
= m_model
->rootItem();
1973 if (item
.isNull()) {
1974 // Try to find out if the URL is writable even if the "root item" is
1975 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1976 item
= KFileItem(url());
1977 item
.setDelayedMimeTypes(true);
1980 KFileItemListProperties
capabilities(KFileItemList() << item
);
1981 m_isFolderWritable
= capabilities
.supportsWriting();
1983 if (m_isFolderWritable
!= wasFolderWritable
) {
1984 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1988 QUrl
DolphinView::viewPropertiesUrl() const
1990 if (m_viewPropertiesContext
.isEmpty()) {
1995 url
.setScheme(m_url
.scheme());
1996 url
.setPath(m_viewPropertiesContext
);
2000 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
2002 forceUrlsSelection(urls
.first(), urls
);
2005 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
2008 m_clearSelectionBeforeSelectingNewItems
= true;
2009 markUrlAsCurrent(current
);
2010 markUrlsAsSelected(selected
);
2013 void DolphinView::copyPathToClipboard()
2015 const KFileItemList list
= selectedItems();
2016 if (list
.isEmpty()) {
2019 const KFileItem
& item
= list
.at(0);
2020 QString path
= item
.localPath();
2021 if (path
.isEmpty()) {
2022 path
= item
.url().toDisplayString();
2024 QClipboard
* clipboard
= QApplication::clipboard();
2025 if (clipboard
== nullptr) {
2028 clipboard
->setText(path
);
2031 void DolphinView::slotIncreaseZoom()
2033 setZoomLevel(zoomLevel() + 1);
2036 void DolphinView::slotDecreaseZoom()
2038 setZoomLevel(zoomLevel() - 1);
2041 void DolphinView::slotSwipeUp()
2043 Q_EMIT
goUpRequested();
2046 void DolphinView::updatePlaceholderLabel()
2048 if (m_loading
|| itemsCount() > 0) {
2049 m_placeholderLabel
->setVisible(false);
2053 if (!nameFilter().isEmpty()) {
2054 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2055 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2056 m_placeholderLabel
->setText(i18n("No items matching the search"));
2057 } else if (m_url
.scheme() == QLatin1String("trash")) {
2058 m_placeholderLabel
->setText(i18n("Trash is empty"));
2059 } else if (m_url
.scheme() == QLatin1String("tags")) {
2060 m_placeholderLabel
->setText(i18n("No tags"));
2061 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2062 m_placeholderLabel
->setText(i18n("No recently used items"));
2063 } else if (m_url
.scheme() == QLatin1String("smb")) {
2064 m_placeholderLabel
->setText(i18n("No shared folders found"));
2065 } else if (m_url
.scheme() == QLatin1String("network")) {
2066 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2067 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2068 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2069 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2070 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2072 m_placeholderLabel
->setText(i18n("Folder is empty"));
2075 m_placeholderLabel
->setVisible(true);