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
);
182 connect(m_model
, &KFileItemModel::fileItemsChanged
, this, &DolphinView::fileItemsChanged
);
184 connect(this, &DolphinView::itemCountChanged
,
185 this, &DolphinView::updatePlaceholderLabel
);
187 m_view
->installEventFilter(this);
188 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
189 this, &DolphinView::slotSortOrderChangedByHeader
);
190 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
191 this, &DolphinView::slotSortRoleChangedByHeader
);
192 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
193 this, &DolphinView::slotVisibleRolesChangedByHeader
);
194 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
195 this, &DolphinView::slotRoleEditingCanceled
);
196 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
197 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
199 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
200 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
201 this, &DolphinView::slotSelectionChanged
);
204 m_toolTipManager
= new ToolTipManager(this);
205 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
208 m_versionControlObserver
= new VersionControlObserver(this);
209 m_versionControlObserver
->setView(this);
210 m_versionControlObserver
->setModel(m_model
);
211 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
212 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
213 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
215 m_twoClicksRenamingTimer
= new QTimer(this);
216 m_twoClicksRenamingTimer
->setSingleShot(true);
217 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
219 applyViewProperties();
220 m_topLayout
->addWidget(m_container
);
225 DolphinView::~DolphinView()
229 QUrl
DolphinView::url() const
234 void DolphinView::setActive(bool active
)
236 if (active
== m_active
) {
245 m_container
->setFocus();
247 Q_EMIT
writeStateChanged(m_isFolderWritable
);
251 bool DolphinView::isActive() const
256 void DolphinView::setMode(Mode mode
)
258 if (mode
!= m_mode
) {
259 ViewProperties
props(viewPropertiesUrl());
260 props
.setViewMode(mode
);
262 // We pass the new ViewProperties to applyViewProperties, rather than
263 // storing them on disk and letting applyViewProperties() read them
264 // from there, to prevent that changing the view mode fails if the
265 // .directory file is not writable (see bug 318534).
266 applyViewProperties(props
);
270 DolphinView::Mode
DolphinView::mode() const
275 void DolphinView::setPreviewsShown(bool show
)
277 if (previewsShown() == show
) {
281 ViewProperties
props(viewPropertiesUrl());
282 props
.setPreviewsShown(show
);
284 const int oldZoomLevel
= m_view
->zoomLevel();
285 m_view
->setPreviewsShown(show
);
286 Q_EMIT
previewsShownChanged(show
);
288 const int newZoomLevel
= m_view
->zoomLevel();
289 if (newZoomLevel
!= oldZoomLevel
) {
290 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
294 bool DolphinView::previewsShown() const
296 return m_view
->previewsShown();
299 void DolphinView::setHiddenFilesShown(bool show
)
301 if (m_model
->showHiddenFiles() == show
) {
305 const KFileItemList itemList
= selectedItems();
306 m_selectedUrls
.clear();
307 m_selectedUrls
= itemList
.urlList();
309 ViewProperties
props(viewPropertiesUrl());
310 props
.setHiddenFilesShown(show
);
312 m_model
->setShowHiddenFiles(show
);
313 Q_EMIT
hiddenFilesShownChanged(show
);
316 bool DolphinView::hiddenFilesShown() const
318 return m_model
->showHiddenFiles();
321 void DolphinView::setGroupedSorting(bool grouped
)
323 if (grouped
== groupedSorting()) {
327 ViewProperties
props(viewPropertiesUrl());
328 props
.setGroupedSorting(grouped
);
331 m_container
->controller()->model()->setGroupedSorting(grouped
);
333 Q_EMIT
groupedSortingChanged(grouped
);
336 bool DolphinView::groupedSorting() const
338 return m_model
->groupedSorting();
341 KFileItemList
DolphinView::items() const
344 const int itemCount
= m_model
->count();
345 list
.reserve(itemCount
);
347 for (int i
= 0; i
< itemCount
; ++i
) {
348 list
.append(m_model
->fileItem(i
));
354 int DolphinView::itemsCount() const
356 return m_model
->count();
359 KFileItemList
DolphinView::selectedItems() const
361 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
363 KFileItemList selectedItems
;
364 const auto items
= selectionManager
->selectedItems();
365 selectedItems
.reserve(items
.count());
366 for (int index
: items
) {
367 selectedItems
.append(m_model
->fileItem(index
));
369 return selectedItems
;
372 int DolphinView::selectedItemsCount() const
374 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
375 return selectionManager
->selectedItems().count();
378 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
380 m_selectedUrls
= urls
;
383 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
385 m_currentItemUrl
= url
;
386 m_scrollToCurrentItem
= true;
389 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
391 const KItemListSelectionManager::SelectionMode mode
= enabled
392 ? KItemListSelectionManager::Select
393 : KItemListSelectionManager::Deselect
;
394 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
396 for (int index
= 0; index
< m_model
->count(); index
++) {
397 const KFileItem item
= m_model
->fileItem(index
);
398 if (regexp
.match(item
.text()).hasMatch()) {
399 // An alternative approach would be to store the matching items in a KItemSet and
400 // select them in one go after the loop, but we'd need a new function
401 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
403 selectionManager
->setSelected(index
, 1, mode
);
408 void DolphinView::setZoomLevel(int level
)
410 const int oldZoomLevel
= zoomLevel();
411 m_view
->setZoomLevel(level
);
412 if (zoomLevel() != oldZoomLevel
) {
414 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
418 int DolphinView::zoomLevel() const
420 return m_view
->zoomLevel();
423 void DolphinView::setSortRole(const QByteArray
& role
)
425 if (role
!= sortRole()) {
426 updateSortRole(role
);
430 QByteArray
DolphinView::sortRole() const
432 const KItemModelBase
* model
= m_container
->controller()->model();
433 return model
->sortRole();
436 void DolphinView::setSortOrder(Qt::SortOrder order
)
438 if (sortOrder() != order
) {
439 updateSortOrder(order
);
443 Qt::SortOrder
DolphinView::sortOrder() const
445 return m_model
->sortOrder();
448 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
450 if (sortFoldersFirst() != foldersFirst
) {
451 updateSortFoldersFirst(foldersFirst
);
455 bool DolphinView::sortFoldersFirst() const
457 return m_model
->sortDirectoriesFirst();
460 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
462 const QList
<QByteArray
> previousRoles
= roles
;
464 ViewProperties
props(viewPropertiesUrl());
465 props
.setVisibleRoles(roles
);
467 m_visibleRoles
= roles
;
468 m_view
->setVisibleRoles(roles
);
470 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
473 QList
<QByteArray
> DolphinView::visibleRoles() const
475 return m_visibleRoles
;
478 void DolphinView::reload()
480 QByteArray viewState
;
481 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
482 saveState(saveStream
);
485 loadDirectory(url(), true);
487 QDataStream
restoreStream(viewState
);
488 restoreState(restoreStream
);
491 void DolphinView::readSettings()
493 const int oldZoomLevel
= m_view
->zoomLevel();
495 GeneralSettings::self()->load();
496 m_view
->readSettings();
497 applyViewProperties();
499 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
500 m_container
->controller()->setAutoActivationDelay(delay
);
502 const int newZoomLevel
= m_view
->zoomLevel();
503 if (newZoomLevel
!= oldZoomLevel
) {
504 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
508 void DolphinView::writeSettings()
510 GeneralSettings::self()->save();
511 m_view
->writeSettings();
514 void DolphinView::setNameFilter(const QString
& nameFilter
)
516 m_model
->setNameFilter(nameFilter
);
519 QString
DolphinView::nameFilter() const
521 return m_model
->nameFilter();
524 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
526 return m_model
->setMimeTypeFilters(filters
);
529 QStringList
DolphinView::mimeTypeFilters() const
531 return m_model
->mimeTypeFilters();
534 void DolphinView::requestStatusBarText()
536 if (m_statJobForStatusBarText
) {
537 // Kill the pending request.
538 m_statJobForStatusBarText
->kill();
541 if (m_container
->controller()->selectionManager()->hasSelection()) {
544 KIO::filesize_t totalFileSize
= 0;
546 // Give a summary of the status of the selected files
547 const KFileItemList list
= selectedItems();
548 for (const KFileItem
& item
: list
) {
553 totalFileSize
+= item
.size();
557 if (folderCount
+ fileCount
== 1) {
558 // If only one item is selected, show info about it
559 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
561 // At least 2 items are selected
562 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
564 } else { // has no selection
565 if (!m_model
->rootItem().url().isValid()) {
569 m_statJobForStatusBarText
= KIO::statDetails(m_model
->rootItem().url(),
570 KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
571 connect(m_statJobForStatusBarText
, &KJob::result
,
572 this, &DolphinView::slotStatJobResult
);
573 m_statJobForStatusBarText
->start();
577 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
,
578 KIO::filesize_t totalFileSize
, const Selection selection
)
584 if (selection
== HasSelection
) {
585 // At least 2 items are selected because the case of 1 selected item is handled in
586 // DolphinView::requestStatusBarText().
587 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
588 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
590 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
591 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
594 if (fileCount
> 0 && folderCount
> 0) {
595 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
596 foldersText
, filesText
,
597 KFormat().formatByteSize(totalFileSize
));
598 } else if (fileCount
> 0) {
599 summary
= i18nc("@info:status files (size)", "%1 (%2)",
601 KFormat().formatByteSize(totalFileSize
));
602 } else if (folderCount
> 0) {
603 summary
= foldersText
;
605 summary
= i18nc("@info:status", "0 Folders, 0 Files");
607 Q_EMIT
statusBarTextChanged(summary
);
610 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
612 QList
<QAction
*> actions
;
614 if (items
.isEmpty()) {
615 const KFileItem item
= m_model
->rootItem();
616 if (!item
.isNull()) {
617 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
620 actions
= m_versionControlObserver
->actions(items
);
626 void DolphinView::setUrl(const QUrl
& url
)
638 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
639 this, &DolphinView::slotRoleEditingFinished
);
641 // It is important to clear the items from the model before
642 // applying the view properties, otherwise expensive operations
643 // might be done on the existing items although they get cleared
644 // anyhow afterwards by loadDirectory().
646 applyViewProperties();
649 Q_EMIT
urlChanged(url
);
652 void DolphinView::selectAll()
654 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
655 selectionManager
->setSelected(0, m_model
->count());
658 void DolphinView::invertSelection()
660 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
661 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
664 void DolphinView::clearSelection()
666 m_selectedUrls
.clear();
667 m_container
->controller()->selectionManager()->clearSelection();
670 void DolphinView::renameSelectedItems()
672 const KFileItemList items
= selectedItems();
673 if (items
.isEmpty()) {
677 if (items
.count() == 1 && GeneralSettings::renameInline()) {
678 const int index
= m_model
->index(items
.first());
680 QMetaObject::Connection
* const connection
= new QMetaObject::Connection
;
681 *connection
= connect(m_view
, &KItemListView::scrollingStopped
, this, [=](){
682 QObject::disconnect(*connection
);
685 m_view
->editRole(index
, "text");
689 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
690 this, &DolphinView::slotRoleEditingFinished
);
692 m_view
->scrollToItem(index
);
695 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
696 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
697 this, &DolphinView::slotRenameDialogRenamingFinished
);
702 // Assure that the current index remains visible when KFileItemModel
703 // will notify the view about changed items (which might result in
704 // a changed sorting).
705 m_assureVisibleCurrentIndex
= true;
708 void DolphinView::trashSelectedItems()
710 const QList
<QUrl
> list
= simplifiedSelectedUrls();
711 KIO::JobUiDelegate uiDelegate
;
712 uiDelegate
.setWindow(window());
713 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
714 KIO::Job
* job
= KIO::trash(list
);
715 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
716 KJobWidgets::setWindow(job
, this);
717 connect(job
, &KIO::Job::result
,
718 this, &DolphinView::slotTrashFileFinished
);
722 void DolphinView::deleteSelectedItems()
724 const QList
<QUrl
> list
= simplifiedSelectedUrls();
726 KIO::JobUiDelegate uiDelegate
;
727 uiDelegate
.setWindow(window());
728 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
729 KIO::Job
* job
= KIO::del(list
);
730 KJobWidgets::setWindow(job
, this);
731 connect(job
, &KIO::Job::result
,
732 this, &DolphinView::slotDeleteFileFinished
);
736 void DolphinView::cutSelectedItemsToClipboard()
738 QMimeData
* mimeData
= selectionMimeData();
739 KIO::setClipboardDataCut(mimeData
, true);
740 QApplication::clipboard()->setMimeData(mimeData
);
743 void DolphinView::copySelectedItemsToClipboard()
745 QMimeData
* mimeData
= selectionMimeData();
746 QApplication::clipboard()->setMimeData(mimeData
);
749 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
751 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
752 KJobWidgets::setWindow(job
, this);
754 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
755 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
756 KIO::FileUndoManager::self()->recordCopyJob(job
);
759 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
761 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
762 KJobWidgets::setWindow(job
, this);
764 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
765 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
766 KIO::FileUndoManager::self()->recordCopyJob(job
);
770 void DolphinView::paste()
775 void DolphinView::pasteIntoFolder()
777 const KFileItemList items
= selectedItems();
778 if ((items
.count() == 1) && items
.first().isDir()) {
779 pasteToUrl(items
.first().url());
783 void DolphinView::duplicateSelectedItems()
785 const KFileItemList itemList
= selectedItems();
786 if (itemList
.isEmpty()) {
790 const QMimeDatabase db
;
792 // Duplicate all selected items and append "copy" to the end of the file name
793 // but before the filename extension, if present
794 QList
<QUrl
> newSelection
;
795 for (const auto &item
: itemList
) {
796 const QUrl originalURL
= item
.url();
797 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
798 const QString originalFileName
= item
.name();
800 QString extension
= db
.suffixForFileName(originalFileName
);
802 QUrl duplicateURL
= originalURL
;
804 // No extension; new filename is "<oldfilename> copy"
805 if (extension
.isEmpty()) {
806 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
807 // There's an extension; new filename is "<oldfilename> copy.<extension>"
809 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
810 extension
= QLatin1String(".") + extension
;
811 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
812 // Preserve file's original filename extension in case the casing differs
813 // from what QMimeDatabase::suffixForFileName() returned
814 const QString originalExtension
= originalFileName
.right(extension
.size());
815 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
818 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
819 KJobWidgets::setWindow(job
, this);
822 newSelection
<< duplicateURL
;
823 KIO::FileUndoManager::self()->recordCopyJob(job
);
827 forceUrlsSelection(newSelection
.first(), newSelection
);
830 void DolphinView::stopLoading()
832 m_model
->cancelDirectoryLoading();
835 void DolphinView::updatePalette()
837 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
842 QWidget
* viewport
= m_container
->viewport();
845 palette
.setColor(viewport
->backgroundRole(), color
);
846 viewport
->setPalette(palette
);
852 void DolphinView::abortTwoClicksRenaming()
854 m_twoClicksRenamingItemUrl
.clear();
855 m_twoClicksRenamingTimer
->stop();
858 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
860 switch (event
->type()) {
861 case QEvent::PaletteChange
:
863 QPixmapCache::clear();
866 case QEvent::WindowActivate
:
867 case QEvent::WindowDeactivate
:
871 case QEvent::KeyPress
:
872 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
873 if (GeneralSettings::useTabForSwitchingSplitView()) {
874 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
875 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
876 Q_EMIT
toggleActiveViewRequested();
881 case QEvent::FocusIn
:
882 if (watched
== m_container
) {
887 case QEvent::GraphicsSceneDragEnter
:
888 if (watched
== m_view
) {
890 abortTwoClicksRenaming();
894 case QEvent::GraphicsSceneDragLeave
:
895 if (watched
== m_view
) {
900 case QEvent::GraphicsSceneDrop
:
901 if (watched
== m_view
) {
908 return QWidget::eventFilter(watched
, event
);
911 void DolphinView::wheelEvent(QWheelEvent
* event
)
913 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
914 const QPoint numDegrees
= event
->angleDelta() / 8;
915 const QPoint numSteps
= numDegrees
/ 15;
917 setZoomLevel(zoomLevel() + numSteps
.y());
924 void DolphinView::hideEvent(QHideEvent
* event
)
927 QWidget::hideEvent(event
);
930 bool DolphinView::event(QEvent
* event
)
932 if (event
->type() == QEvent::WindowDeactivate
) {
934 * Dolphin leaves file preview tooltips open even when is not visible.
936 * Hide tool-tip when Dolphin loses focus.
939 abortTwoClicksRenaming();
942 return QWidget::event(event
);
945 void DolphinView::activate()
950 void DolphinView::slotItemActivated(int index
)
952 abortTwoClicksRenaming();
954 const KFileItem item
= m_model
->fileItem(index
);
955 if (!item
.isNull()) {
956 Q_EMIT
itemActivated(item
);
960 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
962 Q_ASSERT(indexes
.count() >= 2);
964 abortTwoClicksRenaming();
966 if (indexes
.count() > 5) {
967 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
968 const int answer
= KMessageBox::warningYesNo(this, question
);
969 if (answer
!= KMessageBox::Yes
) {
975 items
.reserve(indexes
.count());
977 for (int index
: indexes
) {
978 KFileItem item
= m_model
->fileItem(index
);
979 const QUrl
& url
= openItemAsFolderUrl(item
);
981 if (!url
.isEmpty()) { // Open folders in new tabs
982 Q_EMIT
tabRequested(url
);
988 if (items
.count() == 1) {
989 Q_EMIT
itemActivated(items
.first());
990 } else if (items
.count() > 1) {
991 Q_EMIT
itemsActivated(items
);
995 void DolphinView::slotItemMiddleClicked(int index
)
997 const KFileItem
& item
= m_model
->fileItem(index
);
998 const QUrl
& url
= openItemAsFolderUrl(item
);
999 if (!url
.isEmpty()) {
1000 Q_EMIT
tabRequested(url
);
1001 } else if (isTabsForFilesEnabled()) {
1002 Q_EMIT
tabRequested(item
.url());
1006 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
1008 // Force emit of a selection changed signal before we request the
1009 // context menu, to update the edit-actions first. (See Bug 294013)
1010 if (m_selectionChangedTimer
->isActive()) {
1011 emitSelectionChangedSignal();
1014 const KFileItem item
= m_model
->fileItem(index
);
1015 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
1018 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
1020 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
1023 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
1025 ViewProperties
props(viewPropertiesUrl());
1027 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
1029 KItemListView
* view
= m_container
->controller()->view();
1030 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1032 bool indexingEnabled
= false;
1034 Baloo::IndexerConfig config
;
1035 indexingEnabled
= config
.fileIndexingEnabled();
1039 QMenu
* groupMenu
= nullptr;
1041 // Add all roles to the menu that can be shown or hidden by the user
1042 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1043 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1044 if (info
.role
== "text") {
1045 // It should not be possible to hide the "text" role
1049 const QString text
= m_model
->roleDescription(info
.role
);
1050 QAction
* action
= nullptr;
1051 if (info
.group
.isEmpty()) {
1052 action
= menu
->addAction(text
);
1054 if (!groupMenu
|| info
.group
!= groupName
) {
1055 groupName
= info
.group
;
1056 groupMenu
= menu
->addMenu(groupName
);
1059 action
= groupMenu
->addAction(text
);
1062 action
->setCheckable(true);
1063 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1064 action
->setData(info
.role
);
1066 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1067 (info
.requiresBaloo
) ||
1068 (info
.requiresIndexer
&& indexingEnabled
);
1069 action
->setEnabled(enable
);
1072 menu
->addSeparator();
1074 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1075 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1077 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1078 autoAdjustWidthsAction
->setCheckable(true);
1079 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1080 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1082 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1083 customWidthsAction
->setCheckable(true);
1084 customWidthsAction
->setChecked(!autoColumnWidths
);
1085 customWidthsAction
->setActionGroup(widthsGroup
);
1087 QAction
* action
= menu
->exec(pos
.toPoint());
1088 if (menu
&& action
) {
1089 KItemListHeader
* header
= view
->header();
1091 if (action
== autoAdjustWidthsAction
) {
1092 // Clear the column-widths from the viewproperties and turn on
1093 // the automatic resizing of the columns
1094 props
.setHeaderColumnWidths(QList
<int>());
1095 header
->setAutomaticColumnResizing(true);
1096 } else if (action
== customWidthsAction
) {
1097 // Apply the current column-widths as custom column-widths and turn
1098 // off the automatic resizing of the columns
1099 QList
<int> columnWidths
;
1100 const auto visibleRoles
= view
->visibleRoles();
1101 columnWidths
.reserve(visibleRoles
.count());
1102 for (const QByteArray
& role
: visibleRoles
) {
1103 columnWidths
.append(header
->columnWidth(role
));
1105 props
.setHeaderColumnWidths(columnWidths
);
1106 header
->setAutomaticColumnResizing(false);
1108 // Show or hide the selected role
1109 const QByteArray selectedRole
= action
->data().toByteArray();
1111 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1112 if (action
->isChecked()) {
1113 visibleRoles
.append(selectedRole
);
1115 visibleRoles
.removeOne(selectedRole
);
1118 view
->setVisibleRoles(visibleRoles
);
1119 props
.setVisibleRoles(visibleRoles
);
1121 QList
<int> columnWidths
;
1122 if (!header
->automaticColumnResizing()) {
1123 const auto visibleRoles
= view
->visibleRoles();
1124 columnWidths
.reserve(visibleRoles
.count());
1125 for (const QByteArray
& role
: visibleRoles
) {
1126 columnWidths
.append(header
->columnWidth(role
));
1129 props
.setHeaderColumnWidths(columnWidths
);
1136 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1138 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1140 ViewProperties
props(viewPropertiesUrl());
1141 QList
<int> columnWidths
= props
.headerColumnWidths();
1142 if (columnWidths
.count() != visibleRoles
.count()) {
1143 columnWidths
.clear();
1144 columnWidths
.reserve(visibleRoles
.count());
1145 const KItemListHeader
* header
= m_view
->header();
1146 for (const QByteArray
& role
: visibleRoles
) {
1147 const int width
= header
->columnWidth(role
);
1148 columnWidths
.append(width
);
1152 const int roleIndex
= visibleRoles
.indexOf(role
);
1153 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1154 columnWidths
[roleIndex
] = current
;
1156 props
.setHeaderColumnWidths(columnWidths
);
1159 void DolphinView::slotItemHovered(int index
)
1161 const KFileItem item
= m_model
->fileItem(index
);
1163 if (GeneralSettings::showToolTips() && !m_dragging
) {
1164 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1165 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1166 itemRect
.moveTo(pos
);
1169 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1173 Q_EMIT
requestItemInfo(item
);
1176 void DolphinView::slotItemUnhovered(int index
)
1180 Q_EMIT
requestItemInfo(KFileItem());
1183 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1186 KFileItem destItem
= m_model
->fileItem(index
);
1187 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1188 // Use the URL of the view as drop target if the item is no directory
1190 destItem
= m_model
->rootItem();
1193 // The item represents a directory or desktop-file
1194 destUrl
= destItem
.mostLocalUrl();
1197 QDropEvent
dropEvent(event
->pos().toPoint(),
1198 event
->possibleActions(),
1201 event
->modifiers());
1202 dropUrls(destUrl
, &dropEvent
, this);
1207 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1209 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1212 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1214 if (destUrl
== url()) {
1215 // Mark the dropped urls as selected.
1216 m_clearSelectionBeforeSelectingNewItems
= true;
1217 m_markFirstNewlySelectedItemAsCurrent
= true;
1218 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1223 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1225 if (previous
!= nullptr) {
1226 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1227 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1228 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1229 m_versionControlObserver
->setModel(nullptr);
1233 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1234 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1235 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1236 m_versionControlObserver
->setModel(fileItemModel
);
1240 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1246 if (buttons
& Qt::BackButton
) {
1247 Q_EMIT
goBackRequested();
1248 } else if (buttons
& Qt::ForwardButton
) {
1249 Q_EMIT
goForwardRequested();
1253 void DolphinView::slotSelectedItemTextPressed(int index
)
1255 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1256 const KFileItem item
= m_model
->fileItem(index
);
1257 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1258 if (capabilities
.supportsMoving()) {
1259 m_twoClicksRenamingItemUrl
= item
.url();
1260 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1265 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1267 slotItemCreated(to
);
1270 void DolphinView::slotItemCreated(const QUrl
& url
)
1272 if (m_markFirstNewlySelectedItemAsCurrent
) {
1273 markUrlAsCurrent(url
);
1274 m_markFirstNewlySelectedItemAsCurrent
= false;
1276 m_selectedUrls
<< url
;
1279 void DolphinView::slotJobResult(KJob
*job
)
1282 Q_EMIT
errorMessage(job
->errorString());
1284 if (!m_selectedUrls
.isEmpty()) {
1285 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1289 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1291 const int currentCount
= current
.count();
1292 const int previousCount
= previous
.count();
1293 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1294 (currentCount
> 0 && previousCount
== 0);
1296 // If nothing has been selected before and something got selected (or if something
1297 // was selected before and now nothing is selected) the selectionChangedSignal must
1298 // be emitted asynchronously as fast as possible to update the edit-actions.
1299 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1300 m_selectionChangedTimer
->start();
1303 void DolphinView::emitSelectionChangedSignal()
1305 m_selectionChangedTimer
->stop();
1306 Q_EMIT
selectionChanged(selectedItems());
1309 void DolphinView::slotStatJobResult(KJob
*job
)
1311 int folderCount
= 0;
1313 KIO::filesize_t totalFileSize
= 0;
1314 bool countFileSize
= true;
1316 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1317 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1318 // We have a precomputed value.
1319 totalFileSize
= static_cast<KIO::filesize_t
>(
1320 entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1321 countFileSize
= false;
1324 const int itemCount
= m_model
->count();
1325 for (int i
= 0; i
< itemCount
; ++i
) {
1326 const KFileItem item
= m_model
->fileItem(i
);
1331 if (countFileSize
) {
1332 totalFileSize
+= item
.size();
1336 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1339 void DolphinView::updateSortRole(const QByteArray
& role
)
1341 ViewProperties
props(viewPropertiesUrl());
1342 props
.setSortRole(role
);
1344 KItemModelBase
* model
= m_container
->controller()->model();
1345 model
->setSortRole(role
);
1347 Q_EMIT
sortRoleChanged(role
);
1350 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1352 ViewProperties
props(viewPropertiesUrl());
1353 props
.setSortOrder(order
);
1355 m_model
->setSortOrder(order
);
1357 Q_EMIT
sortOrderChanged(order
);
1360 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1362 ViewProperties
props(viewPropertiesUrl());
1363 props
.setSortFoldersFirst(foldersFirst
);
1365 m_model
->setSortDirectoriesFirst(foldersFirst
);
1367 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1370 QPair
<bool, QString
> DolphinView::pasteInfo() const
1372 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1373 QPair
<bool, QString
> info
;
1374 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1378 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1380 m_tabsForFiles
= tabsForFiles
;
1383 bool DolphinView::isTabsForFilesEnabled() const
1385 return m_tabsForFiles
;
1388 bool DolphinView::itemsExpandable() const
1390 return m_mode
== DetailsView
;
1393 void DolphinView::restoreState(QDataStream
& stream
)
1395 // Read the version number of the view state and check if the version is supported.
1396 quint32 version
= 0;
1399 // The version of the view state isn't supported, we can't restore it.
1403 // Restore the current item that had the keyboard focus
1404 stream
>> m_currentItemUrl
;
1406 // Restore the previously selected items
1407 stream
>> m_selectedUrls
;
1409 // Restore the view position
1410 stream
>> m_restoredContentsPosition
;
1412 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1415 m_model
->restoreExpandedDirectories(urls
);
1418 void DolphinView::saveState(QDataStream
& stream
)
1420 stream
<< quint32(1); // View state version
1422 // Save the current item that has the keyboard focus
1423 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1424 if (currentIndex
!= -1) {
1425 KFileItem item
= m_model
->fileItem(currentIndex
);
1426 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1427 QUrl currentItemUrl
= item
.url();
1428 stream
<< currentItemUrl
;
1433 // Save the selected urls
1434 stream
<< selectedItems().urlList();
1436 // Save view position
1437 const qreal x
= m_container
->horizontalScrollBar()->value();
1438 const qreal y
= m_container
->verticalScrollBar()->value();
1439 stream
<< QPoint(x
, y
);
1441 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1442 stream
<< m_model
->expandedDirectories();
1445 KFileItem
DolphinView::rootItem() const
1447 return m_model
->rootItem();
1450 void DolphinView::setViewPropertiesContext(const QString
& context
)
1452 m_viewPropertiesContext
= context
;
1455 QString
DolphinView::viewPropertiesContext() const
1457 return m_viewPropertiesContext
;
1460 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1462 if (item
.isNull()) {
1466 QUrl url
= item
.targetUrl();
1472 if (item
.isMimeTypeKnown()) {
1473 const QString
& mimetype
= item
.mimetype();
1475 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1476 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1477 // zip:/<path>/ when clicking on a zip file, etc.
1478 // The .protocol file specifies the mimetype that the kioslave handles.
1479 // Note that we don't use mimetype inheritance since we don't want to
1480 // open OpenDocument files as zip folders...
1481 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1482 if (!protocol
.isEmpty()) {
1483 url
.setScheme(protocol
);
1488 if (mimetype
== QLatin1String("application/x-desktop")) {
1489 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1490 KDesktopFile
desktopFile(url
.toLocalFile());
1491 if (desktopFile
.hasLinkType()) {
1492 const QString linkUrl
= desktopFile
.readUrl();
1493 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1494 return QUrl::fromUserInput(linkUrl
);
1503 void DolphinView::resetZoomLevel()
1505 ViewModeSettings::ViewMode mode
;
1508 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1509 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1510 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1512 const ViewModeSettings
settings(mode
);
1513 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1514 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1517 void DolphinView::observeCreatedItem(const QUrl
& url
)
1520 forceUrlsSelection(url
, {url
});
1524 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1526 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1527 Q_EMIT
redirection(oldUrl
, newUrl
);
1528 m_url
= newUrl
; // #186947
1532 void DolphinView::updateViewState()
1534 if (m_currentItemUrl
!= QUrl()) {
1535 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1537 // if there is a selection already, leave it that way
1538 if (!selectionManager
->hasSelection()) {
1539 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1540 if (currentIndex
!= -1) {
1541 selectionManager
->setCurrentItem(currentIndex
);
1543 // scroll to current item and reset the state
1544 if (m_scrollToCurrentItem
) {
1545 m_view
->scrollToItem(currentIndex
);
1546 m_scrollToCurrentItem
= false;
1549 selectionManager
->setCurrentItem(0);
1553 m_currentItemUrl
= QUrl();
1556 if (!m_restoredContentsPosition
.isNull()) {
1557 const int x
= m_restoredContentsPosition
.x();
1558 const int y
= m_restoredContentsPosition
.y();
1559 m_restoredContentsPosition
= QPoint();
1561 m_container
->horizontalScrollBar()->setValue(x
);
1562 m_container
->verticalScrollBar()->setValue(y
);
1565 if (!m_selectedUrls
.isEmpty()) {
1566 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1568 // if there is a selection already, leave it that way
1569 if (!selectionManager
->hasSelection()) {
1570 if (m_clearSelectionBeforeSelectingNewItems
) {
1571 selectionManager
->clearSelection();
1572 m_clearSelectionBeforeSelectingNewItems
= false;
1575 KItemSet selectedItems
= selectionManager
->selectedItems();
1577 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1578 while (it
!= m_selectedUrls
.end()) {
1579 const int index
= m_model
->index(*it
);
1581 selectedItems
.insert(index
);
1582 it
= m_selectedUrls
.erase(it
);
1588 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1589 selectionManager
->setSelectedItems(selectedItems
);
1594 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1597 if (GeneralSettings::showToolTips()) {
1598 m_toolTipManager
->hideToolTip(behavior
);
1605 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1607 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1609 // verify that only one item is selected
1610 if (selectionManager
->selectedItems().count() == 1) {
1611 const int index
= selectionManager
->currentItem();
1612 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1614 // check if the selected item was the same item that started the twoClicksRenaming
1615 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1616 renameSelectedItems();
1621 void DolphinView::slotTrashFileFinished(KJob
* job
)
1623 if (job
->error() == 0) {
1624 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1625 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1626 Q_EMIT
errorMessage(job
->errorString());
1630 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1632 if (job
->error() == 0) {
1633 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1634 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1635 Q_EMIT
errorMessage(job
->errorString());
1639 void DolphinView::slotRenamingResult(KJob
* job
)
1642 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1644 const QUrl newUrl
= copyJob
->destUrl();
1645 const int index
= m_model
->index(newUrl
);
1647 QHash
<QByteArray
, QVariant
> data
;
1648 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1649 data
.insert("text", oldUrl
.fileName());
1650 m_model
->setData(index
, data
);
1655 void DolphinView::slotDirectoryLoadingStarted()
1658 updatePlaceholderLabel();
1660 // Disable the writestate temporary until it can be determined in a fast way
1661 // in DolphinView::slotDirectoryLoadingCompleted()
1662 if (m_isFolderWritable
) {
1663 m_isFolderWritable
= false;
1664 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1667 Q_EMIT
directoryLoadingStarted();
1670 void DolphinView::slotDirectoryLoadingCompleted()
1674 // Update the view-state. This has to be done asynchronously
1675 // because the view might not be in its final state yet.
1676 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1678 // Update the placeholder label in case we found that the folder was empty
1681 Q_EMIT
directoryLoadingCompleted();
1683 updatePlaceholderLabel();
1684 updateWritableState();
1687 void DolphinView::slotDirectoryLoadingCanceled()
1691 updatePlaceholderLabel();
1693 Q_EMIT
directoryLoadingCanceled();
1696 void DolphinView::slotItemsChanged()
1698 m_assureVisibleCurrentIndex
= false;
1701 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1704 Q_ASSERT(m_model
->sortOrder() == current
);
1706 ViewProperties
props(viewPropertiesUrl());
1707 props
.setSortOrder(current
);
1709 Q_EMIT
sortOrderChanged(current
);
1712 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1715 Q_ASSERT(m_model
->sortRole() == current
);
1717 ViewProperties
props(viewPropertiesUrl());
1718 props
.setSortRole(current
);
1720 Q_EMIT
sortRoleChanged(current
);
1723 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1724 const QList
<QByteArray
>& previous
)
1727 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1729 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1731 m_visibleRoles
= current
;
1733 ViewProperties
props(viewPropertiesUrl());
1734 props
.setVisibleRoles(m_visibleRoles
);
1736 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1739 void DolphinView::slotRoleEditingCanceled()
1741 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1742 this, &DolphinView::slotRoleEditingFinished
);
1745 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1747 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1748 this, &DolphinView::slotRoleEditingFinished
);
1750 const KFileItemList items
= selectedItems();
1751 if (items
.count() != 1) {
1755 if (role
== "text") {
1756 const KFileItem oldItem
= items
.first();
1757 const EditResult retVal
= value
.value
<EditResult
>();
1758 const QString newName
= retVal
.newName
;
1759 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1760 const QUrl oldUrl
= oldItem
.url();
1762 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1763 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1766 //Confirm hiding file/directory by renaming inline
1767 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1768 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1769 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1771 const auto code
= KMessageBox::questionYesNo(this,
1772 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1773 "Do you still want to rename it?")
1774 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1775 "Do you still want to rename it?"),
1776 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1778 KStandardGuiItem::cancel(),
1779 QStringLiteral("ConfirmHide")
1782 if (code
== KMessageBox::No
) {
1788 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1789 if (!newNameExistsAlready
&& m_model
->index(oldUrl
) == index
) {
1790 // Only change the data in the model if no item with the new name
1791 // is in the model yet. If there is an item with the new name
1792 // already, calling KIO::CopyJob will open a dialog
1793 // asking for a new name, and KFileItemModel will update the
1794 // data when the dir lister signals that the file name has changed.
1795 QHash
<QByteArray
, QVariant
> data
;
1796 data
.insert(role
, retVal
.newName
);
1797 m_model
->setData(index
, data
);
1800 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1801 KJobWidgets::setWindow(job
, this);
1802 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1803 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1805 forceUrlsSelection(newUrl
, {newUrl
});
1807 if (!newNameExistsAlready
) {
1808 // Only connect the result signal if there is no item with the new name
1809 // in the model yet, see bug 328262.
1810 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1813 if (retVal
.direction
!= EditDone
) {
1814 const short indexShift
= retVal
.direction
== EditNext
? 1 : -1;
1815 m_container
->controller()->selectionManager()->setSelected(index
, 1, KItemListSelectionManager::Deselect
);
1816 m_container
->controller()->selectionManager()->setSelected(index
+ indexShift
, 1,
1817 KItemListSelectionManager::Select
);
1818 renameSelectedItems();
1823 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1825 if (!url
.isValid()) {
1826 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1827 if (location
.isEmpty()) {
1828 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1830 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1836 m_model
->refreshDirectory(url
);
1838 m_model
->loadDirectory(url
);
1842 void DolphinView::applyViewProperties()
1844 const ViewProperties
props(viewPropertiesUrl());
1845 applyViewProperties(props
);
1848 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1850 m_view
->beginTransaction();
1852 const Mode mode
= props
.viewMode();
1853 if (m_mode
!= mode
) {
1854 const Mode previousMode
= m_mode
;
1857 // Changing the mode might result in changing
1858 // the zoom level. Remember the old zoom level so
1859 // that zoomLevelChanged() can get emitted.
1860 const int oldZoomLevel
= m_view
->zoomLevel();
1863 Q_EMIT
modeChanged(m_mode
, previousMode
);
1865 if (m_view
->zoomLevel() != oldZoomLevel
) {
1866 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1870 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1871 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1872 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1873 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1876 const bool groupedSorting
= props
.groupedSorting();
1877 if (groupedSorting
!= m_model
->groupedSorting()) {
1878 m_model
->setGroupedSorting(groupedSorting
);
1879 Q_EMIT
groupedSortingChanged(groupedSorting
);
1882 const QByteArray sortRole
= props
.sortRole();
1883 if (sortRole
!= m_model
->sortRole()) {
1884 m_model
->setSortRole(sortRole
);
1885 Q_EMIT
sortRoleChanged(sortRole
);
1888 const Qt::SortOrder sortOrder
= props
.sortOrder();
1889 if (sortOrder
!= m_model
->sortOrder()) {
1890 m_model
->setSortOrder(sortOrder
);
1891 Q_EMIT
sortOrderChanged(sortOrder
);
1894 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1895 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1896 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1897 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1900 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1901 if (visibleRoles
!= m_visibleRoles
) {
1902 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1903 m_visibleRoles
= visibleRoles
;
1904 m_view
->setVisibleRoles(visibleRoles
);
1905 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1908 const bool previewsShown
= props
.previewsShown();
1909 if (previewsShown
!= m_view
->previewsShown()) {
1910 const int oldZoomLevel
= zoomLevel();
1912 m_view
->setPreviewsShown(previewsShown
);
1913 Q_EMIT
previewsShownChanged(previewsShown
);
1915 // Changing the preview-state might result in a changed zoom-level
1916 if (oldZoomLevel
!= zoomLevel()) {
1917 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1921 KItemListView
* itemListView
= m_container
->controller()->view();
1922 if (itemListView
->isHeaderVisible()) {
1923 KItemListHeader
* header
= itemListView
->header();
1924 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1925 const int rolesCount
= m_visibleRoles
.count();
1926 if (headerColumnWidths
.count() == rolesCount
) {
1927 header
->setAutomaticColumnResizing(false);
1929 QHash
<QByteArray
, qreal
> columnWidths
;
1930 for (int i
= 0; i
< rolesCount
; ++i
) {
1931 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1933 header
->setColumnWidths(columnWidths
);
1935 header
->setAutomaticColumnResizing(true);
1939 m_view
->endTransaction();
1942 void DolphinView::applyModeToView()
1945 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1946 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1947 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1948 default: Q_ASSERT(false); break;
1952 void DolphinView::pasteToUrl(const QUrl
& url
)
1954 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1955 KJobWidgets::setWindow(job
, this);
1956 m_clearSelectionBeforeSelectingNewItems
= true;
1957 m_markFirstNewlySelectedItemAsCurrent
= true;
1958 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1959 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1962 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1966 const KFileItemList items
= selectedItems();
1967 urls
.reserve(items
.count());
1968 for (const KFileItem
& item
: items
) {
1969 urls
.append(item
.url());
1972 if (itemsExpandable()) {
1973 // TODO: Check if we still need KDirModel for this in KDE 5.0
1974 urls
= KDirModel::simplifiedUrlList(urls
);
1980 QMimeData
* DolphinView::selectionMimeData() const
1982 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1983 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1985 return m_model
->createMimeData(selectedIndexes
);
1988 void DolphinView::updateWritableState()
1990 const bool wasFolderWritable
= m_isFolderWritable
;
1991 m_isFolderWritable
= false;
1993 KFileItem item
= m_model
->rootItem();
1994 if (item
.isNull()) {
1995 // Try to find out if the URL is writable even if the "root item" is
1996 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1997 item
= KFileItem(url());
1998 item
.setDelayedMimeTypes(true);
2001 KFileItemListProperties
capabilities(KFileItemList() << item
);
2002 m_isFolderWritable
= capabilities
.supportsWriting();
2004 if (m_isFolderWritable
!= wasFolderWritable
) {
2005 Q_EMIT
writeStateChanged(m_isFolderWritable
);
2009 QUrl
DolphinView::viewPropertiesUrl() const
2011 if (m_viewPropertiesContext
.isEmpty()) {
2016 url
.setScheme(m_url
.scheme());
2017 url
.setPath(m_viewPropertiesContext
);
2021 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
2023 forceUrlsSelection(urls
.first(), urls
);
2026 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
2029 m_clearSelectionBeforeSelectingNewItems
= true;
2030 markUrlAsCurrent(current
);
2031 markUrlsAsSelected(selected
);
2034 void DolphinView::copyPathToClipboard()
2036 const KFileItemList list
= selectedItems();
2037 if (list
.isEmpty()) {
2040 const KFileItem
& item
= list
.at(0);
2041 QString path
= item
.localPath();
2042 if (path
.isEmpty()) {
2043 path
= item
.url().toDisplayString();
2045 QClipboard
* clipboard
= QApplication::clipboard();
2046 if (clipboard
== nullptr) {
2049 clipboard
->setText(path
);
2052 void DolphinView::slotIncreaseZoom()
2054 setZoomLevel(zoomLevel() + 1);
2057 void DolphinView::slotDecreaseZoom()
2059 setZoomLevel(zoomLevel() - 1);
2062 void DolphinView::slotSwipeUp()
2064 Q_EMIT
goUpRequested();
2067 void DolphinView::updatePlaceholderLabel()
2069 if (m_loading
|| itemsCount() > 0) {
2070 m_placeholderLabel
->setVisible(false);
2074 if (!nameFilter().isEmpty()) {
2075 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2076 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2077 m_placeholderLabel
->setText(i18n("No items matching the search"));
2078 } else if (m_url
.scheme() == QLatin1String("trash")) {
2079 m_placeholderLabel
->setText(i18n("Trash is empty"));
2080 } else if (m_url
.scheme() == QLatin1String("tags")) {
2081 m_placeholderLabel
->setText(i18n("No tags"));
2082 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2083 m_placeholderLabel
->setText(i18n("No recently used items"));
2084 } else if (m_url
.scheme() == QLatin1String("smb")) {
2085 m_placeholderLabel
->setText(i18n("No shared folders found"));
2086 } else if (m_url
.scheme() == QLatin1String("network")) {
2087 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2088 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2089 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2090 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2091 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2093 m_placeholderLabel
->setText(i18n("Folder is empty"));
2096 m_placeholderLabel
->setVisible(true);