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 "kitemviews/private/kitemlistroleeditor.h"
22 #include "versioncontrol/versioncontrolobserver.h"
23 #include "viewproperties.h"
24 #include "views/tooltips/tooltipmanager.h"
25 #include "zoomlevelinfo.h"
28 #include <Baloo/IndexerConfig>
30 #include <KColorScheme>
31 #include <KDesktopFile>
33 #include <KFileItemListProperties>
35 #include <KIO/CopyJob>
36 #include <KIO/DeleteJob>
37 #include <KIO/DropJob>
38 #include <KIO/JobUiDelegate>
40 #include <KIO/PasteJob>
41 #include <KIO/PreviewJob>
42 #include <KIO/RenameFileDialog>
43 #include <KJobWidgets>
44 #include <KLocalizedString>
45 #include <KMessageBox>
46 #include <KProtocolManager>
48 #include <QAbstractItemView>
49 #include <QActionGroup>
50 #include <QApplication>
53 #include <QGraphicsOpacityEffect>
54 #include <QGraphicsSceneDragDropEvent>
57 #include <QMimeDatabase>
58 #include <QPixmapCache>
63 #include <QVBoxLayout>
65 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
68 m_tabsForFiles(false),
69 m_assureVisibleCurrentIndex(false),
70 m_isFolderWritable(true),
74 m_viewPropertiesContext(),
75 m_mode(DolphinView::IconsView
),
81 m_toolTipManager(nullptr),
82 m_selectionChangedTimer(nullptr),
84 m_scrollToCurrentItem(false),
85 m_restoredContentsPosition(),
87 m_clearSelectionBeforeSelectingNewItems(false),
88 m_markFirstNewlySelectedItemAsCurrent(false),
89 m_versionControlObserver(nullptr),
90 m_twoClicksRenamingTimer(nullptr),
91 m_placeholderLabel(nullptr)
93 m_topLayout
= new QVBoxLayout(this);
94 m_topLayout
->setSpacing(0);
95 m_topLayout
->setContentsMargins(0, 0, 0, 0);
97 // When a new item has been created by the "Create New..." menu, the item should
98 // get selected and it must be assured that the item will get visible. As the
99 // creation is done asynchronously, several signals must be checked:
100 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
101 this, &DolphinView::observeCreatedItem
);
103 m_selectionChangedTimer
= new QTimer(this);
104 m_selectionChangedTimer
->setSingleShot(true);
105 m_selectionChangedTimer
->setInterval(300);
106 connect(m_selectionChangedTimer
, &QTimer::timeout
,
107 this, &DolphinView::emitSelectionChangedSignal
);
109 m_model
= new KFileItemModel(this);
110 m_view
= new DolphinItemListView();
111 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
112 m_view
->setVisibleRoles({"text"});
115 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
116 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
117 controller
->setAutoActivationDelay(delay
);
119 // The EnlargeSmallPreviews setting can only be changed after the model
120 // has been set in the view by KItemListController.
121 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
123 m_container
= new KItemListContainer(controller
, this);
124 m_container
->installEventFilter(this);
125 setFocusProxy(m_container
);
126 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
127 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
129 // Show some placeholder text for empty folders
130 // This is made using a heavily-modified QLabel rather than a KTitleWidget
131 // because KTitleWidget can't be told to turn off mouse-selectable text
132 m_placeholderLabel
= new QLabel(this);
133 QFont placeholderLabelFont
;
134 // To match the size of a level 2 Heading/KTitleWidget
135 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
136 m_placeholderLabel
->setFont(placeholderLabelFont
);
137 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
138 m_placeholderLabel
->setWordWrap(true);
139 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
140 // Match opacity of QML placeholder label component
141 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
142 effect
->setOpacity(0.5);
143 m_placeholderLabel
->setGraphicsEffect(effect
);
144 // Set initial text and visibility
145 updatePlaceholderLabel();
147 auto *centeringLayout
= new QVBoxLayout(m_container
);
148 centeringLayout
->addWidget(m_placeholderLabel
);
149 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
151 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
152 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
153 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
154 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
155 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
156 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
157 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
158 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
159 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
160 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
161 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
162 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
163 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
164 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
165 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
166 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
167 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
169 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
170 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
171 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
172 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
173 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
174 connect(m_model
, &KFileItemModel::itemsChanged
,
175 this, &DolphinView::slotItemsChanged
);
176 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
177 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
178 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
179 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
180 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
181 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
183 connect(this, &DolphinView::itemCountChanged
,
184 this, &DolphinView::updatePlaceholderLabel
);
186 m_view
->installEventFilter(this);
187 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
188 this, &DolphinView::slotSortOrderChangedByHeader
);
189 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
190 this, &DolphinView::slotSortRoleChangedByHeader
);
191 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
192 this, &DolphinView::slotVisibleRolesChangedByHeader
);
193 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
194 this, &DolphinView::slotRoleEditingCanceled
);
195 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
196 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
198 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
199 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
200 this, &DolphinView::slotSelectionChanged
);
203 m_toolTipManager
= new ToolTipManager(this);
204 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
207 m_versionControlObserver
= new VersionControlObserver(this);
208 m_versionControlObserver
->setView(this);
209 m_versionControlObserver
->setModel(m_model
);
210 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
211 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
212 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
214 m_twoClicksRenamingTimer
= new QTimer(this);
215 m_twoClicksRenamingTimer
->setSingleShot(true);
216 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
218 applyViewProperties();
219 m_topLayout
->addWidget(m_container
);
224 DolphinView::~DolphinView()
228 QUrl
DolphinView::url() const
233 void DolphinView::setActive(bool active
)
235 if (active
== m_active
) {
244 m_container
->setFocus();
246 Q_EMIT
writeStateChanged(m_isFolderWritable
);
250 bool DolphinView::isActive() const
255 void DolphinView::setMode(Mode mode
)
257 if (mode
!= m_mode
) {
258 ViewProperties
props(viewPropertiesUrl());
259 props
.setViewMode(mode
);
261 // We pass the new ViewProperties to applyViewProperties, rather than
262 // storing them on disk and letting applyViewProperties() read them
263 // from there, to prevent that changing the view mode fails if the
264 // .directory file is not writable (see bug 318534).
265 applyViewProperties(props
);
269 DolphinView::Mode
DolphinView::mode() const
274 void DolphinView::setPreviewsShown(bool show
)
276 if (previewsShown() == show
) {
280 ViewProperties
props(viewPropertiesUrl());
281 props
.setPreviewsShown(show
);
283 const int oldZoomLevel
= m_view
->zoomLevel();
284 m_view
->setPreviewsShown(show
);
285 Q_EMIT
previewsShownChanged(show
);
287 const int newZoomLevel
= m_view
->zoomLevel();
288 if (newZoomLevel
!= oldZoomLevel
) {
289 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
293 bool DolphinView::previewsShown() const
295 return m_view
->previewsShown();
298 void DolphinView::setHiddenFilesShown(bool show
)
300 if (m_model
->showHiddenFiles() == show
) {
304 const KFileItemList itemList
= selectedItems();
305 m_selectedUrls
.clear();
306 m_selectedUrls
= itemList
.urlList();
308 ViewProperties
props(viewPropertiesUrl());
309 props
.setHiddenFilesShown(show
);
311 m_model
->setShowHiddenFiles(show
);
312 Q_EMIT
hiddenFilesShownChanged(show
);
315 bool DolphinView::hiddenFilesShown() const
317 return m_model
->showHiddenFiles();
320 void DolphinView::setGroupedSorting(bool grouped
)
322 if (grouped
== groupedSorting()) {
326 ViewProperties
props(viewPropertiesUrl());
327 props
.setGroupedSorting(grouped
);
330 m_container
->controller()->model()->setGroupedSorting(grouped
);
332 Q_EMIT
groupedSortingChanged(grouped
);
335 bool DolphinView::groupedSorting() const
337 return m_model
->groupedSorting();
340 KFileItemList
DolphinView::items() const
343 const int itemCount
= m_model
->count();
344 list
.reserve(itemCount
);
346 for (int i
= 0; i
< itemCount
; ++i
) {
347 list
.append(m_model
->fileItem(i
));
353 int DolphinView::itemsCount() const
355 return m_model
->count();
358 KFileItemList
DolphinView::selectedItems() const
360 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
362 KFileItemList selectedItems
;
363 const auto items
= selectionManager
->selectedItems();
364 selectedItems
.reserve(items
.count());
365 for (int index
: items
) {
366 selectedItems
.append(m_model
->fileItem(index
));
368 return selectedItems
;
371 int DolphinView::selectedItemsCount() const
373 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
374 return selectionManager
->selectedItems().count();
377 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
379 m_selectedUrls
= urls
;
382 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
384 m_currentItemUrl
= url
;
385 m_scrollToCurrentItem
= true;
388 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
390 const KItemListSelectionManager::SelectionMode mode
= enabled
391 ? KItemListSelectionManager::Select
392 : KItemListSelectionManager::Deselect
;
393 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
395 for (int index
= 0; index
< m_model
->count(); index
++) {
396 const KFileItem item
= m_model
->fileItem(index
);
397 if (regexp
.match(item
.text()).hasMatch()) {
398 // An alternative approach would be to store the matching items in a KItemSet and
399 // select them in one go after the loop, but we'd need a new function
400 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
402 selectionManager
->setSelected(index
, 1, mode
);
407 void DolphinView::setZoomLevel(int level
)
409 const int oldZoomLevel
= zoomLevel();
410 m_view
->setZoomLevel(level
);
411 if (zoomLevel() != oldZoomLevel
) {
413 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
417 int DolphinView::zoomLevel() const
419 return m_view
->zoomLevel();
422 void DolphinView::setSortRole(const QByteArray
& role
)
424 if (role
!= sortRole()) {
425 updateSortRole(role
);
429 QByteArray
DolphinView::sortRole() const
431 const KItemModelBase
* model
= m_container
->controller()->model();
432 return model
->sortRole();
435 void DolphinView::setSortOrder(Qt::SortOrder order
)
437 if (sortOrder() != order
) {
438 updateSortOrder(order
);
442 Qt::SortOrder
DolphinView::sortOrder() const
444 return m_model
->sortOrder();
447 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
449 if (sortFoldersFirst() != foldersFirst
) {
450 updateSortFoldersFirst(foldersFirst
);
454 bool DolphinView::sortFoldersFirst() const
456 return m_model
->sortDirectoriesFirst();
459 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
461 const QList
<QByteArray
> previousRoles
= roles
;
463 ViewProperties
props(viewPropertiesUrl());
464 props
.setVisibleRoles(roles
);
466 m_visibleRoles
= roles
;
467 m_view
->setVisibleRoles(roles
);
469 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
472 QList
<QByteArray
> DolphinView::visibleRoles() const
474 return m_visibleRoles
;
477 void DolphinView::reload()
479 QByteArray viewState
;
480 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
481 saveState(saveStream
);
484 loadDirectory(url(), true);
486 QDataStream
restoreStream(viewState
);
487 restoreState(restoreStream
);
490 void DolphinView::readSettings()
492 const int oldZoomLevel
= m_view
->zoomLevel();
494 GeneralSettings::self()->load();
495 m_view
->readSettings();
496 applyViewProperties();
498 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
499 m_container
->controller()->setAutoActivationDelay(delay
);
501 const int newZoomLevel
= m_view
->zoomLevel();
502 if (newZoomLevel
!= oldZoomLevel
) {
503 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
507 void DolphinView::writeSettings()
509 GeneralSettings::self()->save();
510 m_view
->writeSettings();
513 void DolphinView::setNameFilter(const QString
& nameFilter
)
515 m_model
->setNameFilter(nameFilter
);
518 QString
DolphinView::nameFilter() const
520 return m_model
->nameFilter();
523 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
525 return m_model
->setMimeTypeFilters(filters
);
528 QStringList
DolphinView::mimeTypeFilters() const
530 return m_model
->mimeTypeFilters();
533 void DolphinView::requestStatusBarText()
535 if (m_statJobForStatusBarText
) {
536 // Kill the pending request.
537 m_statJobForStatusBarText
->kill();
540 if (m_container
->controller()->selectionManager()->hasSelection()) {
543 KIO::filesize_t totalFileSize
= 0;
545 // Give a summary of the status of the selected files
546 const KFileItemList list
= selectedItems();
547 for (const KFileItem
& item
: list
) {
552 totalFileSize
+= item
.size();
556 if (folderCount
+ fileCount
== 1) {
557 // If only one item is selected, show info about it
558 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
560 // At least 2 items are selected
561 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
563 } else { // has no selection
564 if (!m_model
->rootItem().url().isValid()) {
568 m_statJobForStatusBarText
= KIO::statDetails(m_model
->rootItem().url(),
569 KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
570 connect(m_statJobForStatusBarText
, &KJob::result
,
571 this, &DolphinView::slotStatJobResult
);
572 m_statJobForStatusBarText
->start();
576 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
,
577 KIO::filesize_t totalFileSize
, const Selection selection
)
583 if (selection
== HasSelection
) {
584 // At least 2 items are selected because the case of 1 selected item is handled in
585 // DolphinView::requestStatusBarText().
586 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
587 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
589 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
590 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
593 if (fileCount
> 0 && folderCount
> 0) {
594 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
595 foldersText
, filesText
,
596 KFormat().formatByteSize(totalFileSize
));
597 } else if (fileCount
> 0) {
598 summary
= i18nc("@info:status files (size)", "%1 (%2)",
600 KFormat().formatByteSize(totalFileSize
));
601 } else if (folderCount
> 0) {
602 summary
= foldersText
;
604 summary
= i18nc("@info:status", "0 Folders, 0 Files");
606 Q_EMIT
statusBarTextChanged(summary
);
609 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
611 QList
<QAction
*> actions
;
613 if (items
.isEmpty()) {
614 const KFileItem item
= m_model
->rootItem();
615 if (!item
.isNull()) {
616 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
619 actions
= m_versionControlObserver
->actions(items
);
625 void DolphinView::setUrl(const QUrl
& url
)
637 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
638 this, &DolphinView::slotRoleEditingFinished
);
640 // It is important to clear the items from the model before
641 // applying the view properties, otherwise expensive operations
642 // might be done on the existing items although they get cleared
643 // anyhow afterwards by loadDirectory().
645 applyViewProperties();
648 Q_EMIT
urlChanged(url
);
651 void DolphinView::selectAll()
653 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
654 selectionManager
->setSelected(0, m_model
->count());
657 void DolphinView::invertSelection()
659 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
660 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
663 void DolphinView::clearSelection()
665 m_selectedUrls
.clear();
666 m_container
->controller()->selectionManager()->clearSelection();
669 void DolphinView::renameSelectedItems()
671 const KFileItemList items
= selectedItems();
672 if (items
.isEmpty()) {
676 if (items
.count() == 1 && GeneralSettings::renameInline()) {
677 const int index
= m_model
->index(items
.first());
679 QMetaObject::Connection
* const connection
= new QMetaObject::Connection
;
680 *connection
= connect(m_view
, &KItemListView::scrollingStopped
, this, [=](){
681 QObject::disconnect(*connection
);
684 m_view
->editRole(index
, "text");
688 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
689 this, &DolphinView::slotRoleEditingFinished
);
691 m_view
->scrollToItem(index
);
694 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
695 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
696 this, &DolphinView::slotRenameDialogRenamingFinished
);
701 // Assure that the current index remains visible when KFileItemModel
702 // will notify the view about changed items (which might result in
703 // a changed sorting).
704 m_assureVisibleCurrentIndex
= true;
707 void DolphinView::trashSelectedItems()
709 const QList
<QUrl
> list
= simplifiedSelectedUrls();
710 KIO::JobUiDelegate uiDelegate
;
711 uiDelegate
.setWindow(window());
712 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
713 KIO::Job
* job
= KIO::trash(list
);
714 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
715 KJobWidgets::setWindow(job
, this);
716 connect(job
, &KIO::Job::result
,
717 this, &DolphinView::slotTrashFileFinished
);
721 void DolphinView::deleteSelectedItems()
723 const QList
<QUrl
> list
= simplifiedSelectedUrls();
725 KIO::JobUiDelegate uiDelegate
;
726 uiDelegate
.setWindow(window());
727 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
728 KIO::Job
* job
= KIO::del(list
);
729 KJobWidgets::setWindow(job
, this);
730 connect(job
, &KIO::Job::result
,
731 this, &DolphinView::slotDeleteFileFinished
);
735 void DolphinView::cutSelectedItemsToClipboard()
737 QMimeData
* mimeData
= selectionMimeData();
738 KIO::setClipboardDataCut(mimeData
, true);
739 QApplication::clipboard()->setMimeData(mimeData
);
742 void DolphinView::copySelectedItemsToClipboard()
744 QMimeData
* mimeData
= selectionMimeData();
745 QApplication::clipboard()->setMimeData(mimeData
);
748 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
750 KIO::CopyJob
* job
= KIO::copy(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
);
758 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
760 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
761 KJobWidgets::setWindow(job
, this);
763 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
764 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
765 KIO::FileUndoManager::self()->recordCopyJob(job
);
769 void DolphinView::paste()
774 void DolphinView::pasteIntoFolder()
776 const KFileItemList items
= selectedItems();
777 if ((items
.count() == 1) && items
.first().isDir()) {
778 pasteToUrl(items
.first().url());
782 void DolphinView::duplicateSelectedItems()
784 const KFileItemList itemList
= selectedItems();
785 if (itemList
.isEmpty()) {
789 const QMimeDatabase db
;
791 // Duplicate all selected items and append "copy" to the end of the file name
792 // but before the filename extension, if present
793 QList
<QUrl
> newSelection
;
794 for (const auto &item
: itemList
) {
795 const QUrl originalURL
= item
.url();
796 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
797 const QString originalFileName
= item
.name();
799 QString extension
= db
.suffixForFileName(originalFileName
);
801 QUrl duplicateURL
= originalURL
;
803 // No extension; new filename is "<oldfilename> copy"
804 if (extension
.isEmpty()) {
805 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
806 // There's an extension; new filename is "<oldfilename> copy.<extension>"
808 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
809 extension
= QLatin1String(".") + extension
;
810 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
811 // Preserve file's original filename extension in case the casing differs
812 // from what QMimeDatabase::suffixForFileName() returned
813 const QString originalExtension
= originalFileName
.right(extension
.size());
814 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
817 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
818 KJobWidgets::setWindow(job
, this);
821 newSelection
<< duplicateURL
;
822 KIO::FileUndoManager::self()->recordCopyJob(job
);
826 forceUrlsSelection(newSelection
.first(), newSelection
);
829 void DolphinView::stopLoading()
831 m_model
->cancelDirectoryLoading();
834 void DolphinView::updatePalette()
836 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
841 QWidget
* viewport
= m_container
->viewport();
844 palette
.setColor(viewport
->backgroundRole(), color
);
845 viewport
->setPalette(palette
);
851 void DolphinView::abortTwoClicksRenaming()
853 m_twoClicksRenamingItemUrl
.clear();
854 m_twoClicksRenamingTimer
->stop();
857 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
859 switch (event
->type()) {
860 case QEvent::PaletteChange
:
862 QPixmapCache::clear();
865 case QEvent::WindowActivate
:
866 case QEvent::WindowDeactivate
:
870 case QEvent::KeyPress
:
871 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
872 if (GeneralSettings::useTabForSwitchingSplitView()) {
873 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
874 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
875 Q_EMIT
toggleActiveViewRequested();
880 case QEvent::FocusIn
:
881 if (watched
== m_container
) {
886 case QEvent::GraphicsSceneDragEnter
:
887 if (watched
== m_view
) {
889 abortTwoClicksRenaming();
893 case QEvent::GraphicsSceneDragLeave
:
894 if (watched
== m_view
) {
899 case QEvent::GraphicsSceneDrop
:
900 if (watched
== m_view
) {
907 return QWidget::eventFilter(watched
, event
);
910 void DolphinView::wheelEvent(QWheelEvent
* event
)
912 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
913 const QPoint numDegrees
= event
->angleDelta() / 8;
914 const QPoint numSteps
= numDegrees
/ 15;
916 setZoomLevel(zoomLevel() + numSteps
.y());
923 void DolphinView::hideEvent(QHideEvent
* event
)
926 QWidget::hideEvent(event
);
929 bool DolphinView::event(QEvent
* event
)
931 if (event
->type() == QEvent::WindowDeactivate
) {
933 * Dolphin leaves file preview tooltips open even when is not visible.
935 * Hide tool-tip when Dolphin loses focus.
938 abortTwoClicksRenaming();
941 return QWidget::event(event
);
944 void DolphinView::activate()
949 void DolphinView::slotItemActivated(int index
)
951 abortTwoClicksRenaming();
953 const KFileItem item
= m_model
->fileItem(index
);
954 if (!item
.isNull()) {
955 Q_EMIT
itemActivated(item
);
959 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
961 Q_ASSERT(indexes
.count() >= 2);
963 abortTwoClicksRenaming();
965 if (indexes
.count() > 5) {
966 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
967 const int answer
= KMessageBox::warningYesNo(this, question
);
968 if (answer
!= KMessageBox::Yes
) {
974 items
.reserve(indexes
.count());
976 for (int index
: indexes
) {
977 KFileItem item
= m_model
->fileItem(index
);
978 const QUrl
& url
= openItemAsFolderUrl(item
);
980 if (!url
.isEmpty()) { // Open folders in new tabs
981 Q_EMIT
tabRequested(url
);
987 if (items
.count() == 1) {
988 Q_EMIT
itemActivated(items
.first());
989 } else if (items
.count() > 1) {
990 Q_EMIT
itemsActivated(items
);
994 void DolphinView::slotItemMiddleClicked(int index
)
996 const KFileItem
& item
= m_model
->fileItem(index
);
997 const QUrl
& url
= openItemAsFolderUrl(item
);
998 if (!url
.isEmpty()) {
999 Q_EMIT
tabRequested(url
);
1000 } else if (isTabsForFilesEnabled()) {
1001 Q_EMIT
tabRequested(item
.url());
1005 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
1007 // Force emit of a selection changed signal before we request the
1008 // context menu, to update the edit-actions first. (See Bug 294013)
1009 if (m_selectionChangedTimer
->isActive()) {
1010 emitSelectionChangedSignal();
1013 const KFileItem item
= m_model
->fileItem(index
);
1014 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
1017 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
1019 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
1022 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
1024 ViewProperties
props(viewPropertiesUrl());
1026 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
1028 KItemListView
* view
= m_container
->controller()->view();
1029 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1031 bool indexingEnabled
= false;
1033 Baloo::IndexerConfig config
;
1034 indexingEnabled
= config
.fileIndexingEnabled();
1038 QMenu
* groupMenu
= nullptr;
1040 // Add all roles to the menu that can be shown or hidden by the user
1041 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1042 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1043 if (info
.role
== "text") {
1044 // It should not be possible to hide the "text" role
1048 const QString text
= m_model
->roleDescription(info
.role
);
1049 QAction
* action
= nullptr;
1050 if (info
.group
.isEmpty()) {
1051 action
= menu
->addAction(text
);
1053 if (!groupMenu
|| info
.group
!= groupName
) {
1054 groupName
= info
.group
;
1055 groupMenu
= menu
->addMenu(groupName
);
1058 action
= groupMenu
->addAction(text
);
1061 action
->setCheckable(true);
1062 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1063 action
->setData(info
.role
);
1065 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1066 (info
.requiresBaloo
) ||
1067 (info
.requiresIndexer
&& indexingEnabled
);
1068 action
->setEnabled(enable
);
1071 menu
->addSeparator();
1073 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1074 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1076 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1077 autoAdjustWidthsAction
->setCheckable(true);
1078 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1079 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1081 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1082 customWidthsAction
->setCheckable(true);
1083 customWidthsAction
->setChecked(!autoColumnWidths
);
1084 customWidthsAction
->setActionGroup(widthsGroup
);
1086 QAction
* action
= menu
->exec(pos
.toPoint());
1087 if (menu
&& action
) {
1088 KItemListHeader
* header
= view
->header();
1090 if (action
== autoAdjustWidthsAction
) {
1091 // Clear the column-widths from the viewproperties and turn on
1092 // the automatic resizing of the columns
1093 props
.setHeaderColumnWidths(QList
<int>());
1094 header
->setAutomaticColumnResizing(true);
1095 } else if (action
== customWidthsAction
) {
1096 // Apply the current column-widths as custom column-widths and turn
1097 // off the automatic resizing of the columns
1098 QList
<int> columnWidths
;
1099 const auto visibleRoles
= view
->visibleRoles();
1100 columnWidths
.reserve(visibleRoles
.count());
1101 for (const QByteArray
& role
: visibleRoles
) {
1102 columnWidths
.append(header
->columnWidth(role
));
1104 props
.setHeaderColumnWidths(columnWidths
);
1105 header
->setAutomaticColumnResizing(false);
1107 // Show or hide the selected role
1108 const QByteArray selectedRole
= action
->data().toByteArray();
1110 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1111 if (action
->isChecked()) {
1112 visibleRoles
.append(selectedRole
);
1114 visibleRoles
.removeOne(selectedRole
);
1117 view
->setVisibleRoles(visibleRoles
);
1118 props
.setVisibleRoles(visibleRoles
);
1120 QList
<int> columnWidths
;
1121 if (!header
->automaticColumnResizing()) {
1122 const auto visibleRoles
= view
->visibleRoles();
1123 columnWidths
.reserve(visibleRoles
.count());
1124 for (const QByteArray
& role
: visibleRoles
) {
1125 columnWidths
.append(header
->columnWidth(role
));
1128 props
.setHeaderColumnWidths(columnWidths
);
1135 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1137 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1139 ViewProperties
props(viewPropertiesUrl());
1140 QList
<int> columnWidths
= props
.headerColumnWidths();
1141 if (columnWidths
.count() != visibleRoles
.count()) {
1142 columnWidths
.clear();
1143 columnWidths
.reserve(visibleRoles
.count());
1144 const KItemListHeader
* header
= m_view
->header();
1145 for (const QByteArray
& role
: visibleRoles
) {
1146 const int width
= header
->columnWidth(role
);
1147 columnWidths
.append(width
);
1151 const int roleIndex
= visibleRoles
.indexOf(role
);
1152 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1153 columnWidths
[roleIndex
] = current
;
1155 props
.setHeaderColumnWidths(columnWidths
);
1158 void DolphinView::slotItemHovered(int index
)
1160 const KFileItem item
= m_model
->fileItem(index
);
1162 if (GeneralSettings::showToolTips() && !m_dragging
) {
1163 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1164 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1165 itemRect
.moveTo(pos
);
1168 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1172 Q_EMIT
requestItemInfo(item
);
1175 void DolphinView::slotItemUnhovered(int index
)
1179 Q_EMIT
requestItemInfo(KFileItem());
1182 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1185 KFileItem destItem
= m_model
->fileItem(index
);
1186 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1187 // Use the URL of the view as drop target if the item is no directory
1189 destItem
= m_model
->rootItem();
1192 // The item represents a directory or desktop-file
1193 destUrl
= destItem
.mostLocalUrl();
1196 QDropEvent
dropEvent(event
->pos().toPoint(),
1197 event
->possibleActions(),
1200 event
->modifiers());
1201 dropUrls(destUrl
, &dropEvent
, this);
1206 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1208 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1211 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1213 if (destUrl
== url()) {
1214 // Mark the dropped urls as selected.
1215 m_clearSelectionBeforeSelectingNewItems
= true;
1216 m_markFirstNewlySelectedItemAsCurrent
= true;
1217 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1222 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1224 if (previous
!= nullptr) {
1225 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1226 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1227 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1228 m_versionControlObserver
->setModel(nullptr);
1232 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1233 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1234 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1235 m_versionControlObserver
->setModel(fileItemModel
);
1239 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1245 if (buttons
& Qt::BackButton
) {
1246 Q_EMIT
goBackRequested();
1247 } else if (buttons
& Qt::ForwardButton
) {
1248 Q_EMIT
goForwardRequested();
1252 void DolphinView::slotSelectedItemTextPressed(int index
)
1254 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1255 const KFileItem item
= m_model
->fileItem(index
);
1256 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1257 if (capabilities
.supportsMoving()) {
1258 m_twoClicksRenamingItemUrl
= item
.url();
1259 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1264 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1266 slotItemCreated(to
);
1269 void DolphinView::slotItemCreated(const QUrl
& url
)
1271 if (m_markFirstNewlySelectedItemAsCurrent
) {
1272 markUrlAsCurrent(url
);
1273 m_markFirstNewlySelectedItemAsCurrent
= false;
1275 m_selectedUrls
<< url
;
1278 void DolphinView::slotJobResult(KJob
*job
)
1281 Q_EMIT
errorMessage(job
->errorString());
1283 if (!m_selectedUrls
.isEmpty()) {
1284 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1288 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1290 const int currentCount
= current
.count();
1291 const int previousCount
= previous
.count();
1292 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1293 (currentCount
> 0 && previousCount
== 0);
1295 // If nothing has been selected before and something got selected (or if something
1296 // was selected before and now nothing is selected) the selectionChangedSignal must
1297 // be emitted asynchronously as fast as possible to update the edit-actions.
1298 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1299 m_selectionChangedTimer
->start();
1302 void DolphinView::emitSelectionChangedSignal()
1304 m_selectionChangedTimer
->stop();
1305 Q_EMIT
selectionChanged(selectedItems());
1308 void DolphinView::slotStatJobResult(KJob
*job
)
1310 int folderCount
= 0;
1312 KIO::filesize_t totalFileSize
= 0;
1313 bool countFileSize
= true;
1315 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1316 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1317 // We have a precomputed value.
1318 totalFileSize
= static_cast<KIO::filesize_t
>(
1319 entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1320 countFileSize
= false;
1323 const int itemCount
= m_model
->count();
1324 for (int i
= 0; i
< itemCount
; ++i
) {
1325 const KFileItem item
= m_model
->fileItem(i
);
1330 if (countFileSize
) {
1331 totalFileSize
+= item
.size();
1335 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1338 void DolphinView::updateSortRole(const QByteArray
& role
)
1340 ViewProperties
props(viewPropertiesUrl());
1341 props
.setSortRole(role
);
1343 KItemModelBase
* model
= m_container
->controller()->model();
1344 model
->setSortRole(role
);
1346 Q_EMIT
sortRoleChanged(role
);
1349 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1351 ViewProperties
props(viewPropertiesUrl());
1352 props
.setSortOrder(order
);
1354 m_model
->setSortOrder(order
);
1356 Q_EMIT
sortOrderChanged(order
);
1359 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1361 ViewProperties
props(viewPropertiesUrl());
1362 props
.setSortFoldersFirst(foldersFirst
);
1364 m_model
->setSortDirectoriesFirst(foldersFirst
);
1366 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1369 QPair
<bool, QString
> DolphinView::pasteInfo() const
1371 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1372 QPair
<bool, QString
> info
;
1373 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1377 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1379 m_tabsForFiles
= tabsForFiles
;
1382 bool DolphinView::isTabsForFilesEnabled() const
1384 return m_tabsForFiles
;
1387 bool DolphinView::itemsExpandable() const
1389 return m_mode
== DetailsView
;
1392 void DolphinView::restoreState(QDataStream
& stream
)
1394 // Read the version number of the view state and check if the version is supported.
1395 quint32 version
= 0;
1398 // The version of the view state isn't supported, we can't restore it.
1402 // Restore the current item that had the keyboard focus
1403 stream
>> m_currentItemUrl
;
1405 // Restore the previously selected items
1406 stream
>> m_selectedUrls
;
1408 // Restore the view position
1409 stream
>> m_restoredContentsPosition
;
1411 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1414 m_model
->restoreExpandedDirectories(urls
);
1417 void DolphinView::saveState(QDataStream
& stream
)
1419 stream
<< quint32(1); // View state version
1421 // Save the current item that has the keyboard focus
1422 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1423 if (currentIndex
!= -1) {
1424 KFileItem item
= m_model
->fileItem(currentIndex
);
1425 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1426 QUrl currentItemUrl
= item
.url();
1427 stream
<< currentItemUrl
;
1432 // Save the selected urls
1433 stream
<< selectedItems().urlList();
1435 // Save view position
1436 const qreal x
= m_container
->horizontalScrollBar()->value();
1437 const qreal y
= m_container
->verticalScrollBar()->value();
1438 stream
<< QPoint(x
, y
);
1440 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1441 stream
<< m_model
->expandedDirectories();
1444 KFileItem
DolphinView::rootItem() const
1446 return m_model
->rootItem();
1449 void DolphinView::setViewPropertiesContext(const QString
& context
)
1451 m_viewPropertiesContext
= context
;
1454 QString
DolphinView::viewPropertiesContext() const
1456 return m_viewPropertiesContext
;
1459 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1461 if (item
.isNull()) {
1465 QUrl url
= item
.targetUrl();
1471 if (item
.isMimeTypeKnown()) {
1472 const QString
& mimetype
= item
.mimetype();
1474 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1475 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1476 // zip:/<path>/ when clicking on a zip file, etc.
1477 // The .protocol file specifies the mimetype that the kioslave handles.
1478 // Note that we don't use mimetype inheritance since we don't want to
1479 // open OpenDocument files as zip folders...
1480 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1481 if (!protocol
.isEmpty()) {
1482 url
.setScheme(protocol
);
1487 if (mimetype
== QLatin1String("application/x-desktop")) {
1488 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1489 KDesktopFile
desktopFile(url
.toLocalFile());
1490 if (desktopFile
.hasLinkType()) {
1491 const QString linkUrl
= desktopFile
.readUrl();
1492 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1493 return QUrl::fromUserInput(linkUrl
);
1502 void DolphinView::resetZoomLevel()
1504 ViewModeSettings::ViewMode mode
;
1507 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1508 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1509 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1511 const ViewModeSettings
settings(mode
);
1512 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1513 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1516 void DolphinView::observeCreatedItem(const QUrl
& url
)
1519 forceUrlsSelection(url
, {url
});
1523 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1525 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1526 Q_EMIT
redirection(oldUrl
, newUrl
);
1527 m_url
= newUrl
; // #186947
1531 void DolphinView::updateViewState()
1533 if (m_currentItemUrl
!= QUrl()) {
1534 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1536 // if there is a selection already, leave it that way
1537 if (!selectionManager
->hasSelection()) {
1538 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1539 if (currentIndex
!= -1) {
1540 selectionManager
->setCurrentItem(currentIndex
);
1542 // scroll to current item and reset the state
1543 if (m_scrollToCurrentItem
) {
1544 m_view
->scrollToItem(currentIndex
);
1545 m_scrollToCurrentItem
= false;
1548 selectionManager
->setCurrentItem(0);
1552 m_currentItemUrl
= QUrl();
1555 if (!m_restoredContentsPosition
.isNull()) {
1556 const int x
= m_restoredContentsPosition
.x();
1557 const int y
= m_restoredContentsPosition
.y();
1558 m_restoredContentsPosition
= QPoint();
1560 m_container
->horizontalScrollBar()->setValue(x
);
1561 m_container
->verticalScrollBar()->setValue(y
);
1564 if (!m_selectedUrls
.isEmpty()) {
1565 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1567 // if there is a selection already, leave it that way
1568 if (!selectionManager
->hasSelection()) {
1569 if (m_clearSelectionBeforeSelectingNewItems
) {
1570 selectionManager
->clearSelection();
1571 m_clearSelectionBeforeSelectingNewItems
= false;
1574 KItemSet selectedItems
= selectionManager
->selectedItems();
1576 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1577 while (it
!= m_selectedUrls
.end()) {
1578 const int index
= m_model
->index(*it
);
1580 selectedItems
.insert(index
);
1581 it
= m_selectedUrls
.erase(it
);
1587 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1588 selectionManager
->setSelectedItems(selectedItems
);
1593 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1596 if (GeneralSettings::showToolTips()) {
1597 m_toolTipManager
->hideToolTip(behavior
);
1604 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1606 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1608 // verify that only one item is selected
1609 if (selectionManager
->selectedItems().count() == 1) {
1610 const int index
= selectionManager
->currentItem();
1611 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1613 // check if the selected item was the same item that started the twoClicksRenaming
1614 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1615 renameSelectedItems();
1620 void DolphinView::slotTrashFileFinished(KJob
* job
)
1622 if (job
->error() == 0) {
1623 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1624 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1625 Q_EMIT
errorMessage(job
->errorString());
1629 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1631 if (job
->error() == 0) {
1632 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1633 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1634 Q_EMIT
errorMessage(job
->errorString());
1638 void DolphinView::slotRenamingResult(KJob
* job
)
1641 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1643 const QUrl newUrl
= copyJob
->destUrl();
1644 const int index
= m_model
->index(newUrl
);
1646 QHash
<QByteArray
, QVariant
> data
;
1647 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1648 data
.insert("text", oldUrl
.fileName());
1649 m_model
->setData(index
, data
);
1654 void DolphinView::slotDirectoryLoadingStarted()
1657 updatePlaceholderLabel();
1659 // Disable the writestate temporary until it can be determined in a fast way
1660 // in DolphinView::slotDirectoryLoadingCompleted()
1661 if (m_isFolderWritable
) {
1662 m_isFolderWritable
= false;
1663 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1666 Q_EMIT
directoryLoadingStarted();
1669 void DolphinView::slotDirectoryLoadingCompleted()
1673 // Update the view-state. This has to be done asynchronously
1674 // because the view might not be in its final state yet.
1675 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1677 // Update the placeholder label in case we found that the folder was empty
1680 Q_EMIT
directoryLoadingCompleted();
1682 updatePlaceholderLabel();
1683 updateWritableState();
1686 void DolphinView::slotDirectoryLoadingCanceled()
1690 updatePlaceholderLabel();
1692 Q_EMIT
directoryLoadingCanceled();
1695 void DolphinView::slotItemsChanged()
1697 m_assureVisibleCurrentIndex
= false;
1700 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1703 Q_ASSERT(m_model
->sortOrder() == current
);
1705 ViewProperties
props(viewPropertiesUrl());
1706 props
.setSortOrder(current
);
1708 Q_EMIT
sortOrderChanged(current
);
1711 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1714 Q_ASSERT(m_model
->sortRole() == current
);
1716 ViewProperties
props(viewPropertiesUrl());
1717 props
.setSortRole(current
);
1719 Q_EMIT
sortRoleChanged(current
);
1722 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1723 const QList
<QByteArray
>& previous
)
1726 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1728 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1730 m_visibleRoles
= current
;
1732 ViewProperties
props(viewPropertiesUrl());
1733 props
.setVisibleRoles(m_visibleRoles
);
1735 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1738 void DolphinView::slotRoleEditingCanceled()
1740 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1741 this, &DolphinView::slotRoleEditingFinished
);
1744 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1746 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1747 this, &DolphinView::slotRoleEditingFinished
);
1749 const KFileItemList items
= selectedItems();
1750 if (items
.count() != 1) {
1754 if (role
== "text") {
1755 const KFileItem oldItem
= items
.first();
1756 const EditResult retVal
= value
.value
<EditResult
>();
1757 const QString newName
= retVal
.newName
;
1758 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1759 const QUrl oldUrl
= oldItem
.url();
1761 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1762 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1765 //Confirm hiding file/directory by renaming inline
1766 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1767 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1768 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1770 const auto code
= KMessageBox::questionYesNo(this,
1771 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1772 "Do you still want to rename it?")
1773 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1774 "Do you still want to rename it?"),
1775 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1777 KStandardGuiItem::cancel(),
1778 QStringLiteral("ConfirmHide")
1781 if (code
== KMessageBox::No
) {
1787 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1788 if (!newNameExistsAlready
&& m_model
->index(oldUrl
) == index
) {
1789 // Only change the data in the model if no item with the new name
1790 // is in the model yet. If there is an item with the new name
1791 // already, calling KIO::CopyJob will open a dialog
1792 // asking for a new name, and KFileItemModel will update the
1793 // data when the dir lister signals that the file name has changed.
1794 QHash
<QByteArray
, QVariant
> data
;
1795 data
.insert(role
, retVal
.newName
);
1796 m_model
->setData(index
, data
);
1799 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1800 KJobWidgets::setWindow(job
, this);
1801 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1802 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1804 forceUrlsSelection(newUrl
, {newUrl
});
1806 if (!newNameExistsAlready
) {
1807 // Only connect the result signal if there is no item with the new name
1808 // in the model yet, see bug 328262.
1809 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1812 if (retVal
.direction
!= EditDone
) {
1813 const short indexShift
= retVal
.direction
== EditNext
? 1 : -1;
1814 m_container
->controller()->selectionManager()->setSelected(index
, 1, KItemListSelectionManager::Deselect
);
1815 m_container
->controller()->selectionManager()->setSelected(index
+ indexShift
, 1,
1816 KItemListSelectionManager::Select
);
1817 renameSelectedItems();
1822 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1824 if (!url
.isValid()) {
1825 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1826 if (location
.isEmpty()) {
1827 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1829 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1835 m_model
->refreshDirectory(url
);
1837 m_model
->loadDirectory(url
);
1841 void DolphinView::applyViewProperties()
1843 const ViewProperties
props(viewPropertiesUrl());
1844 applyViewProperties(props
);
1847 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1849 m_view
->beginTransaction();
1851 const Mode mode
= props
.viewMode();
1852 if (m_mode
!= mode
) {
1853 const Mode previousMode
= m_mode
;
1856 // Changing the mode might result in changing
1857 // the zoom level. Remember the old zoom level so
1858 // that zoomLevelChanged() can get emitted.
1859 const int oldZoomLevel
= m_view
->zoomLevel();
1862 Q_EMIT
modeChanged(m_mode
, previousMode
);
1864 if (m_view
->zoomLevel() != oldZoomLevel
) {
1865 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1869 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1870 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1871 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1872 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1875 const bool groupedSorting
= props
.groupedSorting();
1876 if (groupedSorting
!= m_model
->groupedSorting()) {
1877 m_model
->setGroupedSorting(groupedSorting
);
1878 Q_EMIT
groupedSortingChanged(groupedSorting
);
1881 const QByteArray sortRole
= props
.sortRole();
1882 if (sortRole
!= m_model
->sortRole()) {
1883 m_model
->setSortRole(sortRole
);
1884 Q_EMIT
sortRoleChanged(sortRole
);
1887 const Qt::SortOrder sortOrder
= props
.sortOrder();
1888 if (sortOrder
!= m_model
->sortOrder()) {
1889 m_model
->setSortOrder(sortOrder
);
1890 Q_EMIT
sortOrderChanged(sortOrder
);
1893 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1894 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1895 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1896 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1899 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1900 if (visibleRoles
!= m_visibleRoles
) {
1901 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1902 m_visibleRoles
= visibleRoles
;
1903 m_view
->setVisibleRoles(visibleRoles
);
1904 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1907 const bool previewsShown
= props
.previewsShown();
1908 if (previewsShown
!= m_view
->previewsShown()) {
1909 const int oldZoomLevel
= zoomLevel();
1911 m_view
->setPreviewsShown(previewsShown
);
1912 Q_EMIT
previewsShownChanged(previewsShown
);
1914 // Changing the preview-state might result in a changed zoom-level
1915 if (oldZoomLevel
!= zoomLevel()) {
1916 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1920 KItemListView
* itemListView
= m_container
->controller()->view();
1921 if (itemListView
->isHeaderVisible()) {
1922 KItemListHeader
* header
= itemListView
->header();
1923 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1924 const int rolesCount
= m_visibleRoles
.count();
1925 if (headerColumnWidths
.count() == rolesCount
) {
1926 header
->setAutomaticColumnResizing(false);
1928 QHash
<QByteArray
, qreal
> columnWidths
;
1929 for (int i
= 0; i
< rolesCount
; ++i
) {
1930 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1932 header
->setColumnWidths(columnWidths
);
1934 header
->setAutomaticColumnResizing(true);
1938 m_view
->endTransaction();
1941 void DolphinView::applyModeToView()
1944 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1945 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1946 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1947 default: Q_ASSERT(false); break;
1951 void DolphinView::pasteToUrl(const QUrl
& url
)
1953 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1954 KJobWidgets::setWindow(job
, this);
1955 m_clearSelectionBeforeSelectingNewItems
= true;
1956 m_markFirstNewlySelectedItemAsCurrent
= true;
1957 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1958 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1961 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1965 const KFileItemList items
= selectedItems();
1966 urls
.reserve(items
.count());
1967 for (const KFileItem
& item
: items
) {
1968 urls
.append(item
.url());
1971 if (itemsExpandable()) {
1972 // TODO: Check if we still need KDirModel for this in KDE 5.0
1973 urls
= KDirModel::simplifiedUrlList(urls
);
1979 QMimeData
* DolphinView::selectionMimeData() const
1981 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1982 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1984 return m_model
->createMimeData(selectedIndexes
);
1987 void DolphinView::updateWritableState()
1989 const bool wasFolderWritable
= m_isFolderWritable
;
1990 m_isFolderWritable
= false;
1992 KFileItem item
= m_model
->rootItem();
1993 if (item
.isNull()) {
1994 // Try to find out if the URL is writable even if the "root item" is
1995 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1996 item
= KFileItem(url());
1997 item
.setDelayedMimeTypes(true);
2000 KFileItemListProperties
capabilities(KFileItemList() << item
);
2001 m_isFolderWritable
= capabilities
.supportsWriting();
2003 if (m_isFolderWritable
!= wasFolderWritable
) {
2004 Q_EMIT
writeStateChanged(m_isFolderWritable
);
2008 QUrl
DolphinView::viewPropertiesUrl() const
2010 if (m_viewPropertiesContext
.isEmpty()) {
2015 url
.setScheme(m_url
.scheme());
2016 url
.setPath(m_viewPropertiesContext
);
2020 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
2022 forceUrlsSelection(urls
.first(), urls
);
2025 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
2028 m_clearSelectionBeforeSelectingNewItems
= true;
2029 markUrlAsCurrent(current
);
2030 markUrlsAsSelected(selected
);
2033 void DolphinView::copyPathToClipboard()
2035 const KFileItemList list
= selectedItems();
2036 if (list
.isEmpty()) {
2039 const KFileItem
& item
= list
.at(0);
2040 QString path
= item
.localPath();
2041 if (path
.isEmpty()) {
2042 path
= item
.url().toDisplayString();
2044 QClipboard
* clipboard
= QApplication::clipboard();
2045 if (clipboard
== nullptr) {
2048 clipboard
->setText(path
);
2051 void DolphinView::slotIncreaseZoom()
2053 setZoomLevel(zoomLevel() + 1);
2056 void DolphinView::slotDecreaseZoom()
2058 setZoomLevel(zoomLevel() - 1);
2061 void DolphinView::slotSwipeUp()
2063 Q_EMIT
goUpRequested();
2066 void DolphinView::updatePlaceholderLabel()
2068 if (m_loading
|| itemsCount() > 0) {
2069 m_placeholderLabel
->setVisible(false);
2073 if (!nameFilter().isEmpty()) {
2074 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2075 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2076 m_placeholderLabel
->setText(i18n("No items matching the search"));
2077 } else if (m_url
.scheme() == QLatin1String("trash")) {
2078 m_placeholderLabel
->setText(i18n("Trash is empty"));
2079 } else if (m_url
.scheme() == QLatin1String("tags")) {
2080 m_placeholderLabel
->setText(i18n("No tags"));
2081 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2082 m_placeholderLabel
->setText(i18n("No recently used items"));
2083 } else if (m_url
.scheme() == QLatin1String("smb")) {
2084 m_placeholderLabel
->setText(i18n("No shared folders found"));
2085 } else if (m_url
.scheme() == QLatin1String("network")) {
2086 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2087 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2088 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2089 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2090 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2092 m_placeholderLabel
->setText(i18n("Folder is empty"));
2095 m_placeholderLabel
->setVisible(true);