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 <QActionGroup>
49 #include <QApplication>
52 #include <QGraphicsOpacityEffect>
53 #include <QGraphicsSceneDragDropEvent>
56 #include <QMimeDatabase>
57 #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)
92 m_topLayout
= new QVBoxLayout(this);
93 m_topLayout
->setSpacing(0);
94 m_topLayout
->setContentsMargins(0, 0, 0, 0);
96 // When a new item has been created by the "Create New..." menu, the item should
97 // get selected and it must be assured that the item will get visible. As the
98 // creation is done asynchronously, several signals must be checked:
99 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
100 this, &DolphinView::observeCreatedItem
);
102 m_selectionChangedTimer
= new QTimer(this);
103 m_selectionChangedTimer
->setSingleShot(true);
104 m_selectionChangedTimer
->setInterval(300);
105 connect(m_selectionChangedTimer
, &QTimer::timeout
,
106 this, &DolphinView::emitSelectionChangedSignal
);
108 m_model
= new KFileItemModel(this);
109 m_view
= new DolphinItemListView();
110 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
111 m_view
->setVisibleRoles({"text"});
114 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
115 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
116 controller
->setAutoActivationDelay(delay
);
118 // The EnlargeSmallPreviews setting can only be changed after the model
119 // has been set in the view by KItemListController.
120 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
122 m_container
= new KItemListContainer(controller
, this);
123 m_container
->installEventFilter(this);
124 setFocusProxy(m_container
);
125 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
126 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
128 // Show some placeholder text for empty folders
129 // This is made using a heavily-modified QLabel rather than a KTitleWidget
130 // because KTitleWidget can't be told to turn off mouse-selectable text
131 m_placeholderLabel
= new QLabel(this);
132 QFont placeholderLabelFont
;
133 // To match the size of a level 2 Heading/KTitleWidget
134 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
135 m_placeholderLabel
->setFont(placeholderLabelFont
);
136 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
137 m_placeholderLabel
->setWordWrap(true);
138 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
139 // Match opacity of QML placeholder label component
140 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
141 effect
->setOpacity(0.5);
142 m_placeholderLabel
->setGraphicsEffect(effect
);
143 // Set initial text and visibility
144 updatePlaceholderLabel();
146 auto *centeringLayout
= new QVBoxLayout(m_container
);
147 centeringLayout
->addWidget(m_placeholderLabel
);
148 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
150 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
151 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
152 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
153 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
154 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
155 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
156 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
157 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
158 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
159 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
160 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
161 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
162 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
163 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
164 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
165 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
166 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
168 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
169 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
170 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
171 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
172 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
173 connect(m_model
, &KFileItemModel::itemsChanged
,
174 this, &DolphinView::slotItemsChanged
);
175 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
176 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
177 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
178 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
179 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
180 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
182 connect(this, &DolphinView::itemCountChanged
,
183 this, &DolphinView::updatePlaceholderLabel
);
185 m_view
->installEventFilter(this);
186 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
187 this, &DolphinView::slotSortOrderChangedByHeader
);
188 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
189 this, &DolphinView::slotSortRoleChangedByHeader
);
190 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
191 this, &DolphinView::slotVisibleRolesChangedByHeader
);
192 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
193 this, &DolphinView::slotRoleEditingCanceled
);
194 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
195 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
197 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
198 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
199 this, &DolphinView::slotSelectionChanged
);
202 m_toolTipManager
= new ToolTipManager(this);
203 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
206 m_versionControlObserver
= new VersionControlObserver(this);
207 m_versionControlObserver
->setView(this);
208 m_versionControlObserver
->setModel(m_model
);
209 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
210 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
211 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
213 m_twoClicksRenamingTimer
= new QTimer(this);
214 m_twoClicksRenamingTimer
->setSingleShot(true);
215 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
217 applyViewProperties();
218 m_topLayout
->addWidget(m_container
);
223 DolphinView::~DolphinView()
227 QUrl
DolphinView::url() const
232 void DolphinView::setActive(bool active
)
234 if (active
== m_active
) {
243 m_container
->setFocus();
245 Q_EMIT
writeStateChanged(m_isFolderWritable
);
249 bool DolphinView::isActive() const
254 void DolphinView::setMode(Mode mode
)
256 if (mode
!= m_mode
) {
257 ViewProperties
props(viewPropertiesUrl());
258 props
.setViewMode(mode
);
260 // We pass the new ViewProperties to applyViewProperties, rather than
261 // storing them on disk and letting applyViewProperties() read them
262 // from there, to prevent that changing the view mode fails if the
263 // .directory file is not writable (see bug 318534).
264 applyViewProperties(props
);
268 DolphinView::Mode
DolphinView::mode() const
273 void DolphinView::setPreviewsShown(bool show
)
275 if (previewsShown() == show
) {
279 ViewProperties
props(viewPropertiesUrl());
280 props
.setPreviewsShown(show
);
282 const int oldZoomLevel
= m_view
->zoomLevel();
283 m_view
->setPreviewsShown(show
);
284 Q_EMIT
previewsShownChanged(show
);
286 const int newZoomLevel
= m_view
->zoomLevel();
287 if (newZoomLevel
!= oldZoomLevel
) {
288 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
292 bool DolphinView::previewsShown() const
294 return m_view
->previewsShown();
297 void DolphinView::setHiddenFilesShown(bool show
)
299 if (m_model
->showHiddenFiles() == show
) {
303 const KFileItemList itemList
= selectedItems();
304 m_selectedUrls
.clear();
305 m_selectedUrls
= itemList
.urlList();
307 ViewProperties
props(viewPropertiesUrl());
308 props
.setHiddenFilesShown(show
);
310 m_model
->setShowHiddenFiles(show
);
311 Q_EMIT
hiddenFilesShownChanged(show
);
314 bool DolphinView::hiddenFilesShown() const
316 return m_model
->showHiddenFiles();
319 void DolphinView::setGroupedSorting(bool grouped
)
321 if (grouped
== groupedSorting()) {
325 ViewProperties
props(viewPropertiesUrl());
326 props
.setGroupedSorting(grouped
);
329 m_container
->controller()->model()->setGroupedSorting(grouped
);
331 Q_EMIT
groupedSortingChanged(grouped
);
334 bool DolphinView::groupedSorting() const
336 return m_model
->groupedSorting();
339 KFileItemList
DolphinView::items() const
342 const int itemCount
= m_model
->count();
343 list
.reserve(itemCount
);
345 for (int i
= 0; i
< itemCount
; ++i
) {
346 list
.append(m_model
->fileItem(i
));
352 int DolphinView::itemsCount() const
354 return m_model
->count();
357 KFileItemList
DolphinView::selectedItems() const
359 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
361 KFileItemList selectedItems
;
362 const auto items
= selectionManager
->selectedItems();
363 selectedItems
.reserve(items
.count());
364 for (int index
: items
) {
365 selectedItems
.append(m_model
->fileItem(index
));
367 return selectedItems
;
370 int DolphinView::selectedItemsCount() const
372 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
373 return selectionManager
->selectedItems().count();
376 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
378 m_selectedUrls
= urls
;
381 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
383 m_currentItemUrl
= url
;
384 m_scrollToCurrentItem
= true;
387 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
389 const KItemListSelectionManager::SelectionMode mode
= enabled
390 ? KItemListSelectionManager::Select
391 : KItemListSelectionManager::Deselect
;
392 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
394 for (int index
= 0; index
< m_model
->count(); index
++) {
395 const KFileItem item
= m_model
->fileItem(index
);
396 if (regexp
.match(item
.text()).hasMatch()) {
397 // An alternative approach would be to store the matching items in a KItemSet and
398 // select them in one go after the loop, but we'd need a new function
399 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
401 selectionManager
->setSelected(index
, 1, mode
);
406 void DolphinView::setZoomLevel(int level
)
408 const int oldZoomLevel
= zoomLevel();
409 m_view
->setZoomLevel(level
);
410 if (zoomLevel() != oldZoomLevel
) {
412 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
416 int DolphinView::zoomLevel() const
418 return m_view
->zoomLevel();
421 void DolphinView::setSortRole(const QByteArray
& role
)
423 if (role
!= sortRole()) {
424 updateSortRole(role
);
428 QByteArray
DolphinView::sortRole() const
430 const KItemModelBase
* model
= m_container
->controller()->model();
431 return model
->sortRole();
434 void DolphinView::setSortOrder(Qt::SortOrder order
)
436 if (sortOrder() != order
) {
437 updateSortOrder(order
);
441 Qt::SortOrder
DolphinView::sortOrder() const
443 return m_model
->sortOrder();
446 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
448 if (sortFoldersFirst() != foldersFirst
) {
449 updateSortFoldersFirst(foldersFirst
);
453 bool DolphinView::sortFoldersFirst() const
455 return m_model
->sortDirectoriesFirst();
458 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
460 const QList
<QByteArray
> previousRoles
= roles
;
462 ViewProperties
props(viewPropertiesUrl());
463 props
.setVisibleRoles(roles
);
465 m_visibleRoles
= roles
;
466 m_view
->setVisibleRoles(roles
);
468 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
471 QList
<QByteArray
> DolphinView::visibleRoles() const
473 return m_visibleRoles
;
476 void DolphinView::reload()
478 QByteArray viewState
;
479 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
480 saveState(saveStream
);
483 loadDirectory(url(), true);
485 QDataStream
restoreStream(viewState
);
486 restoreState(restoreStream
);
489 void DolphinView::readSettings()
491 const int oldZoomLevel
= m_view
->zoomLevel();
493 GeneralSettings::self()->load();
494 m_view
->readSettings();
495 applyViewProperties();
497 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
498 m_container
->controller()->setAutoActivationDelay(delay
);
500 const int newZoomLevel
= m_view
->zoomLevel();
501 if (newZoomLevel
!= oldZoomLevel
) {
502 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
506 void DolphinView::writeSettings()
508 GeneralSettings::self()->save();
509 m_view
->writeSettings();
512 void DolphinView::setNameFilter(const QString
& nameFilter
)
514 m_model
->setNameFilter(nameFilter
);
517 QString
DolphinView::nameFilter() const
519 return m_model
->nameFilter();
522 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
524 return m_model
->setMimeTypeFilters(filters
);
527 QStringList
DolphinView::mimeTypeFilters() const
529 return m_model
->mimeTypeFilters();
532 void DolphinView::requestStatusBarText()
534 if (m_statJobForStatusBarText
) {
535 // Kill the pending request.
536 m_statJobForStatusBarText
->kill();
539 if (m_container
->controller()->selectionManager()->hasSelection()) {
542 KIO::filesize_t totalFileSize
= 0;
544 // Give a summary of the status of the selected files
545 const KFileItemList list
= selectedItems();
546 for (const KFileItem
& item
: list
) {
551 totalFileSize
+= item
.size();
555 if (folderCount
+ fileCount
== 1) {
556 // If only one item is selected, show info about it
557 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
559 // At least 2 items are selected
560 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
562 } else { // has no selection
563 if (!m_model
->rootItem().url().isValid()) {
567 m_statJobForStatusBarText
= KIO::statDetails(m_model
->rootItem().url(),
568 KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
569 connect(m_statJobForStatusBarText
, &KJob::result
,
570 this, &DolphinView::slotStatJobResult
);
571 m_statJobForStatusBarText
->start();
575 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
,
576 KIO::filesize_t totalFileSize
, const Selection selection
)
582 if (selection
== HasSelection
) {
583 // At least 2 items are selected because the case of 1 selected item is handled in
584 // DolphinView::requestStatusBarText().
585 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
586 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
588 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
589 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
592 if (fileCount
> 0 && folderCount
> 0) {
593 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
594 foldersText
, filesText
,
595 KFormat().formatByteSize(totalFileSize
));
596 } else if (fileCount
> 0) {
597 summary
= i18nc("@info:status files (size)", "%1 (%2)",
599 KFormat().formatByteSize(totalFileSize
));
600 } else if (folderCount
> 0) {
601 summary
= foldersText
;
603 summary
= i18nc("@info:status", "0 Folders, 0 Files");
605 Q_EMIT
statusBarTextChanged(summary
);
608 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
610 QList
<QAction
*> actions
;
612 if (items
.isEmpty()) {
613 const KFileItem item
= m_model
->rootItem();
614 if (!item
.isNull()) {
615 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
618 actions
= m_versionControlObserver
->actions(items
);
624 void DolphinView::setUrl(const QUrl
& url
)
636 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
637 this, &DolphinView::slotRoleEditingFinished
);
639 // It is important to clear the items from the model before
640 // applying the view properties, otherwise expensive operations
641 // might be done on the existing items although they get cleared
642 // anyhow afterwards by loadDirectory().
644 applyViewProperties();
647 Q_EMIT
urlChanged(url
);
650 void DolphinView::selectAll()
652 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
653 selectionManager
->setSelected(0, m_model
->count());
656 void DolphinView::invertSelection()
658 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
659 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
662 void DolphinView::clearSelection()
664 m_selectedUrls
.clear();
665 m_container
->controller()->selectionManager()->clearSelection();
668 void DolphinView::renameSelectedItems()
670 const KFileItemList items
= selectedItems();
671 if (items
.isEmpty()) {
675 if (items
.count() == 1 && GeneralSettings::renameInline()) {
676 const int index
= m_model
->index(items
.first());
677 m_view
->editRole(index
, "text");
681 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
682 this, &DolphinView::slotRoleEditingFinished
);
684 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
685 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
686 this, &DolphinView::slotRenameDialogRenamingFinished
);
691 // Assure that the current index remains visible when KFileItemModel
692 // will notify the view about changed items (which might result in
693 // a changed sorting).
694 m_assureVisibleCurrentIndex
= true;
697 void DolphinView::trashSelectedItems()
699 const QList
<QUrl
> list
= simplifiedSelectedUrls();
700 KIO::JobUiDelegate uiDelegate
;
701 uiDelegate
.setWindow(window());
702 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
703 KIO::Job
* job
= KIO::trash(list
);
704 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
705 KJobWidgets::setWindow(job
, this);
706 connect(job
, &KIO::Job::result
,
707 this, &DolphinView::slotTrashFileFinished
);
711 void DolphinView::deleteSelectedItems()
713 const QList
<QUrl
> list
= simplifiedSelectedUrls();
715 KIO::JobUiDelegate uiDelegate
;
716 uiDelegate
.setWindow(window());
717 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
718 KIO::Job
* job
= KIO::del(list
);
719 KJobWidgets::setWindow(job
, this);
720 connect(job
, &KIO::Job::result
,
721 this, &DolphinView::slotDeleteFileFinished
);
725 void DolphinView::cutSelectedItemsToClipboard()
727 QMimeData
* mimeData
= selectionMimeData();
728 KIO::setClipboardDataCut(mimeData
, true);
729 QApplication::clipboard()->setMimeData(mimeData
);
732 void DolphinView::copySelectedItemsToClipboard()
734 QMimeData
* mimeData
= selectionMimeData();
735 QApplication::clipboard()->setMimeData(mimeData
);
738 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
740 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
741 KJobWidgets::setWindow(job
, this);
743 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
744 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
745 KIO::FileUndoManager::self()->recordCopyJob(job
);
748 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
750 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
751 KJobWidgets::setWindow(job
, this);
753 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
754 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
755 KIO::FileUndoManager::self()->recordCopyJob(job
);
759 void DolphinView::paste()
764 void DolphinView::pasteIntoFolder()
766 const KFileItemList items
= selectedItems();
767 if ((items
.count() == 1) && items
.first().isDir()) {
768 pasteToUrl(items
.first().url());
772 void DolphinView::duplicateSelectedItems()
774 const KFileItemList itemList
= selectedItems();
775 if (itemList
.isEmpty()) {
779 const QMimeDatabase db
;
781 // Duplicate all selected items and append "copy" to the end of the file name
782 // but before the filename extension, if present
783 QList
<QUrl
> newSelection
;
784 for (const auto &item
: itemList
) {
785 const QUrl originalURL
= item
.url();
786 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
787 const QString originalFileName
= item
.name();
789 QString extension
= db
.suffixForFileName(originalFileName
);
791 QUrl duplicateURL
= originalURL
;
793 // No extension; new filename is "<oldfilename> copy"
794 if (extension
.isEmpty()) {
795 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
796 // There's an extension; new filename is "<oldfilename> copy.<extension>"
798 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
799 extension
= QLatin1String(".") + extension
;
800 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
801 // Preserve file's original filename extension in case the casing differs
802 // from what QMimeDatabase::suffixForFileName() returned
803 const QString originalExtension
= originalFileName
.right(extension
.size());
804 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
807 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
808 KJobWidgets::setWindow(job
, this);
811 newSelection
<< duplicateURL
;
812 KIO::FileUndoManager::self()->recordCopyJob(job
);
816 forceUrlsSelection(newSelection
.first(), newSelection
);
819 void DolphinView::stopLoading()
821 m_model
->cancelDirectoryLoading();
824 void DolphinView::updatePalette()
826 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
831 QWidget
* viewport
= m_container
->viewport();
834 palette
.setColor(viewport
->backgroundRole(), color
);
835 viewport
->setPalette(palette
);
841 void DolphinView::abortTwoClicksRenaming()
843 m_twoClicksRenamingItemUrl
.clear();
844 m_twoClicksRenamingTimer
->stop();
847 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
849 switch (event
->type()) {
850 case QEvent::PaletteChange
:
852 QPixmapCache::clear();
855 case QEvent::WindowActivate
:
856 case QEvent::WindowDeactivate
:
860 case QEvent::KeyPress
:
861 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
862 if (GeneralSettings::useTabForSwitchingSplitView()) {
863 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
864 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
865 Q_EMIT
toggleActiveViewRequested();
870 case QEvent::FocusIn
:
871 if (watched
== m_container
) {
876 case QEvent::GraphicsSceneDragEnter
:
877 if (watched
== m_view
) {
879 abortTwoClicksRenaming();
883 case QEvent::GraphicsSceneDragLeave
:
884 if (watched
== m_view
) {
889 case QEvent::GraphicsSceneDrop
:
890 if (watched
== m_view
) {
897 return QWidget::eventFilter(watched
, event
);
900 void DolphinView::wheelEvent(QWheelEvent
* event
)
902 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
903 const QPoint numDegrees
= event
->angleDelta() / 8;
904 const QPoint numSteps
= numDegrees
/ 15;
906 setZoomLevel(zoomLevel() + numSteps
.y());
913 void DolphinView::hideEvent(QHideEvent
* event
)
916 QWidget::hideEvent(event
);
919 bool DolphinView::event(QEvent
* event
)
921 if (event
->type() == QEvent::WindowDeactivate
) {
923 * Dolphin leaves file preview tooltips open even when is not visible.
925 * Hide tool-tip when Dolphin loses focus.
928 abortTwoClicksRenaming();
931 return QWidget::event(event
);
934 void DolphinView::activate()
939 void DolphinView::slotItemActivated(int index
)
941 abortTwoClicksRenaming();
943 const KFileItem item
= m_model
->fileItem(index
);
944 if (!item
.isNull()) {
945 Q_EMIT
itemActivated(item
);
949 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
951 Q_ASSERT(indexes
.count() >= 2);
953 abortTwoClicksRenaming();
955 if (indexes
.count() > 5) {
956 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
957 const int answer
= KMessageBox::warningYesNo(this, question
);
958 if (answer
!= KMessageBox::Yes
) {
964 items
.reserve(indexes
.count());
966 for (int index
: indexes
) {
967 KFileItem item
= m_model
->fileItem(index
);
968 const QUrl
& url
= openItemAsFolderUrl(item
);
970 if (!url
.isEmpty()) { // Open folders in new tabs
971 Q_EMIT
tabRequested(url
);
977 if (items
.count() == 1) {
978 Q_EMIT
itemActivated(items
.first());
979 } else if (items
.count() > 1) {
980 Q_EMIT
itemsActivated(items
);
984 void DolphinView::slotItemMiddleClicked(int index
)
986 const KFileItem
& item
= m_model
->fileItem(index
);
987 const QUrl
& url
= openItemAsFolderUrl(item
);
988 if (!url
.isEmpty()) {
989 Q_EMIT
tabRequested(url
);
990 } else if (isTabsForFilesEnabled()) {
991 Q_EMIT
tabRequested(item
.url());
995 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
997 // Force emit of a selection changed signal before we request the
998 // context menu, to update the edit-actions first. (See Bug 294013)
999 if (m_selectionChangedTimer
->isActive()) {
1000 emitSelectionChangedSignal();
1003 const KFileItem item
= m_model
->fileItem(index
);
1004 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
1007 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
1009 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
1012 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
1014 ViewProperties
props(viewPropertiesUrl());
1016 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
1018 KItemListView
* view
= m_container
->controller()->view();
1019 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1021 bool indexingEnabled
= false;
1023 Baloo::IndexerConfig config
;
1024 indexingEnabled
= config
.fileIndexingEnabled();
1028 QMenu
* groupMenu
= nullptr;
1030 // Add all roles to the menu that can be shown or hidden by the user
1031 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1032 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1033 if (info
.role
== "text") {
1034 // It should not be possible to hide the "text" role
1038 const QString text
= m_model
->roleDescription(info
.role
);
1039 QAction
* action
= nullptr;
1040 if (info
.group
.isEmpty()) {
1041 action
= menu
->addAction(text
);
1043 if (!groupMenu
|| info
.group
!= groupName
) {
1044 groupName
= info
.group
;
1045 groupMenu
= menu
->addMenu(groupName
);
1048 action
= groupMenu
->addAction(text
);
1051 action
->setCheckable(true);
1052 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1053 action
->setData(info
.role
);
1055 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1056 (info
.requiresBaloo
) ||
1057 (info
.requiresIndexer
&& indexingEnabled
);
1058 action
->setEnabled(enable
);
1061 menu
->addSeparator();
1063 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1064 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1066 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1067 autoAdjustWidthsAction
->setCheckable(true);
1068 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1069 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1071 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1072 customWidthsAction
->setCheckable(true);
1073 customWidthsAction
->setChecked(!autoColumnWidths
);
1074 customWidthsAction
->setActionGroup(widthsGroup
);
1076 QAction
* action
= menu
->exec(pos
.toPoint());
1077 if (menu
&& action
) {
1078 KItemListHeader
* header
= view
->header();
1080 if (action
== autoAdjustWidthsAction
) {
1081 // Clear the column-widths from the viewproperties and turn on
1082 // the automatic resizing of the columns
1083 props
.setHeaderColumnWidths(QList
<int>());
1084 header
->setAutomaticColumnResizing(true);
1085 } else if (action
== customWidthsAction
) {
1086 // Apply the current column-widths as custom column-widths and turn
1087 // off the automatic resizing of the columns
1088 QList
<int> columnWidths
;
1089 const auto visibleRoles
= view
->visibleRoles();
1090 columnWidths
.reserve(visibleRoles
.count());
1091 for (const QByteArray
& role
: visibleRoles
) {
1092 columnWidths
.append(header
->columnWidth(role
));
1094 props
.setHeaderColumnWidths(columnWidths
);
1095 header
->setAutomaticColumnResizing(false);
1097 // Show or hide the selected role
1098 const QByteArray selectedRole
= action
->data().toByteArray();
1100 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1101 if (action
->isChecked()) {
1102 visibleRoles
.append(selectedRole
);
1104 visibleRoles
.removeOne(selectedRole
);
1107 view
->setVisibleRoles(visibleRoles
);
1108 props
.setVisibleRoles(visibleRoles
);
1110 QList
<int> columnWidths
;
1111 if (!header
->automaticColumnResizing()) {
1112 const auto visibleRoles
= view
->visibleRoles();
1113 columnWidths
.reserve(visibleRoles
.count());
1114 for (const QByteArray
& role
: visibleRoles
) {
1115 columnWidths
.append(header
->columnWidth(role
));
1118 props
.setHeaderColumnWidths(columnWidths
);
1125 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1127 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1129 ViewProperties
props(viewPropertiesUrl());
1130 QList
<int> columnWidths
= props
.headerColumnWidths();
1131 if (columnWidths
.count() != visibleRoles
.count()) {
1132 columnWidths
.clear();
1133 columnWidths
.reserve(visibleRoles
.count());
1134 const KItemListHeader
* header
= m_view
->header();
1135 for (const QByteArray
& role
: visibleRoles
) {
1136 const int width
= header
->columnWidth(role
);
1137 columnWidths
.append(width
);
1141 const int roleIndex
= visibleRoles
.indexOf(role
);
1142 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1143 columnWidths
[roleIndex
] = current
;
1145 props
.setHeaderColumnWidths(columnWidths
);
1148 void DolphinView::slotItemHovered(int index
)
1150 const KFileItem item
= m_model
->fileItem(index
);
1152 if (GeneralSettings::showToolTips() && !m_dragging
) {
1153 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1154 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1155 itemRect
.moveTo(pos
);
1158 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1162 Q_EMIT
requestItemInfo(item
);
1165 void DolphinView::slotItemUnhovered(int index
)
1169 Q_EMIT
requestItemInfo(KFileItem());
1172 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1175 KFileItem destItem
= m_model
->fileItem(index
);
1176 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1177 // Use the URL of the view as drop target if the item is no directory
1179 destItem
= m_model
->rootItem();
1182 // The item represents a directory or desktop-file
1183 destUrl
= destItem
.mostLocalUrl();
1186 QDropEvent
dropEvent(event
->pos().toPoint(),
1187 event
->possibleActions(),
1190 event
->modifiers());
1191 dropUrls(destUrl
, &dropEvent
, this);
1196 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1198 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1201 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1203 if (destUrl
== url()) {
1204 // Mark the dropped urls as selected.
1205 m_clearSelectionBeforeSelectingNewItems
= true;
1206 m_markFirstNewlySelectedItemAsCurrent
= true;
1207 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1212 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1214 if (previous
!= nullptr) {
1215 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1216 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1217 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1218 m_versionControlObserver
->setModel(nullptr);
1222 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1223 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1224 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1225 m_versionControlObserver
->setModel(fileItemModel
);
1229 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1235 if (buttons
& Qt::BackButton
) {
1236 Q_EMIT
goBackRequested();
1237 } else if (buttons
& Qt::ForwardButton
) {
1238 Q_EMIT
goForwardRequested();
1242 void DolphinView::slotSelectedItemTextPressed(int index
)
1244 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1245 const KFileItem item
= m_model
->fileItem(index
);
1246 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1247 if (capabilities
.supportsMoving()) {
1248 m_twoClicksRenamingItemUrl
= item
.url();
1249 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1254 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1256 slotItemCreated(to
);
1259 void DolphinView::slotItemCreated(const QUrl
& url
)
1261 if (m_markFirstNewlySelectedItemAsCurrent
) {
1262 markUrlAsCurrent(url
);
1263 m_markFirstNewlySelectedItemAsCurrent
= false;
1265 m_selectedUrls
<< url
;
1268 void DolphinView::slotJobResult(KJob
*job
)
1271 Q_EMIT
errorMessage(job
->errorString());
1273 if (!m_selectedUrls
.isEmpty()) {
1274 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1278 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1280 const int currentCount
= current
.count();
1281 const int previousCount
= previous
.count();
1282 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1283 (currentCount
> 0 && previousCount
== 0);
1285 // If nothing has been selected before and something got selected (or if something
1286 // was selected before and now nothing is selected) the selectionChangedSignal must
1287 // be emitted asynchronously as fast as possible to update the edit-actions.
1288 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1289 m_selectionChangedTimer
->start();
1292 void DolphinView::emitSelectionChangedSignal()
1294 m_selectionChangedTimer
->stop();
1295 Q_EMIT
selectionChanged(selectedItems());
1298 void DolphinView::slotStatJobResult(KJob
*job
)
1300 int folderCount
= 0;
1302 KIO::filesize_t totalFileSize
= 0;
1303 bool countFileSize
= true;
1305 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1306 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1307 // We have a precomputed value.
1308 totalFileSize
= static_cast<KIO::filesize_t
>(
1309 entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1310 countFileSize
= false;
1313 const int itemCount
= m_model
->count();
1314 for (int i
= 0; i
< itemCount
; ++i
) {
1315 const KFileItem item
= m_model
->fileItem(i
);
1320 if (countFileSize
) {
1321 totalFileSize
+= item
.size();
1325 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1328 void DolphinView::updateSortRole(const QByteArray
& role
)
1330 ViewProperties
props(viewPropertiesUrl());
1331 props
.setSortRole(role
);
1333 KItemModelBase
* model
= m_container
->controller()->model();
1334 model
->setSortRole(role
);
1336 Q_EMIT
sortRoleChanged(role
);
1339 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1341 ViewProperties
props(viewPropertiesUrl());
1342 props
.setSortOrder(order
);
1344 m_model
->setSortOrder(order
);
1346 Q_EMIT
sortOrderChanged(order
);
1349 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1351 ViewProperties
props(viewPropertiesUrl());
1352 props
.setSortFoldersFirst(foldersFirst
);
1354 m_model
->setSortDirectoriesFirst(foldersFirst
);
1356 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1359 QPair
<bool, QString
> DolphinView::pasteInfo() const
1361 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1362 QPair
<bool, QString
> info
;
1363 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1367 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1369 m_tabsForFiles
= tabsForFiles
;
1372 bool DolphinView::isTabsForFilesEnabled() const
1374 return m_tabsForFiles
;
1377 bool DolphinView::itemsExpandable() const
1379 return m_mode
== DetailsView
;
1382 void DolphinView::restoreState(QDataStream
& stream
)
1384 // Read the version number of the view state and check if the version is supported.
1385 quint32 version
= 0;
1388 // The version of the view state isn't supported, we can't restore it.
1392 // Restore the current item that had the keyboard focus
1393 stream
>> m_currentItemUrl
;
1395 // Restore the previously selected items
1396 stream
>> m_selectedUrls
;
1398 // Restore the view position
1399 stream
>> m_restoredContentsPosition
;
1401 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1404 m_model
->restoreExpandedDirectories(urls
);
1407 void DolphinView::saveState(QDataStream
& stream
)
1409 stream
<< quint32(1); // View state version
1411 // Save the current item that has the keyboard focus
1412 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1413 if (currentIndex
!= -1) {
1414 KFileItem item
= m_model
->fileItem(currentIndex
);
1415 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1416 QUrl currentItemUrl
= item
.url();
1417 stream
<< currentItemUrl
;
1422 // Save the selected urls
1423 stream
<< selectedItems().urlList();
1425 // Save view position
1426 const qreal x
= m_container
->horizontalScrollBar()->value();
1427 const qreal y
= m_container
->verticalScrollBar()->value();
1428 stream
<< QPoint(x
, y
);
1430 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1431 stream
<< m_model
->expandedDirectories();
1434 KFileItem
DolphinView::rootItem() const
1436 return m_model
->rootItem();
1439 void DolphinView::setViewPropertiesContext(const QString
& context
)
1441 m_viewPropertiesContext
= context
;
1444 QString
DolphinView::viewPropertiesContext() const
1446 return m_viewPropertiesContext
;
1449 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1451 if (item
.isNull()) {
1455 QUrl url
= item
.targetUrl();
1461 if (item
.isMimeTypeKnown()) {
1462 const QString
& mimetype
= item
.mimetype();
1464 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1465 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1466 // zip:/<path>/ when clicking on a zip file, etc.
1467 // The .protocol file specifies the mimetype that the kioslave handles.
1468 // Note that we don't use mimetype inheritance since we don't want to
1469 // open OpenDocument files as zip folders...
1470 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1471 if (!protocol
.isEmpty()) {
1472 url
.setScheme(protocol
);
1477 if (mimetype
== QLatin1String("application/x-desktop")) {
1478 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1479 KDesktopFile
desktopFile(url
.toLocalFile());
1480 if (desktopFile
.hasLinkType()) {
1481 const QString linkUrl
= desktopFile
.readUrl();
1482 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1483 return QUrl::fromUserInput(linkUrl
);
1492 void DolphinView::resetZoomLevel()
1494 ViewModeSettings::ViewMode mode
;
1497 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1498 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1499 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1501 const ViewModeSettings
settings(mode
);
1502 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1503 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1506 void DolphinView::observeCreatedItem(const QUrl
& url
)
1509 forceUrlsSelection(url
, {url
});
1513 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1515 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1516 Q_EMIT
redirection(oldUrl
, newUrl
);
1517 m_url
= newUrl
; // #186947
1521 void DolphinView::updateViewState()
1523 if (m_currentItemUrl
!= QUrl()) {
1524 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1526 // if there is a selection already, leave it that way
1527 if (!selectionManager
->hasSelection()) {
1528 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1529 if (currentIndex
!= -1) {
1530 selectionManager
->setCurrentItem(currentIndex
);
1532 // scroll to current item and reset the state
1533 if (m_scrollToCurrentItem
) {
1534 m_view
->scrollToItem(currentIndex
);
1535 m_scrollToCurrentItem
= false;
1538 selectionManager
->setCurrentItem(0);
1542 m_currentItemUrl
= QUrl();
1545 if (!m_restoredContentsPosition
.isNull()) {
1546 const int x
= m_restoredContentsPosition
.x();
1547 const int y
= m_restoredContentsPosition
.y();
1548 m_restoredContentsPosition
= QPoint();
1550 m_container
->horizontalScrollBar()->setValue(x
);
1551 m_container
->verticalScrollBar()->setValue(y
);
1554 if (!m_selectedUrls
.isEmpty()) {
1555 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1557 // if there is a selection already, leave it that way
1558 if (!selectionManager
->hasSelection()) {
1559 if (m_clearSelectionBeforeSelectingNewItems
) {
1560 selectionManager
->clearSelection();
1561 m_clearSelectionBeforeSelectingNewItems
= false;
1564 KItemSet selectedItems
= selectionManager
->selectedItems();
1566 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1567 while (it
!= m_selectedUrls
.end()) {
1568 const int index
= m_model
->index(*it
);
1570 selectedItems
.insert(index
);
1571 it
= m_selectedUrls
.erase(it
);
1577 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1578 selectionManager
->setSelectedItems(selectedItems
);
1583 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1586 if (GeneralSettings::showToolTips()) {
1587 m_toolTipManager
->hideToolTip(behavior
);
1594 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1596 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1598 // verify that only one item is selected
1599 if (selectionManager
->selectedItems().count() == 1) {
1600 const int index
= selectionManager
->currentItem();
1601 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1603 // check if the selected item was the same item that started the twoClicksRenaming
1604 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1605 renameSelectedItems();
1610 void DolphinView::slotTrashFileFinished(KJob
* job
)
1612 if (job
->error() == 0) {
1613 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1614 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1615 Q_EMIT
errorMessage(job
->errorString());
1619 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1621 if (job
->error() == 0) {
1622 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1623 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1624 Q_EMIT
errorMessage(job
->errorString());
1628 void DolphinView::slotRenamingResult(KJob
* job
)
1631 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1633 const QUrl newUrl
= copyJob
->destUrl();
1634 const int index
= m_model
->index(newUrl
);
1636 QHash
<QByteArray
, QVariant
> data
;
1637 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1638 data
.insert("text", oldUrl
.fileName());
1639 m_model
->setData(index
, data
);
1644 void DolphinView::slotDirectoryLoadingStarted()
1647 updatePlaceholderLabel();
1649 // Disable the writestate temporary until it can be determined in a fast way
1650 // in DolphinView::slotDirectoryLoadingCompleted()
1651 if (m_isFolderWritable
) {
1652 m_isFolderWritable
= false;
1653 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1656 Q_EMIT
directoryLoadingStarted();
1659 void DolphinView::slotDirectoryLoadingCompleted()
1663 // Update the view-state. This has to be done asynchronously
1664 // because the view might not be in its final state yet.
1665 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1667 // Update the placeholder label in case we found that the folder was empty
1670 Q_EMIT
directoryLoadingCompleted();
1672 updatePlaceholderLabel();
1673 updateWritableState();
1676 void DolphinView::slotDirectoryLoadingCanceled()
1680 updatePlaceholderLabel();
1682 Q_EMIT
directoryLoadingCanceled();
1685 void DolphinView::slotItemsChanged()
1687 m_assureVisibleCurrentIndex
= false;
1690 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1693 Q_ASSERT(m_model
->sortOrder() == current
);
1695 ViewProperties
props(viewPropertiesUrl());
1696 props
.setSortOrder(current
);
1698 Q_EMIT
sortOrderChanged(current
);
1701 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1704 Q_ASSERT(m_model
->sortRole() == current
);
1706 ViewProperties
props(viewPropertiesUrl());
1707 props
.setSortRole(current
);
1709 Q_EMIT
sortRoleChanged(current
);
1712 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1713 const QList
<QByteArray
>& previous
)
1716 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1718 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1720 m_visibleRoles
= current
;
1722 ViewProperties
props(viewPropertiesUrl());
1723 props
.setVisibleRoles(m_visibleRoles
);
1725 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1728 void DolphinView::slotRoleEditingCanceled()
1730 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1731 this, &DolphinView::slotRoleEditingFinished
);
1734 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1736 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1737 this, &DolphinView::slotRoleEditingFinished
);
1739 if (index
< 0 || index
>= m_model
->count()) {
1743 if (role
== "text") {
1744 const KFileItem oldItem
= m_model
->fileItem(index
);
1745 const QString newName
= value
.toString();
1746 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1747 const QUrl oldUrl
= oldItem
.url();
1749 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1750 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1753 //Confirm hiding file/directory by renaming inline
1754 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1755 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1756 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1758 const auto code
= KMessageBox::questionYesNo(this,
1759 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1760 "Do you still want to rename it?")
1761 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1762 "Do you still want to rename it?"),
1763 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1765 KStandardGuiItem::cancel(),
1766 QStringLiteral("ConfirmHide")
1769 if (code
== KMessageBox::No
) {
1775 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1776 if (!newNameExistsAlready
) {
1777 // Only change the data in the model if no item with the new name
1778 // is in the model yet. If there is an item with the new name
1779 // already, calling KIO::CopyJob will open a dialog
1780 // asking for a new name, and KFileItemModel will update the
1781 // data when the dir lister signals that the file name has changed.
1782 QHash
<QByteArray
, QVariant
> data
;
1783 data
.insert(role
, value
);
1784 m_model
->setData(index
, data
);
1787 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1788 KJobWidgets::setWindow(job
, this);
1789 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1790 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1792 forceUrlsSelection(newUrl
, {newUrl
});
1794 if (!newNameExistsAlready
) {
1795 // Only connect the result signal if there is no item with the new name
1796 // in the model yet, see bug 328262.
1797 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1803 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1805 if (!url
.isValid()) {
1806 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1807 if (location
.isEmpty()) {
1808 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1810 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1816 m_model
->refreshDirectory(url
);
1818 m_model
->loadDirectory(url
);
1822 void DolphinView::applyViewProperties()
1824 const ViewProperties
props(viewPropertiesUrl());
1825 applyViewProperties(props
);
1828 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1830 m_view
->beginTransaction();
1832 const Mode mode
= props
.viewMode();
1833 if (m_mode
!= mode
) {
1834 const Mode previousMode
= m_mode
;
1837 // Changing the mode might result in changing
1838 // the zoom level. Remember the old zoom level so
1839 // that zoomLevelChanged() can get emitted.
1840 const int oldZoomLevel
= m_view
->zoomLevel();
1843 Q_EMIT
modeChanged(m_mode
, previousMode
);
1845 if (m_view
->zoomLevel() != oldZoomLevel
) {
1846 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1850 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1851 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1852 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1853 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1856 const bool groupedSorting
= props
.groupedSorting();
1857 if (groupedSorting
!= m_model
->groupedSorting()) {
1858 m_model
->setGroupedSorting(groupedSorting
);
1859 Q_EMIT
groupedSortingChanged(groupedSorting
);
1862 const QByteArray sortRole
= props
.sortRole();
1863 if (sortRole
!= m_model
->sortRole()) {
1864 m_model
->setSortRole(sortRole
);
1865 Q_EMIT
sortRoleChanged(sortRole
);
1868 const Qt::SortOrder sortOrder
= props
.sortOrder();
1869 if (sortOrder
!= m_model
->sortOrder()) {
1870 m_model
->setSortOrder(sortOrder
);
1871 Q_EMIT
sortOrderChanged(sortOrder
);
1874 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1875 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1876 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1877 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1880 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1881 if (visibleRoles
!= m_visibleRoles
) {
1882 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1883 m_visibleRoles
= visibleRoles
;
1884 m_view
->setVisibleRoles(visibleRoles
);
1885 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1888 const bool previewsShown
= props
.previewsShown();
1889 if (previewsShown
!= m_view
->previewsShown()) {
1890 const int oldZoomLevel
= zoomLevel();
1892 m_view
->setPreviewsShown(previewsShown
);
1893 Q_EMIT
previewsShownChanged(previewsShown
);
1895 // Changing the preview-state might result in a changed zoom-level
1896 if (oldZoomLevel
!= zoomLevel()) {
1897 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1901 KItemListView
* itemListView
= m_container
->controller()->view();
1902 if (itemListView
->isHeaderVisible()) {
1903 KItemListHeader
* header
= itemListView
->header();
1904 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1905 const int rolesCount
= m_visibleRoles
.count();
1906 if (headerColumnWidths
.count() == rolesCount
) {
1907 header
->setAutomaticColumnResizing(false);
1909 QHash
<QByteArray
, qreal
> columnWidths
;
1910 for (int i
= 0; i
< rolesCount
; ++i
) {
1911 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1913 header
->setColumnWidths(columnWidths
);
1915 header
->setAutomaticColumnResizing(true);
1919 m_view
->endTransaction();
1922 void DolphinView::applyModeToView()
1925 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1926 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1927 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1928 default: Q_ASSERT(false); break;
1932 void DolphinView::pasteToUrl(const QUrl
& url
)
1934 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1935 KJobWidgets::setWindow(job
, this);
1936 m_clearSelectionBeforeSelectingNewItems
= true;
1937 m_markFirstNewlySelectedItemAsCurrent
= true;
1938 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1939 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1942 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1946 const KFileItemList items
= selectedItems();
1947 urls
.reserve(items
.count());
1948 for (const KFileItem
& item
: items
) {
1949 urls
.append(item
.url());
1952 if (itemsExpandable()) {
1953 // TODO: Check if we still need KDirModel for this in KDE 5.0
1954 urls
= KDirModel::simplifiedUrlList(urls
);
1960 QMimeData
* DolphinView::selectionMimeData() const
1962 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1963 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1965 return m_model
->createMimeData(selectedIndexes
);
1968 void DolphinView::updateWritableState()
1970 const bool wasFolderWritable
= m_isFolderWritable
;
1971 m_isFolderWritable
= false;
1973 KFileItem item
= m_model
->rootItem();
1974 if (item
.isNull()) {
1975 // Try to find out if the URL is writable even if the "root item" is
1976 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1977 item
= KFileItem(url());
1978 item
.setDelayedMimeTypes(true);
1981 KFileItemListProperties
capabilities(KFileItemList() << item
);
1982 m_isFolderWritable
= capabilities
.supportsWriting();
1984 if (m_isFolderWritable
!= wasFolderWritable
) {
1985 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1989 QUrl
DolphinView::viewPropertiesUrl() const
1991 if (m_viewPropertiesContext
.isEmpty()) {
1996 url
.setScheme(m_url
.scheme());
1997 url
.setPath(m_viewPropertiesContext
);
2001 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
2003 forceUrlsSelection(urls
.first(), urls
);
2006 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
2009 m_clearSelectionBeforeSelectingNewItems
= true;
2010 markUrlAsCurrent(current
);
2011 markUrlsAsSelected(selected
);
2014 void DolphinView::copyPathToClipboard()
2016 const KFileItemList list
= selectedItems();
2017 if (list
.isEmpty()) {
2020 const KFileItem
& item
= list
.at(0);
2021 QString path
= item
.localPath();
2022 if (path
.isEmpty()) {
2023 path
= item
.url().toDisplayString();
2025 QClipboard
* clipboard
= QApplication::clipboard();
2026 if (clipboard
== nullptr) {
2029 clipboard
->setText(path
);
2032 void DolphinView::slotIncreaseZoom()
2034 setZoomLevel(zoomLevel() + 1);
2037 void DolphinView::slotDecreaseZoom()
2039 setZoomLevel(zoomLevel() - 1);
2042 void DolphinView::slotSwipeUp()
2044 Q_EMIT
goUpRequested();
2047 void DolphinView::updatePlaceholderLabel()
2049 if (m_loading
|| itemsCount() > 0) {
2050 m_placeholderLabel
->setVisible(false);
2054 if (!nameFilter().isEmpty()) {
2055 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2056 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2057 m_placeholderLabel
->setText(i18n("No items matching the search"));
2058 } else if (m_url
.scheme() == QLatin1String("trash")) {
2059 m_placeholderLabel
->setText(i18n("Trash is empty"));
2060 } else if (m_url
.scheme() == QLatin1String("tags")) {
2061 m_placeholderLabel
->setText(i18n("No tags"));
2062 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2063 m_placeholderLabel
->setText(i18n("No recently used items"));
2064 } else if (m_url
.scheme() == QLatin1String("smb")) {
2065 m_placeholderLabel
->setText(i18n("No shared folders found"));
2066 } else if (m_url
.scheme() == QLatin1String("network")) {
2067 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2068 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2069 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2070 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2071 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2073 m_placeholderLabel
->setText(i18n("Folder is empty"));
2076 m_placeholderLabel
->setVisible(true);