2 * SPDX-FileCopyrightText: 2006-2009 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2006 Gregor Kališnik <gregor@podnapisi.net>
5 * SPDX-License-Identifier: GPL-2.0-or-later
8 #include "dolphinview.h"
10 #include "dolphin_detailsmodesettings.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphinitemlistview.h"
13 #include "dolphinnewfilemenuobserver.h"
14 #include "draganddrophelper.h"
15 #include "kitemviews/kfileitemlistview.h"
16 #include "kitemviews/kfileitemmodel.h"
17 #include "kitemviews/kitemlistcontainer.h"
18 #include "kitemviews/kitemlistcontroller.h"
19 #include "kitemviews/kitemlistheader.h"
20 #include "kitemviews/kitemlistselectionmanager.h"
21 #include "versioncontrol/versioncontrolobserver.h"
22 #include "viewproperties.h"
23 #include "views/tooltips/tooltipmanager.h"
24 #include "zoomlevelinfo.h"
27 #include <Baloo/IndexerConfig>
29 #include <KColorScheme>
30 #include <KDesktopFile>
32 #include <KFileItemListProperties>
34 #include <KIO/CopyJob>
35 #include <KIO/DeleteJob>
36 #include <KIO/DropJob>
37 #include <KIO/JobUiDelegate>
39 #include <KIO/PasteJob>
40 #include <KIO/PreviewJob>
41 #include <KIO/RenameFileDialog>
42 #include <KJobWidgets>
43 #include <KLocalizedString>
44 #include <KMessageBox>
45 #include <KProtocolManager>
47 #include <QAbstractItemView>
48 #include <QApplication>
51 #include <QGraphicsOpacityEffect>
52 #include <QGraphicsSceneDragDropEvent>
55 #include <QMimeDatabase>
56 #include <QPixmapCache>
61 #include <QVBoxLayout>
63 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
66 m_tabsForFiles(false),
67 m_assureVisibleCurrentIndex(false),
68 m_isFolderWritable(true),
71 m_viewPropertiesContext(),
72 m_mode(DolphinView::IconsView
),
78 m_toolTipManager(nullptr),
79 m_selectionChangedTimer(nullptr),
81 m_scrollToCurrentItem(false),
82 m_restoredContentsPosition(),
84 m_clearSelectionBeforeSelectingNewItems(false),
85 m_markFirstNewlySelectedItemAsCurrent(false),
86 m_versionControlObserver(nullptr),
87 m_twoClicksRenamingTimer(nullptr),
88 m_placeholderLabel(nullptr)
90 m_topLayout
= new QVBoxLayout(this);
91 m_topLayout
->setSpacing(0);
92 m_topLayout
->setContentsMargins(0, 0, 0, 0);
94 // When a new item has been created by the "Create New..." menu, the item should
95 // get selected and it must be assured that the item will get visible. As the
96 // creation is done asynchronously, several signals must be checked:
97 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
98 this, &DolphinView::observeCreatedItem
);
100 m_selectionChangedTimer
= new QTimer(this);
101 m_selectionChangedTimer
->setSingleShot(true);
102 m_selectionChangedTimer
->setInterval(300);
103 connect(m_selectionChangedTimer
, &QTimer::timeout
,
104 this, &DolphinView::emitSelectionChangedSignal
);
106 m_model
= new KFileItemModel(this);
107 m_view
= new DolphinItemListView();
108 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
109 m_view
->setVisibleRoles({"text"});
112 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
113 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
114 controller
->setAutoActivationDelay(delay
);
116 // The EnlargeSmallPreviews setting can only be changed after the model
117 // has been set in the view by KItemListController.
118 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
120 m_container
= new KItemListContainer(controller
, this);
121 m_container
->installEventFilter(this);
122 setFocusProxy(m_container
);
123 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
124 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
126 // Show some placeholder text for empty folders
127 // This is made using a heavily-modified QLabel rather than a KTitleWidget
128 // because KTitleWidget can't be told to turn off mouse-selectable text
129 m_placeholderLabel
= new QLabel(this);
130 QFont placeholderLabelFont
;
131 // To match the size of a level 2 Heading/KTitleWidget
132 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
133 m_placeholderLabel
->setFont(placeholderLabelFont
);
134 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
135 m_placeholderLabel
->setWordWrap(true);
136 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
137 // Match opacity of QML placeholder label component
138 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
139 effect
->setOpacity(0.5);
140 m_placeholderLabel
->setGraphicsEffect(effect
);
141 // Set initial text and visibility
142 updatePlaceholderLabel();
143 // Add a new layout to hold it and put it in the layout
144 auto *centeringLayout
= new QVBoxLayout(this);
145 m_container
->setLayout(centeringLayout
);
146 centeringLayout
->addWidget(m_placeholderLabel
);
147 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
149 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
150 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
151 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
152 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
153 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
154 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
155 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
156 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
157 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
158 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
159 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
160 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
161 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
162 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
163 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
164 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
165 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
167 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
168 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
169 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::directoryLoadingCanceled
);
170 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
171 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
172 connect(m_model
, &KFileItemModel::itemsChanged
,
173 this, &DolphinView::slotItemsChanged
);
174 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
175 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
176 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
177 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
178 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
179 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
181 connect(this, &DolphinView::itemCountChanged
,
182 this, &DolphinView::updatePlaceholderLabel
);
183 connect(this, &DolphinView::urlChanged
,
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 QString
DolphinView::statusBarText() const
541 KIO::filesize_t totalFileSize
= 0;
543 if (m_container
->controller()->selectionManager()->hasSelection()) {
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 return list
.first().getStatusBarInfo();
559 // At least 2 items are selected
560 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
561 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
564 calculateItemCount(fileCount
, folderCount
, totalFileSize
);
565 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
566 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
569 if (fileCount
> 0 && folderCount
> 0) {
570 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
571 foldersText
, filesText
,
572 KFormat().formatByteSize(totalFileSize
));
573 } else if (fileCount
> 0) {
574 summary
= i18nc("@info:status files (size)", "%1 (%2)",
576 KFormat().formatByteSize(totalFileSize
));
577 } else if (folderCount
> 0) {
578 summary
= foldersText
;
580 summary
= i18nc("@info:status", "0 Folders, 0 Files");
586 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
588 QList
<QAction
*> actions
;
590 if (items
.isEmpty()) {
591 const KFileItem item
= m_model
->rootItem();
592 if (!item
.isNull()) {
593 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
596 actions
= m_versionControlObserver
->actions(items
);
602 void DolphinView::setUrl(const QUrl
& url
)
614 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
615 this, &DolphinView::slotRoleEditingFinished
);
617 // It is important to clear the items from the model before
618 // applying the view properties, otherwise expensive operations
619 // might be done on the existing items although they get cleared
620 // anyhow afterwards by loadDirectory().
622 applyViewProperties();
625 Q_EMIT
urlChanged(url
);
628 void DolphinView::selectAll()
630 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
631 selectionManager
->setSelected(0, m_model
->count());
634 void DolphinView::invertSelection()
636 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
637 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
640 void DolphinView::clearSelection()
642 m_selectedUrls
.clear();
643 m_container
->controller()->selectionManager()->clearSelection();
646 void DolphinView::renameSelectedItems()
648 const KFileItemList items
= selectedItems();
649 if (items
.isEmpty()) {
653 if (items
.count() == 1 && GeneralSettings::renameInline()) {
654 const int index
= m_model
->index(items
.first());
655 m_view
->editRole(index
, "text");
659 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
660 this, &DolphinView::slotRoleEditingFinished
);
662 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
663 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
664 this, &DolphinView::slotRenameDialogRenamingFinished
);
669 // Assure that the current index remains visible when KFileItemModel
670 // will notify the view about changed items (which might result in
671 // a changed sorting).
672 m_assureVisibleCurrentIndex
= true;
675 void DolphinView::trashSelectedItems()
677 const QList
<QUrl
> list
= simplifiedSelectedUrls();
678 KIO::JobUiDelegate uiDelegate
;
679 uiDelegate
.setWindow(window());
680 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
681 KIO::Job
* job
= KIO::trash(list
);
682 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
683 KJobWidgets::setWindow(job
, this);
684 connect(job
, &KIO::Job::result
,
685 this, &DolphinView::slotTrashFileFinished
);
689 void DolphinView::deleteSelectedItems()
691 const QList
<QUrl
> list
= simplifiedSelectedUrls();
693 KIO::JobUiDelegate uiDelegate
;
694 uiDelegate
.setWindow(window());
695 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
696 KIO::Job
* job
= KIO::del(list
);
697 KJobWidgets::setWindow(job
, this);
698 connect(job
, &KIO::Job::result
,
699 this, &DolphinView::slotDeleteFileFinished
);
703 void DolphinView::cutSelectedItemsToClipboard()
705 QMimeData
* mimeData
= selectionMimeData();
706 KIO::setClipboardDataCut(mimeData
, true);
707 QApplication::clipboard()->setMimeData(mimeData
);
710 void DolphinView::copySelectedItemsToClipboard()
712 QMimeData
* mimeData
= selectionMimeData();
713 QApplication::clipboard()->setMimeData(mimeData
);
716 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
718 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
719 KJobWidgets::setWindow(job
, this);
721 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
722 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
723 KIO::FileUndoManager::self()->recordCopyJob(job
);
726 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
728 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
729 KJobWidgets::setWindow(job
, this);
731 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
732 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
733 KIO::FileUndoManager::self()->recordCopyJob(job
);
737 void DolphinView::paste()
742 void DolphinView::pasteIntoFolder()
744 const KFileItemList items
= selectedItems();
745 if ((items
.count() == 1) && items
.first().isDir()) {
746 pasteToUrl(items
.first().url());
750 void DolphinView::duplicateSelectedItems()
752 const KFileItemList itemList
= selectedItems();
753 if (itemList
.isEmpty()) {
757 const QMimeDatabase db
;
759 // Duplicate all selected items and append "copy" to the end of the file name
760 // but before the filename extension, if present
761 QList
<QUrl
> newSelection
;
762 for (const auto &item
: itemList
) {
763 const QUrl originalURL
= item
.url();
764 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
765 const QString originalFileName
= item
.name();
767 QString extension
= db
.suffixForFileName(originalFileName
);
769 QUrl duplicateURL
= originalURL
;
771 // No extension; new filename is "<oldfilename> copy"
772 if (extension
.isEmpty()) {
773 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
774 // There's an extension; new filename is "<oldfilename> copy.<extension>"
776 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
777 extension
= QLatin1String(".") + extension
;
778 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
779 // Preserve file's original filename extension in case the casing differs
780 // from what QMimeDatabase::suffixForFileName() returned
781 const QString originalExtension
= originalFileName
.right(extension
.size());
782 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
785 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
786 KJobWidgets::setWindow(job
, this);
789 newSelection
<< duplicateURL
;
790 KIO::FileUndoManager::self()->recordCopyJob(job
);
794 forceUrlsSelection(newSelection
.first(), newSelection
);
797 void DolphinView::stopLoading()
799 m_model
->cancelDirectoryLoading();
802 void DolphinView::updatePalette()
804 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
809 QWidget
* viewport
= m_container
->viewport();
812 palette
.setColor(viewport
->backgroundRole(), color
);
813 viewport
->setPalette(palette
);
819 void DolphinView::abortTwoClicksRenaming()
821 m_twoClicksRenamingItemUrl
.clear();
822 m_twoClicksRenamingTimer
->stop();
825 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
827 switch (event
->type()) {
828 case QEvent::PaletteChange
:
830 QPixmapCache::clear();
833 case QEvent::WindowActivate
:
834 case QEvent::WindowDeactivate
:
838 case QEvent::KeyPress
:
839 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
840 if (GeneralSettings::useTabForSwitchingSplitView()) {
841 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
842 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
843 Q_EMIT
toggleActiveViewRequested();
848 case QEvent::FocusIn
:
849 if (watched
== m_container
) {
854 case QEvent::GraphicsSceneDragEnter
:
855 if (watched
== m_view
) {
857 abortTwoClicksRenaming();
861 case QEvent::GraphicsSceneDragLeave
:
862 if (watched
== m_view
) {
867 case QEvent::GraphicsSceneDrop
:
868 if (watched
== m_view
) {
875 return QWidget::eventFilter(watched
, event
);
878 void DolphinView::wheelEvent(QWheelEvent
* event
)
880 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
881 const QPoint numDegrees
= event
->angleDelta() / 8;
882 const QPoint numSteps
= numDegrees
/ 15;
884 setZoomLevel(zoomLevel() + numSteps
.y());
891 void DolphinView::hideEvent(QHideEvent
* event
)
894 QWidget::hideEvent(event
);
897 bool DolphinView::event(QEvent
* event
)
899 if (event
->type() == QEvent::WindowDeactivate
) {
901 * Dolphin leaves file preview tooltips open even when is not visible.
903 * Hide tool-tip when Dolphin loses focus.
906 abortTwoClicksRenaming();
909 return QWidget::event(event
);
912 void DolphinView::activate()
917 void DolphinView::slotItemActivated(int index
)
919 abortTwoClicksRenaming();
921 const KFileItem item
= m_model
->fileItem(index
);
922 if (!item
.isNull()) {
923 Q_EMIT
itemActivated(item
);
927 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
929 Q_ASSERT(indexes
.count() >= 2);
931 abortTwoClicksRenaming();
933 if (indexes
.count() > 5) {
934 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
935 const int answer
= KMessageBox::warningYesNo(this, question
);
936 if (answer
!= KMessageBox::Yes
) {
942 items
.reserve(indexes
.count());
944 for (int index
: indexes
) {
945 KFileItem item
= m_model
->fileItem(index
);
946 const QUrl
& url
= openItemAsFolderUrl(item
);
948 if (!url
.isEmpty()) { // Open folders in new tabs
949 Q_EMIT
tabRequested(url
, DolphinTabWidget::AfterLastTab
);
955 if (items
.count() == 1) {
956 Q_EMIT
itemActivated(items
.first());
957 } else if (items
.count() > 1) {
958 Q_EMIT
itemsActivated(items
);
962 void DolphinView::slotItemMiddleClicked(int index
)
964 const KFileItem
& item
= m_model
->fileItem(index
);
965 const QUrl
& url
= openItemAsFolderUrl(item
);
966 if (!url
.isEmpty()) {
967 Q_EMIT
tabRequested(url
, DolphinTabWidget::AfterCurrentTab
);
968 } else if (isTabsForFilesEnabled()) {
969 Q_EMIT
tabRequested(item
.url(), DolphinTabWidget::AfterCurrentTab
);
973 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
975 // Force emit of a selection changed signal before we request the
976 // context menu, to update the edit-actions first. (See Bug 294013)
977 if (m_selectionChangedTimer
->isActive()) {
978 emitSelectionChangedSignal();
981 const KFileItem item
= m_model
->fileItem(index
);
982 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
985 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
987 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
990 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
992 ViewProperties
props(viewPropertiesUrl());
994 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
996 KItemListView
* view
= m_container
->controller()->view();
997 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
999 bool indexingEnabled
= false;
1001 Baloo::IndexerConfig config
;
1002 indexingEnabled
= config
.fileIndexingEnabled();
1006 QMenu
* groupMenu
= nullptr;
1008 // Add all roles to the menu that can be shown or hidden by the user
1009 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1010 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1011 if (info
.role
== "text") {
1012 // It should not be possible to hide the "text" role
1016 const QString text
= m_model
->roleDescription(info
.role
);
1017 QAction
* action
= nullptr;
1018 if (info
.group
.isEmpty()) {
1019 action
= menu
->addAction(text
);
1021 if (!groupMenu
|| info
.group
!= groupName
) {
1022 groupName
= info
.group
;
1023 groupMenu
= menu
->addMenu(groupName
);
1026 action
= groupMenu
->addAction(text
);
1029 action
->setCheckable(true);
1030 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1031 action
->setData(info
.role
);
1033 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1034 (info
.requiresBaloo
) ||
1035 (info
.requiresIndexer
&& indexingEnabled
);
1036 action
->setEnabled(enable
);
1039 menu
->addSeparator();
1041 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1042 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1044 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1045 autoAdjustWidthsAction
->setCheckable(true);
1046 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1047 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1049 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1050 customWidthsAction
->setCheckable(true);
1051 customWidthsAction
->setChecked(!autoColumnWidths
);
1052 customWidthsAction
->setActionGroup(widthsGroup
);
1054 QAction
* action
= menu
->exec(pos
.toPoint());
1055 if (menu
&& action
) {
1056 KItemListHeader
* header
= view
->header();
1058 if (action
== autoAdjustWidthsAction
) {
1059 // Clear the column-widths from the viewproperties and turn on
1060 // the automatic resizing of the columns
1061 props
.setHeaderColumnWidths(QList
<int>());
1062 header
->setAutomaticColumnResizing(true);
1063 } else if (action
== customWidthsAction
) {
1064 // Apply the current column-widths as custom column-widths and turn
1065 // off the automatic resizing of the columns
1066 QList
<int> columnWidths
;
1067 const auto visibleRoles
= view
->visibleRoles();
1068 columnWidths
.reserve(visibleRoles
.count());
1069 for (const QByteArray
& role
: visibleRoles
) {
1070 columnWidths
.append(header
->columnWidth(role
));
1072 props
.setHeaderColumnWidths(columnWidths
);
1073 header
->setAutomaticColumnResizing(false);
1075 // Show or hide the selected role
1076 const QByteArray selectedRole
= action
->data().toByteArray();
1078 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1079 if (action
->isChecked()) {
1080 visibleRoles
.append(selectedRole
);
1082 visibleRoles
.removeOne(selectedRole
);
1085 view
->setVisibleRoles(visibleRoles
);
1086 props
.setVisibleRoles(visibleRoles
);
1088 QList
<int> columnWidths
;
1089 if (!header
->automaticColumnResizing()) {
1090 const auto visibleRoles
= view
->visibleRoles();
1091 columnWidths
.reserve(visibleRoles
.count());
1092 for (const QByteArray
& role
: visibleRoles
) {
1093 columnWidths
.append(header
->columnWidth(role
));
1096 props
.setHeaderColumnWidths(columnWidths
);
1103 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1105 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1107 ViewProperties
props(viewPropertiesUrl());
1108 QList
<int> columnWidths
= props
.headerColumnWidths();
1109 if (columnWidths
.count() != visibleRoles
.count()) {
1110 columnWidths
.clear();
1111 columnWidths
.reserve(visibleRoles
.count());
1112 const KItemListHeader
* header
= m_view
->header();
1113 for (const QByteArray
& role
: visibleRoles
) {
1114 const int width
= header
->columnWidth(role
);
1115 columnWidths
.append(width
);
1119 const int roleIndex
= visibleRoles
.indexOf(role
);
1120 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1121 columnWidths
[roleIndex
] = current
;
1123 props
.setHeaderColumnWidths(columnWidths
);
1126 void DolphinView::slotItemHovered(int index
)
1128 const KFileItem item
= m_model
->fileItem(index
);
1130 if (GeneralSettings::showToolTips() && !m_dragging
) {
1131 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1132 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1133 itemRect
.moveTo(pos
);
1136 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1140 Q_EMIT
requestItemInfo(item
);
1143 void DolphinView::slotItemUnhovered(int index
)
1147 Q_EMIT
requestItemInfo(KFileItem());
1150 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1153 KFileItem destItem
= m_model
->fileItem(index
);
1154 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1155 // Use the URL of the view as drop target if the item is no directory
1157 destItem
= m_model
->rootItem();
1160 // The item represents a directory or desktop-file
1161 destUrl
= destItem
.mostLocalUrl();
1164 QDropEvent
dropEvent(event
->pos().toPoint(),
1165 event
->possibleActions(),
1168 event
->modifiers());
1169 dropUrls(destUrl
, &dropEvent
, this);
1174 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1176 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1179 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1181 if (destUrl
== url()) {
1182 // Mark the dropped urls as selected.
1183 m_clearSelectionBeforeSelectingNewItems
= true;
1184 m_markFirstNewlySelectedItemAsCurrent
= true;
1185 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1190 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1192 if (previous
!= nullptr) {
1193 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1194 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1195 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1196 m_versionControlObserver
->setModel(nullptr);
1200 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1201 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1202 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1203 m_versionControlObserver
->setModel(fileItemModel
);
1207 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1213 if (buttons
& Qt::BackButton
) {
1214 Q_EMIT
goBackRequested();
1215 } else if (buttons
& Qt::ForwardButton
) {
1216 Q_EMIT
goForwardRequested();
1220 void DolphinView::slotSelectedItemTextPressed(int index
)
1222 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1223 const KFileItem item
= m_model
->fileItem(index
);
1224 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1225 if (capabilities
.supportsMoving()) {
1226 m_twoClicksRenamingItemUrl
= item
.url();
1227 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1232 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1234 slotItemCreated(to
);
1237 void DolphinView::slotItemCreated(const QUrl
& url
)
1239 if (m_markFirstNewlySelectedItemAsCurrent
) {
1240 markUrlAsCurrent(url
);
1241 m_markFirstNewlySelectedItemAsCurrent
= false;
1243 m_selectedUrls
<< url
;
1246 void DolphinView::slotJobResult(KJob
*job
)
1249 Q_EMIT
errorMessage(job
->errorString());
1251 if (!m_selectedUrls
.isEmpty()) {
1252 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1256 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1258 const int currentCount
= current
.count();
1259 const int previousCount
= previous
.count();
1260 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1261 (currentCount
> 0 && previousCount
== 0);
1263 // If nothing has been selected before and something got selected (or if something
1264 // was selected before and now nothing is selected) the selectionChangedSignal must
1265 // be emitted asynchronously as fast as possible to update the edit-actions.
1266 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1267 m_selectionChangedTimer
->start();
1270 void DolphinView::emitSelectionChangedSignal()
1272 m_selectionChangedTimer
->stop();
1273 Q_EMIT
selectionChanged(selectedItems());
1276 void DolphinView::updateSortRole(const QByteArray
& role
)
1278 ViewProperties
props(viewPropertiesUrl());
1279 props
.setSortRole(role
);
1281 KItemModelBase
* model
= m_container
->controller()->model();
1282 model
->setSortRole(role
);
1284 Q_EMIT
sortRoleChanged(role
);
1287 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1289 ViewProperties
props(viewPropertiesUrl());
1290 props
.setSortOrder(order
);
1292 m_model
->setSortOrder(order
);
1294 Q_EMIT
sortOrderChanged(order
);
1297 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1299 ViewProperties
props(viewPropertiesUrl());
1300 props
.setSortFoldersFirst(foldersFirst
);
1302 m_model
->setSortDirectoriesFirst(foldersFirst
);
1304 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1307 QPair
<bool, QString
> DolphinView::pasteInfo() const
1309 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1310 QPair
<bool, QString
> info
;
1311 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1315 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1317 m_tabsForFiles
= tabsForFiles
;
1320 bool DolphinView::isTabsForFilesEnabled() const
1322 return m_tabsForFiles
;
1325 bool DolphinView::itemsExpandable() const
1327 return m_mode
== DetailsView
;
1330 void DolphinView::restoreState(QDataStream
& stream
)
1332 // Read the version number of the view state and check if the version is supported.
1333 quint32 version
= 0;
1336 // The version of the view state isn't supported, we can't restore it.
1340 // Restore the current item that had the keyboard focus
1341 stream
>> m_currentItemUrl
;
1343 // Restore the previously selected items
1344 stream
>> m_selectedUrls
;
1346 // Restore the view position
1347 stream
>> m_restoredContentsPosition
;
1349 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1352 m_model
->restoreExpandedDirectories(urls
);
1355 void DolphinView::saveState(QDataStream
& stream
)
1357 stream
<< quint32(1); // View state version
1359 // Save the current item that has the keyboard focus
1360 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1361 if (currentIndex
!= -1) {
1362 KFileItem item
= m_model
->fileItem(currentIndex
);
1363 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1364 QUrl currentItemUrl
= item
.url();
1365 stream
<< currentItemUrl
;
1370 // Save the selected urls
1371 stream
<< selectedItems().urlList();
1373 // Save view position
1374 const qreal x
= m_container
->horizontalScrollBar()->value();
1375 const qreal y
= m_container
->verticalScrollBar()->value();
1376 stream
<< QPoint(x
, y
);
1378 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1379 stream
<< m_model
->expandedDirectories();
1382 KFileItem
DolphinView::rootItem() const
1384 return m_model
->rootItem();
1387 void DolphinView::setViewPropertiesContext(const QString
& context
)
1389 m_viewPropertiesContext
= context
;
1392 QString
DolphinView::viewPropertiesContext() const
1394 return m_viewPropertiesContext
;
1397 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1399 if (item
.isNull()) {
1403 QUrl url
= item
.targetUrl();
1409 if (item
.isMimeTypeKnown()) {
1410 const QString
& mimetype
= item
.mimetype();
1412 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1413 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1414 // zip:/<path>/ when clicking on a zip file, etc.
1415 // The .protocol file specifies the mimetype that the kioslave handles.
1416 // Note that we don't use mimetype inheritance since we don't want to
1417 // open OpenDocument files as zip folders...
1418 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1419 if (!protocol
.isEmpty()) {
1420 url
.setScheme(protocol
);
1425 if (mimetype
== QLatin1String("application/x-desktop")) {
1426 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1427 KDesktopFile
desktopFile(url
.toLocalFile());
1428 if (desktopFile
.hasLinkType()) {
1429 const QString linkUrl
= desktopFile
.readUrl();
1430 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1431 return QUrl::fromUserInput(linkUrl
);
1440 void DolphinView::resetZoomLevel()
1442 ViewModeSettings::ViewMode mode
;
1445 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1446 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1447 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1449 const ViewModeSettings
settings(mode
);
1450 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1451 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1454 void DolphinView::observeCreatedItem(const QUrl
& url
)
1457 forceUrlsSelection(url
, {url
});
1461 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1463 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1464 Q_EMIT
redirection(oldUrl
, newUrl
);
1465 m_url
= newUrl
; // #186947
1469 void DolphinView::updateViewState()
1471 if (m_currentItemUrl
!= QUrl()) {
1472 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1474 // if there is a selection already, leave it that way
1475 if (!selectionManager
->hasSelection()) {
1476 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1477 if (currentIndex
!= -1) {
1478 selectionManager
->setCurrentItem(currentIndex
);
1480 // scroll to current item and reset the state
1481 if (m_scrollToCurrentItem
) {
1482 m_view
->scrollToItem(currentIndex
);
1483 m_scrollToCurrentItem
= false;
1486 selectionManager
->setCurrentItem(0);
1490 m_currentItemUrl
= QUrl();
1493 if (!m_restoredContentsPosition
.isNull()) {
1494 const int x
= m_restoredContentsPosition
.x();
1495 const int y
= m_restoredContentsPosition
.y();
1496 m_restoredContentsPosition
= QPoint();
1498 m_container
->horizontalScrollBar()->setValue(x
);
1499 m_container
->verticalScrollBar()->setValue(y
);
1502 if (!m_selectedUrls
.isEmpty()) {
1503 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1505 // if there is a selection already, leave it that way
1506 if (!selectionManager
->hasSelection()) {
1507 if (m_clearSelectionBeforeSelectingNewItems
) {
1508 selectionManager
->clearSelection();
1509 m_clearSelectionBeforeSelectingNewItems
= false;
1512 KItemSet selectedItems
= selectionManager
->selectedItems();
1514 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1515 while (it
!= m_selectedUrls
.end()) {
1516 const int index
= m_model
->index(*it
);
1518 selectedItems
.insert(index
);
1519 it
= m_selectedUrls
.erase(it
);
1525 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1526 selectionManager
->setSelectedItems(selectedItems
);
1531 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1534 if (GeneralSettings::showToolTips()) {
1535 m_toolTipManager
->hideToolTip(behavior
);
1542 void DolphinView::calculateItemCount(int& fileCount
,
1544 KIO::filesize_t
& totalFileSize
) const
1546 const int itemCount
= m_model
->count();
1548 bool countFileSize
= true;
1550 if (!m_model
->rootItem().url().isValid()) {
1554 // In case we have a precomputed value
1555 const auto job
= KIO::statDetails(m_model
->rootItem().url(), KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
1557 const auto entry
= job
->statResult();
1558 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1559 totalFileSize
= static_cast<KIO::filesize_t
>(entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1560 countFileSize
= false;
1563 for (int i
= 0; i
< itemCount
; ++i
) {
1564 const KFileItem item
= m_model
->fileItem(i
);
1569 if (countFileSize
) {
1570 totalFileSize
+= item
.size();
1576 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1578 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1580 // verify that only one item is selected
1581 if (selectionManager
->selectedItems().count() == 1) {
1582 const int index
= selectionManager
->currentItem();
1583 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1585 // check if the selected item was the same item that started the twoClicksRenaming
1586 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1587 renameSelectedItems();
1592 void DolphinView::slotTrashFileFinished(KJob
* job
)
1594 if (job
->error() == 0) {
1595 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1596 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1597 Q_EMIT
errorMessage(job
->errorString());
1601 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1603 if (job
->error() == 0) {
1604 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1605 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1606 Q_EMIT
errorMessage(job
->errorString());
1610 void DolphinView::slotRenamingResult(KJob
* job
)
1613 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1615 const QUrl newUrl
= copyJob
->destUrl();
1616 const int index
= m_model
->index(newUrl
);
1618 QHash
<QByteArray
, QVariant
> data
;
1619 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1620 data
.insert("text", oldUrl
.fileName());
1621 m_model
->setData(index
, data
);
1626 void DolphinView::slotDirectoryLoadingStarted()
1628 // We don't want the placeholder label to flicker while the folder is loading
1629 m_placeholderLabel
->setVisible(false);
1631 // Disable the writestate temporary until it can be determined in a fast way
1632 // in DolphinView::slotDirectoryLoadingCompleted()
1633 if (m_isFolderWritable
) {
1634 m_isFolderWritable
= false;
1635 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1638 Q_EMIT
directoryLoadingStarted();
1641 void DolphinView::slotDirectoryLoadingCompleted()
1643 // Update the view-state. This has to be done asynchronously
1644 // because the view might not be in its final state yet.
1645 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1647 // Update the placeholder label in case we found that the folder was empty
1650 Q_EMIT
directoryLoadingCompleted();
1652 updatePlaceholderLabel();
1653 updateWritableState();
1656 void DolphinView::slotItemsChanged()
1658 m_assureVisibleCurrentIndex
= false;
1661 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1664 Q_ASSERT(m_model
->sortOrder() == current
);
1666 ViewProperties
props(viewPropertiesUrl());
1667 props
.setSortOrder(current
);
1669 Q_EMIT
sortOrderChanged(current
);
1672 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1675 Q_ASSERT(m_model
->sortRole() == current
);
1677 ViewProperties
props(viewPropertiesUrl());
1678 props
.setSortRole(current
);
1680 Q_EMIT
sortRoleChanged(current
);
1683 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1684 const QList
<QByteArray
>& previous
)
1687 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1689 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1691 m_visibleRoles
= current
;
1693 ViewProperties
props(viewPropertiesUrl());
1694 props
.setVisibleRoles(m_visibleRoles
);
1696 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1699 void DolphinView::slotRoleEditingCanceled()
1701 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1702 this, &DolphinView::slotRoleEditingFinished
);
1705 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1707 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1708 this, &DolphinView::slotRoleEditingFinished
);
1710 if (index
< 0 || index
>= m_model
->count()) {
1714 if (role
== "text") {
1715 const KFileItem oldItem
= m_model
->fileItem(index
);
1716 const QString newName
= value
.toString();
1717 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1718 const QUrl oldUrl
= oldItem
.url();
1720 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1721 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1724 //Confirm hiding file/directory by renaming inline
1725 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1726 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1727 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1729 const auto code
= KMessageBox::questionYesNo(this,
1730 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1731 "Do you still want to rename it?")
1732 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1733 "Do you still want to rename it?"),
1734 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1736 KStandardGuiItem::cancel(),
1737 QStringLiteral("ConfirmHide")
1740 if (code
== KMessageBox::No
) {
1746 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1747 if (!newNameExistsAlready
) {
1748 // Only change the data in the model if no item with the new name
1749 // is in the model yet. If there is an item with the new name
1750 // already, calling KIO::CopyJob will open a dialog
1751 // asking for a new name, and KFileItemModel will update the
1752 // data when the dir lister signals that the file name has changed.
1753 QHash
<QByteArray
, QVariant
> data
;
1754 data
.insert(role
, value
);
1755 m_model
->setData(index
, data
);
1758 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1759 KJobWidgets::setWindow(job
, this);
1760 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1761 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1763 forceUrlsSelection(newUrl
, {newUrl
});
1765 if (!newNameExistsAlready
) {
1766 // Only connect the result signal if there is no item with the new name
1767 // in the model yet, see bug 328262.
1768 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1774 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1776 if (!url
.isValid()) {
1777 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1778 if (location
.isEmpty()) {
1779 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1781 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1787 m_model
->refreshDirectory(url
);
1789 m_model
->loadDirectory(url
);
1793 void DolphinView::applyViewProperties()
1795 const ViewProperties
props(viewPropertiesUrl());
1796 applyViewProperties(props
);
1799 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1801 m_view
->beginTransaction();
1803 const Mode mode
= props
.viewMode();
1804 if (m_mode
!= mode
) {
1805 const Mode previousMode
= m_mode
;
1808 // Changing the mode might result in changing
1809 // the zoom level. Remember the old zoom level so
1810 // that zoomLevelChanged() can get emitted.
1811 const int oldZoomLevel
= m_view
->zoomLevel();
1814 Q_EMIT
modeChanged(m_mode
, previousMode
);
1816 if (m_view
->zoomLevel() != oldZoomLevel
) {
1817 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1821 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1822 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1823 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1824 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1827 const bool groupedSorting
= props
.groupedSorting();
1828 if (groupedSorting
!= m_model
->groupedSorting()) {
1829 m_model
->setGroupedSorting(groupedSorting
);
1830 Q_EMIT
groupedSortingChanged(groupedSorting
);
1833 const QByteArray sortRole
= props
.sortRole();
1834 if (sortRole
!= m_model
->sortRole()) {
1835 m_model
->setSortRole(sortRole
);
1836 Q_EMIT
sortRoleChanged(sortRole
);
1839 const Qt::SortOrder sortOrder
= props
.sortOrder();
1840 if (sortOrder
!= m_model
->sortOrder()) {
1841 m_model
->setSortOrder(sortOrder
);
1842 Q_EMIT
sortOrderChanged(sortOrder
);
1845 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1846 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1847 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1848 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1851 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1852 if (visibleRoles
!= m_visibleRoles
) {
1853 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1854 m_visibleRoles
= visibleRoles
;
1855 m_view
->setVisibleRoles(visibleRoles
);
1856 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1859 const bool previewsShown
= props
.previewsShown();
1860 if (previewsShown
!= m_view
->previewsShown()) {
1861 const int oldZoomLevel
= zoomLevel();
1863 m_view
->setPreviewsShown(previewsShown
);
1864 Q_EMIT
previewsShownChanged(previewsShown
);
1866 // Changing the preview-state might result in a changed zoom-level
1867 if (oldZoomLevel
!= zoomLevel()) {
1868 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1872 KItemListView
* itemListView
= m_container
->controller()->view();
1873 if (itemListView
->isHeaderVisible()) {
1874 KItemListHeader
* header
= itemListView
->header();
1875 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1876 const int rolesCount
= m_visibleRoles
.count();
1877 if (headerColumnWidths
.count() == rolesCount
) {
1878 header
->setAutomaticColumnResizing(false);
1880 QHash
<QByteArray
, qreal
> columnWidths
;
1881 for (int i
= 0; i
< rolesCount
; ++i
) {
1882 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1884 header
->setColumnWidths(columnWidths
);
1886 header
->setAutomaticColumnResizing(true);
1890 m_view
->endTransaction();
1893 void DolphinView::applyModeToView()
1896 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1897 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1898 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1899 default: Q_ASSERT(false); break;
1903 void DolphinView::pasteToUrl(const QUrl
& url
)
1905 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1906 KJobWidgets::setWindow(job
, this);
1907 m_clearSelectionBeforeSelectingNewItems
= true;
1908 m_markFirstNewlySelectedItemAsCurrent
= true;
1909 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1910 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1913 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1917 const KFileItemList items
= selectedItems();
1918 urls
.reserve(items
.count());
1919 for (const KFileItem
& item
: items
) {
1920 urls
.append(item
.url());
1923 if (itemsExpandable()) {
1924 // TODO: Check if we still need KDirModel for this in KDE 5.0
1925 urls
= KDirModel::simplifiedUrlList(urls
);
1931 QMimeData
* DolphinView::selectionMimeData() const
1933 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1934 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1936 return m_model
->createMimeData(selectedIndexes
);
1939 void DolphinView::updateWritableState()
1941 const bool wasFolderWritable
= m_isFolderWritable
;
1942 m_isFolderWritable
= false;
1944 KFileItem item
= m_model
->rootItem();
1945 if (item
.isNull()) {
1946 // Try to find out if the URL is writable even if the "root item" is
1947 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1948 item
= KFileItem(url());
1949 item
.setDelayedMimeTypes(true);
1952 KFileItemListProperties
capabilities(KFileItemList() << item
);
1953 m_isFolderWritable
= capabilities
.supportsWriting();
1955 if (m_isFolderWritable
!= wasFolderWritable
) {
1956 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1960 QUrl
DolphinView::viewPropertiesUrl() const
1962 if (m_viewPropertiesContext
.isEmpty()) {
1967 url
.setScheme(m_url
.scheme());
1968 url
.setPath(m_viewPropertiesContext
);
1972 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
1974 forceUrlsSelection(urls
.first(), urls
);
1977 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
1980 m_clearSelectionBeforeSelectingNewItems
= true;
1981 markUrlAsCurrent(current
);
1982 markUrlsAsSelected(selected
);
1985 void DolphinView::copyPathToClipboard()
1987 const KFileItemList list
= selectedItems();
1988 if (list
.isEmpty()) {
1991 const KFileItem
& item
= list
.at(0);
1992 QString path
= item
.localPath();
1993 if (path
.isEmpty()) {
1994 path
= item
.url().toDisplayString();
1996 QClipboard
* clipboard
= QApplication::clipboard();
1997 if (clipboard
== nullptr) {
2000 clipboard
->setText(path
);
2003 void DolphinView::slotIncreaseZoom()
2005 setZoomLevel(zoomLevel() + 1);
2008 void DolphinView::slotDecreaseZoom()
2010 setZoomLevel(zoomLevel() - 1);
2013 void DolphinView::slotSwipeUp()
2015 Q_EMIT
goUpRequested();
2018 void DolphinView::updatePlaceholderLabel()
2020 if (itemsCount() > 0) {
2021 m_placeholderLabel
->setVisible(false);
2025 if (!nameFilter().isEmpty()) {
2026 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2027 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2028 m_placeholderLabel
->setText(i18n("No items matching the search"));
2029 } else if (m_url
.scheme() == QLatin1String("trash")) {
2030 m_placeholderLabel
->setText(i18n("Trash is empty"));
2031 } else if (m_url
.scheme() == QLatin1String("tags")) {
2032 m_placeholderLabel
->setText(i18n("No tags"));
2033 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2034 m_placeholderLabel
->setText(i18n("No recently used items"));
2035 } else if (m_url
.scheme() == QLatin1String("smb")) {
2036 m_placeholderLabel
->setText(i18n("No shared folders found"));
2037 } else if (m_url
.scheme() == QLatin1String("network")) {
2038 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2039 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2040 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2041 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2042 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2044 m_placeholderLabel
->setText(i18n("Folder is empty"));
2047 m_placeholderLabel
->setVisible(true);