2 * SPDX-FileCopyrightText: 2006-2009 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2006 Gregor Kališnik <gregor@podnapisi.net>
5 * SPDX-License-Identifier: GPL-2.0-or-later
8 #include "dolphinview.h"
10 #include "dolphin_detailsmodesettings.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphinitemlistview.h"
13 #include "dolphinnewfilemenuobserver.h"
14 #include "draganddrophelper.h"
15 #include "kitemviews/kfileitemlistview.h"
16 #include "kitemviews/kfileitemmodel.h"
17 #include "kitemviews/kitemlistcontainer.h"
18 #include "kitemviews/kitemlistcontroller.h"
19 #include "kitemviews/kitemlistheader.h"
20 #include "kitemviews/kitemlistselectionmanager.h"
21 #include "versioncontrol/versioncontrolobserver.h"
22 #include "viewproperties.h"
23 #include "views/tooltips/tooltipmanager.h"
24 #include "zoomlevelinfo.h"
27 #include <Baloo/IndexerConfig>
29 #include <KColorScheme>
30 #include <KDesktopFile>
32 #include <KFileItemListProperties>
34 #include <KIO/CopyJob>
35 #include <KIO/DeleteJob>
36 #include <KIO/DropJob>
37 #include <KIO/JobUiDelegate>
39 #include <KIO/PasteJob>
40 #include <KIO/PreviewJob>
41 #include <KIO/RenameFileDialog>
42 #include <KJobWidgets>
43 #include <KLocalizedString>
44 #include <KMessageBox>
45 #include <KProtocolManager>
47 #include <QAbstractItemView>
48 #include <QApplication>
51 #include <QGraphicsOpacityEffect>
52 #include <QGraphicsSceneDragDropEvent>
55 #include <QMimeDatabase>
56 #include <QPixmapCache>
61 #include <QVBoxLayout>
63 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
66 m_tabsForFiles(false),
67 m_assureVisibleCurrentIndex(false),
68 m_isFolderWritable(true),
72 m_viewPropertiesContext(),
73 m_mode(DolphinView::IconsView
),
79 m_toolTipManager(nullptr),
80 m_selectionChangedTimer(nullptr),
82 m_scrollToCurrentItem(false),
83 m_restoredContentsPosition(),
85 m_clearSelectionBeforeSelectingNewItems(false),
86 m_markFirstNewlySelectedItemAsCurrent(false),
87 m_versionControlObserver(nullptr),
88 m_twoClicksRenamingTimer(nullptr),
89 m_placeholderLabel(nullptr)
91 m_topLayout
= new QVBoxLayout(this);
92 m_topLayout
->setSpacing(0);
93 m_topLayout
->setContentsMargins(0, 0, 0, 0);
95 // When a new item has been created by the "Create New..." menu, the item should
96 // get selected and it must be assured that the item will get visible. As the
97 // creation is done asynchronously, several signals must be checked:
98 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
99 this, &DolphinView::observeCreatedItem
);
101 m_selectionChangedTimer
= new QTimer(this);
102 m_selectionChangedTimer
->setSingleShot(true);
103 m_selectionChangedTimer
->setInterval(300);
104 connect(m_selectionChangedTimer
, &QTimer::timeout
,
105 this, &DolphinView::emitSelectionChangedSignal
);
107 m_model
= new KFileItemModel(this);
108 m_view
= new DolphinItemListView();
109 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
110 m_view
->setVisibleRoles({"text"});
113 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
114 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
115 controller
->setAutoActivationDelay(delay
);
117 // The EnlargeSmallPreviews setting can only be changed after the model
118 // has been set in the view by KItemListController.
119 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
121 m_container
= new KItemListContainer(controller
, this);
122 m_container
->installEventFilter(this);
123 setFocusProxy(m_container
);
124 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
125 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
127 // Show some placeholder text for empty folders
128 // This is made using a heavily-modified QLabel rather than a KTitleWidget
129 // because KTitleWidget can't be told to turn off mouse-selectable text
130 m_placeholderLabel
= new QLabel(this);
131 QFont placeholderLabelFont
;
132 // To match the size of a level 2 Heading/KTitleWidget
133 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
134 m_placeholderLabel
->setFont(placeholderLabelFont
);
135 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
136 m_placeholderLabel
->setWordWrap(true);
137 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
138 // Match opacity of QML placeholder label component
139 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
140 effect
->setOpacity(0.5);
141 m_placeholderLabel
->setGraphicsEffect(effect
);
142 // Set initial text and visibility
143 updatePlaceholderLabel();
145 auto *centeringLayout
= new QVBoxLayout(m_container
);
146 centeringLayout
->addWidget(m_placeholderLabel
);
147 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
149 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
150 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
151 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
152 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
153 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
154 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
155 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
156 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
157 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
158 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
159 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
160 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
161 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
162 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
163 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
164 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
165 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
167 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
168 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
169 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
170 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
171 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
172 connect(m_model
, &KFileItemModel::itemsChanged
,
173 this, &DolphinView::slotItemsChanged
);
174 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
175 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
176 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
177 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
178 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
179 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
181 connect(this, &DolphinView::itemCountChanged
,
182 this, &DolphinView::updatePlaceholderLabel
);
184 m_view
->installEventFilter(this);
185 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
186 this, &DolphinView::slotSortOrderChangedByHeader
);
187 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
188 this, &DolphinView::slotSortRoleChangedByHeader
);
189 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
190 this, &DolphinView::slotVisibleRolesChangedByHeader
);
191 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
192 this, &DolphinView::slotRoleEditingCanceled
);
193 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
194 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
196 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
197 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
198 this, &DolphinView::slotSelectionChanged
);
201 m_toolTipManager
= new ToolTipManager(this);
202 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
205 m_versionControlObserver
= new VersionControlObserver(this);
206 m_versionControlObserver
->setView(this);
207 m_versionControlObserver
->setModel(m_model
);
208 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
209 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
210 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
212 m_twoClicksRenamingTimer
= new QTimer(this);
213 m_twoClicksRenamingTimer
->setSingleShot(true);
214 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
216 applyViewProperties();
217 m_topLayout
->addWidget(m_container
);
222 DolphinView::~DolphinView()
226 QUrl
DolphinView::url() const
231 void DolphinView::setActive(bool active
)
233 if (active
== m_active
) {
242 m_container
->setFocus();
244 Q_EMIT
writeStateChanged(m_isFolderWritable
);
248 bool DolphinView::isActive() const
253 void DolphinView::setMode(Mode mode
)
255 if (mode
!= m_mode
) {
256 ViewProperties
props(viewPropertiesUrl());
257 props
.setViewMode(mode
);
259 // We pass the new ViewProperties to applyViewProperties, rather than
260 // storing them on disk and letting applyViewProperties() read them
261 // from there, to prevent that changing the view mode fails if the
262 // .directory file is not writable (see bug 318534).
263 applyViewProperties(props
);
267 DolphinView::Mode
DolphinView::mode() const
272 void DolphinView::setPreviewsShown(bool show
)
274 if (previewsShown() == show
) {
278 ViewProperties
props(viewPropertiesUrl());
279 props
.setPreviewsShown(show
);
281 const int oldZoomLevel
= m_view
->zoomLevel();
282 m_view
->setPreviewsShown(show
);
283 Q_EMIT
previewsShownChanged(show
);
285 const int newZoomLevel
= m_view
->zoomLevel();
286 if (newZoomLevel
!= oldZoomLevel
) {
287 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
291 bool DolphinView::previewsShown() const
293 return m_view
->previewsShown();
296 void DolphinView::setHiddenFilesShown(bool show
)
298 if (m_model
->showHiddenFiles() == show
) {
302 const KFileItemList itemList
= selectedItems();
303 m_selectedUrls
.clear();
304 m_selectedUrls
= itemList
.urlList();
306 ViewProperties
props(viewPropertiesUrl());
307 props
.setHiddenFilesShown(show
);
309 m_model
->setShowHiddenFiles(show
);
310 Q_EMIT
hiddenFilesShownChanged(show
);
313 bool DolphinView::hiddenFilesShown() const
315 return m_model
->showHiddenFiles();
318 void DolphinView::setGroupedSorting(bool grouped
)
320 if (grouped
== groupedSorting()) {
324 ViewProperties
props(viewPropertiesUrl());
325 props
.setGroupedSorting(grouped
);
328 m_container
->controller()->model()->setGroupedSorting(grouped
);
330 Q_EMIT
groupedSortingChanged(grouped
);
333 bool DolphinView::groupedSorting() const
335 return m_model
->groupedSorting();
338 KFileItemList
DolphinView::items() const
341 const int itemCount
= m_model
->count();
342 list
.reserve(itemCount
);
344 for (int i
= 0; i
< itemCount
; ++i
) {
345 list
.append(m_model
->fileItem(i
));
351 int DolphinView::itemsCount() const
353 return m_model
->count();
356 KFileItemList
DolphinView::selectedItems() const
358 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
360 KFileItemList selectedItems
;
361 const auto items
= selectionManager
->selectedItems();
362 selectedItems
.reserve(items
.count());
363 for (int index
: items
) {
364 selectedItems
.append(m_model
->fileItem(index
));
366 return selectedItems
;
369 int DolphinView::selectedItemsCount() const
371 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
372 return selectionManager
->selectedItems().count();
375 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
377 m_selectedUrls
= urls
;
380 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
382 m_currentItemUrl
= url
;
383 m_scrollToCurrentItem
= true;
386 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
388 const KItemListSelectionManager::SelectionMode mode
= enabled
389 ? KItemListSelectionManager::Select
390 : KItemListSelectionManager::Deselect
;
391 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
393 for (int index
= 0; index
< m_model
->count(); index
++) {
394 const KFileItem item
= m_model
->fileItem(index
);
395 if (regexp
.match(item
.text()).hasMatch()) {
396 // An alternative approach would be to store the matching items in a KItemSet and
397 // select them in one go after the loop, but we'd need a new function
398 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
400 selectionManager
->setSelected(index
, 1, mode
);
405 void DolphinView::setZoomLevel(int level
)
407 const int oldZoomLevel
= zoomLevel();
408 m_view
->setZoomLevel(level
);
409 if (zoomLevel() != oldZoomLevel
) {
411 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
415 int DolphinView::zoomLevel() const
417 return m_view
->zoomLevel();
420 void DolphinView::setSortRole(const QByteArray
& role
)
422 if (role
!= sortRole()) {
423 updateSortRole(role
);
427 QByteArray
DolphinView::sortRole() const
429 const KItemModelBase
* model
= m_container
->controller()->model();
430 return model
->sortRole();
433 void DolphinView::setSortOrder(Qt::SortOrder order
)
435 if (sortOrder() != order
) {
436 updateSortOrder(order
);
440 Qt::SortOrder
DolphinView::sortOrder() const
442 return m_model
->sortOrder();
445 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
447 if (sortFoldersFirst() != foldersFirst
) {
448 updateSortFoldersFirst(foldersFirst
);
452 bool DolphinView::sortFoldersFirst() const
454 return m_model
->sortDirectoriesFirst();
457 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
459 const QList
<QByteArray
> previousRoles
= roles
;
461 ViewProperties
props(viewPropertiesUrl());
462 props
.setVisibleRoles(roles
);
464 m_visibleRoles
= roles
;
465 m_view
->setVisibleRoles(roles
);
467 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
470 QList
<QByteArray
> DolphinView::visibleRoles() const
472 return m_visibleRoles
;
475 void DolphinView::reload()
477 QByteArray viewState
;
478 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
479 saveState(saveStream
);
482 loadDirectory(url(), true);
484 QDataStream
restoreStream(viewState
);
485 restoreState(restoreStream
);
488 void DolphinView::readSettings()
490 const int oldZoomLevel
= m_view
->zoomLevel();
492 GeneralSettings::self()->load();
493 m_view
->readSettings();
494 applyViewProperties();
496 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
497 m_container
->controller()->setAutoActivationDelay(delay
);
499 const int newZoomLevel
= m_view
->zoomLevel();
500 if (newZoomLevel
!= oldZoomLevel
) {
501 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
505 void DolphinView::writeSettings()
507 GeneralSettings::self()->save();
508 m_view
->writeSettings();
511 void DolphinView::setNameFilter(const QString
& nameFilter
)
513 m_model
->setNameFilter(nameFilter
);
516 QString
DolphinView::nameFilter() const
518 return m_model
->nameFilter();
521 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
523 return m_model
->setMimeTypeFilters(filters
);
526 QStringList
DolphinView::mimeTypeFilters() const
528 return m_model
->mimeTypeFilters();
531 QString
DolphinView::statusBarText() const
539 KIO::filesize_t totalFileSize
= 0;
541 if (m_container
->controller()->selectionManager()->hasSelection()) {
542 // Give a summary of the status of the selected files
543 const KFileItemList list
= selectedItems();
544 for (const KFileItem
& item
: list
) {
549 totalFileSize
+= item
.size();
553 if (folderCount
+ fileCount
== 1) {
554 // If only one item is selected, show info about it
555 return list
.first().getStatusBarInfo();
557 // At least 2 items are selected
558 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
559 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
562 calculateItemCount(fileCount
, folderCount
, totalFileSize
);
563 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
564 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
567 if (fileCount
> 0 && folderCount
> 0) {
568 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
569 foldersText
, filesText
,
570 KFormat().formatByteSize(totalFileSize
));
571 } else if (fileCount
> 0) {
572 summary
= i18nc("@info:status files (size)", "%1 (%2)",
574 KFormat().formatByteSize(totalFileSize
));
575 } else if (folderCount
> 0) {
576 summary
= foldersText
;
578 summary
= i18nc("@info:status", "0 Folders, 0 Files");
584 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
586 QList
<QAction
*> actions
;
588 if (items
.isEmpty()) {
589 const KFileItem item
= m_model
->rootItem();
590 if (!item
.isNull()) {
591 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
594 actions
= m_versionControlObserver
->actions(items
);
600 void DolphinView::setUrl(const QUrl
& url
)
612 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
613 this, &DolphinView::slotRoleEditingFinished
);
615 // It is important to clear the items from the model before
616 // applying the view properties, otherwise expensive operations
617 // might be done on the existing items although they get cleared
618 // anyhow afterwards by loadDirectory().
620 applyViewProperties();
623 Q_EMIT
urlChanged(url
);
626 void DolphinView::selectAll()
628 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
629 selectionManager
->setSelected(0, m_model
->count());
632 void DolphinView::invertSelection()
634 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
635 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
638 void DolphinView::clearSelection()
640 m_selectedUrls
.clear();
641 m_container
->controller()->selectionManager()->clearSelection();
644 void DolphinView::renameSelectedItems()
646 const KFileItemList items
= selectedItems();
647 if (items
.isEmpty()) {
651 if (items
.count() == 1 && GeneralSettings::renameInline()) {
652 const int index
= m_model
->index(items
.first());
653 m_view
->editRole(index
, "text");
657 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
658 this, &DolphinView::slotRoleEditingFinished
);
660 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
661 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
662 this, &DolphinView::slotRenameDialogRenamingFinished
);
667 // Assure that the current index remains visible when KFileItemModel
668 // will notify the view about changed items (which might result in
669 // a changed sorting).
670 m_assureVisibleCurrentIndex
= true;
673 void DolphinView::trashSelectedItems()
675 const QList
<QUrl
> list
= simplifiedSelectedUrls();
676 KIO::JobUiDelegate uiDelegate
;
677 uiDelegate
.setWindow(window());
678 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
679 KIO::Job
* job
= KIO::trash(list
);
680 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
681 KJobWidgets::setWindow(job
, this);
682 connect(job
, &KIO::Job::result
,
683 this, &DolphinView::slotTrashFileFinished
);
687 void DolphinView::deleteSelectedItems()
689 const QList
<QUrl
> list
= simplifiedSelectedUrls();
691 KIO::JobUiDelegate uiDelegate
;
692 uiDelegate
.setWindow(window());
693 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
694 KIO::Job
* job
= KIO::del(list
);
695 KJobWidgets::setWindow(job
, this);
696 connect(job
, &KIO::Job::result
,
697 this, &DolphinView::slotDeleteFileFinished
);
701 void DolphinView::cutSelectedItemsToClipboard()
703 QMimeData
* mimeData
= selectionMimeData();
704 KIO::setClipboardDataCut(mimeData
, true);
705 QApplication::clipboard()->setMimeData(mimeData
);
708 void DolphinView::copySelectedItemsToClipboard()
710 QMimeData
* mimeData
= selectionMimeData();
711 QApplication::clipboard()->setMimeData(mimeData
);
714 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
716 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
717 KJobWidgets::setWindow(job
, this);
719 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
720 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
721 KIO::FileUndoManager::self()->recordCopyJob(job
);
724 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
726 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
727 KJobWidgets::setWindow(job
, this);
729 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
730 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
731 KIO::FileUndoManager::self()->recordCopyJob(job
);
735 void DolphinView::paste()
740 void DolphinView::pasteIntoFolder()
742 const KFileItemList items
= selectedItems();
743 if ((items
.count() == 1) && items
.first().isDir()) {
744 pasteToUrl(items
.first().url());
748 void DolphinView::duplicateSelectedItems()
750 const KFileItemList itemList
= selectedItems();
751 if (itemList
.isEmpty()) {
755 const QMimeDatabase db
;
757 // Duplicate all selected items and append "copy" to the end of the file name
758 // but before the filename extension, if present
759 QList
<QUrl
> newSelection
;
760 for (const auto &item
: itemList
) {
761 const QUrl originalURL
= item
.url();
762 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
763 const QString originalFileName
= item
.name();
765 QString extension
= db
.suffixForFileName(originalFileName
);
767 QUrl duplicateURL
= originalURL
;
769 // No extension; new filename is "<oldfilename> copy"
770 if (extension
.isEmpty()) {
771 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
772 // There's an extension; new filename is "<oldfilename> copy.<extension>"
774 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
775 extension
= QLatin1String(".") + extension
;
776 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
777 // Preserve file's original filename extension in case the casing differs
778 // from what QMimeDatabase::suffixForFileName() returned
779 const QString originalExtension
= originalFileName
.right(extension
.size());
780 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
783 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
784 KJobWidgets::setWindow(job
, this);
787 newSelection
<< duplicateURL
;
788 KIO::FileUndoManager::self()->recordCopyJob(job
);
792 forceUrlsSelection(newSelection
.first(), newSelection
);
795 void DolphinView::stopLoading()
797 m_model
->cancelDirectoryLoading();
800 void DolphinView::updatePalette()
802 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
807 QWidget
* viewport
= m_container
->viewport();
810 palette
.setColor(viewport
->backgroundRole(), color
);
811 viewport
->setPalette(palette
);
817 void DolphinView::abortTwoClicksRenaming()
819 m_twoClicksRenamingItemUrl
.clear();
820 m_twoClicksRenamingTimer
->stop();
823 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
825 switch (event
->type()) {
826 case QEvent::PaletteChange
:
828 QPixmapCache::clear();
831 case QEvent::WindowActivate
:
832 case QEvent::WindowDeactivate
:
836 case QEvent::KeyPress
:
837 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
838 if (GeneralSettings::useTabForSwitchingSplitView()) {
839 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
840 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
841 Q_EMIT
toggleActiveViewRequested();
846 case QEvent::FocusIn
:
847 if (watched
== m_container
) {
852 case QEvent::GraphicsSceneDragEnter
:
853 if (watched
== m_view
) {
855 abortTwoClicksRenaming();
859 case QEvent::GraphicsSceneDragLeave
:
860 if (watched
== m_view
) {
865 case QEvent::GraphicsSceneDrop
:
866 if (watched
== m_view
) {
873 return QWidget::eventFilter(watched
, event
);
876 void DolphinView::wheelEvent(QWheelEvent
* event
)
878 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
879 const QPoint numDegrees
= event
->angleDelta() / 8;
880 const QPoint numSteps
= numDegrees
/ 15;
882 setZoomLevel(zoomLevel() + numSteps
.y());
889 void DolphinView::hideEvent(QHideEvent
* event
)
892 QWidget::hideEvent(event
);
895 bool DolphinView::event(QEvent
* event
)
897 if (event
->type() == QEvent::WindowDeactivate
) {
899 * Dolphin leaves file preview tooltips open even when is not visible.
901 * Hide tool-tip when Dolphin loses focus.
904 abortTwoClicksRenaming();
907 return QWidget::event(event
);
910 void DolphinView::activate()
915 void DolphinView::slotItemActivated(int index
)
917 abortTwoClicksRenaming();
919 const KFileItem item
= m_model
->fileItem(index
);
920 if (!item
.isNull()) {
921 Q_EMIT
itemActivated(item
);
925 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
927 Q_ASSERT(indexes
.count() >= 2);
929 abortTwoClicksRenaming();
931 if (indexes
.count() > 5) {
932 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
933 const int answer
= KMessageBox::warningYesNo(this, question
);
934 if (answer
!= KMessageBox::Yes
) {
940 items
.reserve(indexes
.count());
942 for (int index
: indexes
) {
943 KFileItem item
= m_model
->fileItem(index
);
944 const QUrl
& url
= openItemAsFolderUrl(item
);
946 if (!url
.isEmpty()) { // Open folders in new tabs
947 Q_EMIT
tabRequested(url
);
953 if (items
.count() == 1) {
954 Q_EMIT
itemActivated(items
.first());
955 } else if (items
.count() > 1) {
956 Q_EMIT
itemsActivated(items
);
960 void DolphinView::slotItemMiddleClicked(int index
)
962 const KFileItem
& item
= m_model
->fileItem(index
);
963 const QUrl
& url
= openItemAsFolderUrl(item
);
964 if (!url
.isEmpty()) {
965 Q_EMIT
tabRequested(url
);
966 } else if (isTabsForFilesEnabled()) {
967 Q_EMIT
tabRequested(item
.url());
971 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
973 // Force emit of a selection changed signal before we request the
974 // context menu, to update the edit-actions first. (See Bug 294013)
975 if (m_selectionChangedTimer
->isActive()) {
976 emitSelectionChangedSignal();
979 const KFileItem item
= m_model
->fileItem(index
);
980 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
983 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
985 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
988 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
990 ViewProperties
props(viewPropertiesUrl());
992 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
994 KItemListView
* view
= m_container
->controller()->view();
995 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
997 bool indexingEnabled
= false;
999 Baloo::IndexerConfig config
;
1000 indexingEnabled
= config
.fileIndexingEnabled();
1004 QMenu
* groupMenu
= nullptr;
1006 // Add all roles to the menu that can be shown or hidden by the user
1007 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1008 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1009 if (info
.role
== "text") {
1010 // It should not be possible to hide the "text" role
1014 const QString text
= m_model
->roleDescription(info
.role
);
1015 QAction
* action
= nullptr;
1016 if (info
.group
.isEmpty()) {
1017 action
= menu
->addAction(text
);
1019 if (!groupMenu
|| info
.group
!= groupName
) {
1020 groupName
= info
.group
;
1021 groupMenu
= menu
->addMenu(groupName
);
1024 action
= groupMenu
->addAction(text
);
1027 action
->setCheckable(true);
1028 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1029 action
->setData(info
.role
);
1031 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1032 (info
.requiresBaloo
) ||
1033 (info
.requiresIndexer
&& indexingEnabled
);
1034 action
->setEnabled(enable
);
1037 menu
->addSeparator();
1039 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1040 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1042 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1043 autoAdjustWidthsAction
->setCheckable(true);
1044 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1045 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1047 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1048 customWidthsAction
->setCheckable(true);
1049 customWidthsAction
->setChecked(!autoColumnWidths
);
1050 customWidthsAction
->setActionGroup(widthsGroup
);
1052 QAction
* action
= menu
->exec(pos
.toPoint());
1053 if (menu
&& action
) {
1054 KItemListHeader
* header
= view
->header();
1056 if (action
== autoAdjustWidthsAction
) {
1057 // Clear the column-widths from the viewproperties and turn on
1058 // the automatic resizing of the columns
1059 props
.setHeaderColumnWidths(QList
<int>());
1060 header
->setAutomaticColumnResizing(true);
1061 } else if (action
== customWidthsAction
) {
1062 // Apply the current column-widths as custom column-widths and turn
1063 // off the automatic resizing of the columns
1064 QList
<int> columnWidths
;
1065 const auto visibleRoles
= view
->visibleRoles();
1066 columnWidths
.reserve(visibleRoles
.count());
1067 for (const QByteArray
& role
: visibleRoles
) {
1068 columnWidths
.append(header
->columnWidth(role
));
1070 props
.setHeaderColumnWidths(columnWidths
);
1071 header
->setAutomaticColumnResizing(false);
1073 // Show or hide the selected role
1074 const QByteArray selectedRole
= action
->data().toByteArray();
1076 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1077 if (action
->isChecked()) {
1078 visibleRoles
.append(selectedRole
);
1080 visibleRoles
.removeOne(selectedRole
);
1083 view
->setVisibleRoles(visibleRoles
);
1084 props
.setVisibleRoles(visibleRoles
);
1086 QList
<int> columnWidths
;
1087 if (!header
->automaticColumnResizing()) {
1088 const auto visibleRoles
= view
->visibleRoles();
1089 columnWidths
.reserve(visibleRoles
.count());
1090 for (const QByteArray
& role
: visibleRoles
) {
1091 columnWidths
.append(header
->columnWidth(role
));
1094 props
.setHeaderColumnWidths(columnWidths
);
1101 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1103 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1105 ViewProperties
props(viewPropertiesUrl());
1106 QList
<int> columnWidths
= props
.headerColumnWidths();
1107 if (columnWidths
.count() != visibleRoles
.count()) {
1108 columnWidths
.clear();
1109 columnWidths
.reserve(visibleRoles
.count());
1110 const KItemListHeader
* header
= m_view
->header();
1111 for (const QByteArray
& role
: visibleRoles
) {
1112 const int width
= header
->columnWidth(role
);
1113 columnWidths
.append(width
);
1117 const int roleIndex
= visibleRoles
.indexOf(role
);
1118 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1119 columnWidths
[roleIndex
] = current
;
1121 props
.setHeaderColumnWidths(columnWidths
);
1124 void DolphinView::slotItemHovered(int index
)
1126 const KFileItem item
= m_model
->fileItem(index
);
1128 if (GeneralSettings::showToolTips() && !m_dragging
) {
1129 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1130 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1131 itemRect
.moveTo(pos
);
1134 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1138 Q_EMIT
requestItemInfo(item
);
1141 void DolphinView::slotItemUnhovered(int index
)
1145 Q_EMIT
requestItemInfo(KFileItem());
1148 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1151 KFileItem destItem
= m_model
->fileItem(index
);
1152 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1153 // Use the URL of the view as drop target if the item is no directory
1155 destItem
= m_model
->rootItem();
1158 // The item represents a directory or desktop-file
1159 destUrl
= destItem
.mostLocalUrl();
1162 QDropEvent
dropEvent(event
->pos().toPoint(),
1163 event
->possibleActions(),
1166 event
->modifiers());
1167 dropUrls(destUrl
, &dropEvent
, this);
1172 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1174 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1177 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1179 if (destUrl
== url()) {
1180 // Mark the dropped urls as selected.
1181 m_clearSelectionBeforeSelectingNewItems
= true;
1182 m_markFirstNewlySelectedItemAsCurrent
= true;
1183 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1188 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1190 if (previous
!= nullptr) {
1191 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1192 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1193 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1194 m_versionControlObserver
->setModel(nullptr);
1198 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1199 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1200 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1201 m_versionControlObserver
->setModel(fileItemModel
);
1205 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1211 if (buttons
& Qt::BackButton
) {
1212 Q_EMIT
goBackRequested();
1213 } else if (buttons
& Qt::ForwardButton
) {
1214 Q_EMIT
goForwardRequested();
1218 void DolphinView::slotSelectedItemTextPressed(int index
)
1220 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1221 const KFileItem item
= m_model
->fileItem(index
);
1222 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1223 if (capabilities
.supportsMoving()) {
1224 m_twoClicksRenamingItemUrl
= item
.url();
1225 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1230 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1232 slotItemCreated(to
);
1235 void DolphinView::slotItemCreated(const QUrl
& url
)
1237 if (m_markFirstNewlySelectedItemAsCurrent
) {
1238 markUrlAsCurrent(url
);
1239 m_markFirstNewlySelectedItemAsCurrent
= false;
1241 m_selectedUrls
<< url
;
1244 void DolphinView::slotJobResult(KJob
*job
)
1247 Q_EMIT
errorMessage(job
->errorString());
1249 if (!m_selectedUrls
.isEmpty()) {
1250 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1254 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1256 const int currentCount
= current
.count();
1257 const int previousCount
= previous
.count();
1258 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1259 (currentCount
> 0 && previousCount
== 0);
1261 // If nothing has been selected before and something got selected (or if something
1262 // was selected before and now nothing is selected) the selectionChangedSignal must
1263 // be emitted asynchronously as fast as possible to update the edit-actions.
1264 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1265 m_selectionChangedTimer
->start();
1268 void DolphinView::emitSelectionChangedSignal()
1270 m_selectionChangedTimer
->stop();
1271 Q_EMIT
selectionChanged(selectedItems());
1274 void DolphinView::updateSortRole(const QByteArray
& role
)
1276 ViewProperties
props(viewPropertiesUrl());
1277 props
.setSortRole(role
);
1279 KItemModelBase
* model
= m_container
->controller()->model();
1280 model
->setSortRole(role
);
1282 Q_EMIT
sortRoleChanged(role
);
1285 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1287 ViewProperties
props(viewPropertiesUrl());
1288 props
.setSortOrder(order
);
1290 m_model
->setSortOrder(order
);
1292 Q_EMIT
sortOrderChanged(order
);
1295 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1297 ViewProperties
props(viewPropertiesUrl());
1298 props
.setSortFoldersFirst(foldersFirst
);
1300 m_model
->setSortDirectoriesFirst(foldersFirst
);
1302 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1305 QPair
<bool, QString
> DolphinView::pasteInfo() const
1307 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1308 QPair
<bool, QString
> info
;
1309 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1313 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1315 m_tabsForFiles
= tabsForFiles
;
1318 bool DolphinView::isTabsForFilesEnabled() const
1320 return m_tabsForFiles
;
1323 bool DolphinView::itemsExpandable() const
1325 return m_mode
== DetailsView
;
1328 void DolphinView::restoreState(QDataStream
& stream
)
1330 // Read the version number of the view state and check if the version is supported.
1331 quint32 version
= 0;
1334 // The version of the view state isn't supported, we can't restore it.
1338 // Restore the current item that had the keyboard focus
1339 stream
>> m_currentItemUrl
;
1341 // Restore the previously selected items
1342 stream
>> m_selectedUrls
;
1344 // Restore the view position
1345 stream
>> m_restoredContentsPosition
;
1347 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1350 m_model
->restoreExpandedDirectories(urls
);
1353 void DolphinView::saveState(QDataStream
& stream
)
1355 stream
<< quint32(1); // View state version
1357 // Save the current item that has the keyboard focus
1358 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1359 if (currentIndex
!= -1) {
1360 KFileItem item
= m_model
->fileItem(currentIndex
);
1361 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1362 QUrl currentItemUrl
= item
.url();
1363 stream
<< currentItemUrl
;
1368 // Save the selected urls
1369 stream
<< selectedItems().urlList();
1371 // Save view position
1372 const qreal x
= m_container
->horizontalScrollBar()->value();
1373 const qreal y
= m_container
->verticalScrollBar()->value();
1374 stream
<< QPoint(x
, y
);
1376 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1377 stream
<< m_model
->expandedDirectories();
1380 KFileItem
DolphinView::rootItem() const
1382 return m_model
->rootItem();
1385 void DolphinView::setViewPropertiesContext(const QString
& context
)
1387 m_viewPropertiesContext
= context
;
1390 QString
DolphinView::viewPropertiesContext() const
1392 return m_viewPropertiesContext
;
1395 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1397 if (item
.isNull()) {
1401 QUrl url
= item
.targetUrl();
1407 if (item
.isMimeTypeKnown()) {
1408 const QString
& mimetype
= item
.mimetype();
1410 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1411 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1412 // zip:/<path>/ when clicking on a zip file, etc.
1413 // The .protocol file specifies the mimetype that the kioslave handles.
1414 // Note that we don't use mimetype inheritance since we don't want to
1415 // open OpenDocument files as zip folders...
1416 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1417 if (!protocol
.isEmpty()) {
1418 url
.setScheme(protocol
);
1423 if (mimetype
== QLatin1String("application/x-desktop")) {
1424 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1425 KDesktopFile
desktopFile(url
.toLocalFile());
1426 if (desktopFile
.hasLinkType()) {
1427 const QString linkUrl
= desktopFile
.readUrl();
1428 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1429 return QUrl::fromUserInput(linkUrl
);
1438 void DolphinView::resetZoomLevel()
1440 ViewModeSettings::ViewMode mode
;
1443 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1444 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1445 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1447 const ViewModeSettings
settings(mode
);
1448 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1449 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1452 void DolphinView::observeCreatedItem(const QUrl
& url
)
1455 forceUrlsSelection(url
, {url
});
1459 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1461 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1462 Q_EMIT
redirection(oldUrl
, newUrl
);
1463 m_url
= newUrl
; // #186947
1467 void DolphinView::updateViewState()
1469 if (m_currentItemUrl
!= QUrl()) {
1470 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1472 // if there is a selection already, leave it that way
1473 if (!selectionManager
->hasSelection()) {
1474 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1475 if (currentIndex
!= -1) {
1476 selectionManager
->setCurrentItem(currentIndex
);
1478 // scroll to current item and reset the state
1479 if (m_scrollToCurrentItem
) {
1480 m_view
->scrollToItem(currentIndex
);
1481 m_scrollToCurrentItem
= false;
1484 selectionManager
->setCurrentItem(0);
1488 m_currentItemUrl
= QUrl();
1491 if (!m_restoredContentsPosition
.isNull()) {
1492 const int x
= m_restoredContentsPosition
.x();
1493 const int y
= m_restoredContentsPosition
.y();
1494 m_restoredContentsPosition
= QPoint();
1496 m_container
->horizontalScrollBar()->setValue(x
);
1497 m_container
->verticalScrollBar()->setValue(y
);
1500 if (!m_selectedUrls
.isEmpty()) {
1501 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1503 // if there is a selection already, leave it that way
1504 if (!selectionManager
->hasSelection()) {
1505 if (m_clearSelectionBeforeSelectingNewItems
) {
1506 selectionManager
->clearSelection();
1507 m_clearSelectionBeforeSelectingNewItems
= false;
1510 KItemSet selectedItems
= selectionManager
->selectedItems();
1512 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1513 while (it
!= m_selectedUrls
.end()) {
1514 const int index
= m_model
->index(*it
);
1516 selectedItems
.insert(index
);
1517 it
= m_selectedUrls
.erase(it
);
1523 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1524 selectionManager
->setSelectedItems(selectedItems
);
1529 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1532 if (GeneralSettings::showToolTips()) {
1533 m_toolTipManager
->hideToolTip(behavior
);
1540 void DolphinView::calculateItemCount(int& fileCount
,
1542 KIO::filesize_t
& totalFileSize
) const
1544 const int itemCount
= m_model
->count();
1546 bool countFileSize
= true;
1548 if (!m_model
->rootItem().url().isValid()) {
1552 // In case we have a precomputed value
1553 const auto job
= KIO::statDetails(m_model
->rootItem().url(), KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
1555 const auto entry
= job
->statResult();
1556 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1557 totalFileSize
= static_cast<KIO::filesize_t
>(entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1558 countFileSize
= false;
1561 for (int i
= 0; i
< itemCount
; ++i
) {
1562 const KFileItem item
= m_model
->fileItem(i
);
1567 if (countFileSize
) {
1568 totalFileSize
+= item
.size();
1574 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1576 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1578 // verify that only one item is selected
1579 if (selectionManager
->selectedItems().count() == 1) {
1580 const int index
= selectionManager
->currentItem();
1581 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1583 // check if the selected item was the same item that started the twoClicksRenaming
1584 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1585 renameSelectedItems();
1590 void DolphinView::slotTrashFileFinished(KJob
* job
)
1592 if (job
->error() == 0) {
1593 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1594 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1595 Q_EMIT
errorMessage(job
->errorString());
1599 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1601 if (job
->error() == 0) {
1602 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1603 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1604 Q_EMIT
errorMessage(job
->errorString());
1608 void DolphinView::slotRenamingResult(KJob
* job
)
1611 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1613 const QUrl newUrl
= copyJob
->destUrl();
1614 const int index
= m_model
->index(newUrl
);
1616 QHash
<QByteArray
, QVariant
> data
;
1617 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1618 data
.insert("text", oldUrl
.fileName());
1619 m_model
->setData(index
, data
);
1624 void DolphinView::slotDirectoryLoadingStarted()
1627 updatePlaceholderLabel();
1629 // Disable the writestate temporary until it can be determined in a fast way
1630 // in DolphinView::slotDirectoryLoadingCompleted()
1631 if (m_isFolderWritable
) {
1632 m_isFolderWritable
= false;
1633 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1636 Q_EMIT
directoryLoadingStarted();
1639 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::slotDirectoryLoadingCanceled()
1660 updatePlaceholderLabel();
1662 Q_EMIT
directoryLoadingCanceled();
1665 void DolphinView::slotItemsChanged()
1667 m_assureVisibleCurrentIndex
= false;
1670 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1673 Q_ASSERT(m_model
->sortOrder() == current
);
1675 ViewProperties
props(viewPropertiesUrl());
1676 props
.setSortOrder(current
);
1678 Q_EMIT
sortOrderChanged(current
);
1681 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1684 Q_ASSERT(m_model
->sortRole() == current
);
1686 ViewProperties
props(viewPropertiesUrl());
1687 props
.setSortRole(current
);
1689 Q_EMIT
sortRoleChanged(current
);
1692 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1693 const QList
<QByteArray
>& previous
)
1696 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1698 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1700 m_visibleRoles
= current
;
1702 ViewProperties
props(viewPropertiesUrl());
1703 props
.setVisibleRoles(m_visibleRoles
);
1705 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1708 void DolphinView::slotRoleEditingCanceled()
1710 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1711 this, &DolphinView::slotRoleEditingFinished
);
1714 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1716 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1717 this, &DolphinView::slotRoleEditingFinished
);
1719 if (index
< 0 || index
>= m_model
->count()) {
1723 if (role
== "text") {
1724 const KFileItem oldItem
= m_model
->fileItem(index
);
1725 const QString newName
= value
.toString();
1726 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1727 const QUrl oldUrl
= oldItem
.url();
1729 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1730 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1733 //Confirm hiding file/directory by renaming inline
1734 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1735 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1736 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1738 const auto code
= KMessageBox::questionYesNo(this,
1739 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1740 "Do you still want to rename it?")
1741 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1742 "Do you still want to rename it?"),
1743 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1745 KStandardGuiItem::cancel(),
1746 QStringLiteral("ConfirmHide")
1749 if (code
== KMessageBox::No
) {
1755 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1756 if (!newNameExistsAlready
) {
1757 // Only change the data in the model if no item with the new name
1758 // is in the model yet. If there is an item with the new name
1759 // already, calling KIO::CopyJob will open a dialog
1760 // asking for a new name, and KFileItemModel will update the
1761 // data when the dir lister signals that the file name has changed.
1762 QHash
<QByteArray
, QVariant
> data
;
1763 data
.insert(role
, value
);
1764 m_model
->setData(index
, data
);
1767 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1768 KJobWidgets::setWindow(job
, this);
1769 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1770 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1772 forceUrlsSelection(newUrl
, {newUrl
});
1774 if (!newNameExistsAlready
) {
1775 // Only connect the result signal if there is no item with the new name
1776 // in the model yet, see bug 328262.
1777 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1783 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1785 if (!url
.isValid()) {
1786 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1787 if (location
.isEmpty()) {
1788 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1790 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1796 m_model
->refreshDirectory(url
);
1798 m_model
->loadDirectory(url
);
1802 void DolphinView::applyViewProperties()
1804 const ViewProperties
props(viewPropertiesUrl());
1805 applyViewProperties(props
);
1808 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1810 m_view
->beginTransaction();
1812 const Mode mode
= props
.viewMode();
1813 if (m_mode
!= mode
) {
1814 const Mode previousMode
= m_mode
;
1817 // Changing the mode might result in changing
1818 // the zoom level. Remember the old zoom level so
1819 // that zoomLevelChanged() can get emitted.
1820 const int oldZoomLevel
= m_view
->zoomLevel();
1823 Q_EMIT
modeChanged(m_mode
, previousMode
);
1825 if (m_view
->zoomLevel() != oldZoomLevel
) {
1826 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1830 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1831 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1832 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1833 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1836 const bool groupedSorting
= props
.groupedSorting();
1837 if (groupedSorting
!= m_model
->groupedSorting()) {
1838 m_model
->setGroupedSorting(groupedSorting
);
1839 Q_EMIT
groupedSortingChanged(groupedSorting
);
1842 const QByteArray sortRole
= props
.sortRole();
1843 if (sortRole
!= m_model
->sortRole()) {
1844 m_model
->setSortRole(sortRole
);
1845 Q_EMIT
sortRoleChanged(sortRole
);
1848 const Qt::SortOrder sortOrder
= props
.sortOrder();
1849 if (sortOrder
!= m_model
->sortOrder()) {
1850 m_model
->setSortOrder(sortOrder
);
1851 Q_EMIT
sortOrderChanged(sortOrder
);
1854 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1855 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1856 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1857 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1860 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1861 if (visibleRoles
!= m_visibleRoles
) {
1862 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1863 m_visibleRoles
= visibleRoles
;
1864 m_view
->setVisibleRoles(visibleRoles
);
1865 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1868 const bool previewsShown
= props
.previewsShown();
1869 if (previewsShown
!= m_view
->previewsShown()) {
1870 const int oldZoomLevel
= zoomLevel();
1872 m_view
->setPreviewsShown(previewsShown
);
1873 Q_EMIT
previewsShownChanged(previewsShown
);
1875 // Changing the preview-state might result in a changed zoom-level
1876 if (oldZoomLevel
!= zoomLevel()) {
1877 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1881 KItemListView
* itemListView
= m_container
->controller()->view();
1882 if (itemListView
->isHeaderVisible()) {
1883 KItemListHeader
* header
= itemListView
->header();
1884 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1885 const int rolesCount
= m_visibleRoles
.count();
1886 if (headerColumnWidths
.count() == rolesCount
) {
1887 header
->setAutomaticColumnResizing(false);
1889 QHash
<QByteArray
, qreal
> columnWidths
;
1890 for (int i
= 0; i
< rolesCount
; ++i
) {
1891 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1893 header
->setColumnWidths(columnWidths
);
1895 header
->setAutomaticColumnResizing(true);
1899 m_view
->endTransaction();
1902 void DolphinView::applyModeToView()
1905 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1906 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1907 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1908 default: Q_ASSERT(false); break;
1912 void DolphinView::pasteToUrl(const QUrl
& url
)
1914 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1915 KJobWidgets::setWindow(job
, this);
1916 m_clearSelectionBeforeSelectingNewItems
= true;
1917 m_markFirstNewlySelectedItemAsCurrent
= true;
1918 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1919 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1922 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1926 const KFileItemList items
= selectedItems();
1927 urls
.reserve(items
.count());
1928 for (const KFileItem
& item
: items
) {
1929 urls
.append(item
.url());
1932 if (itemsExpandable()) {
1933 // TODO: Check if we still need KDirModel for this in KDE 5.0
1934 urls
= KDirModel::simplifiedUrlList(urls
);
1940 QMimeData
* DolphinView::selectionMimeData() const
1942 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1943 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1945 return m_model
->createMimeData(selectedIndexes
);
1948 void DolphinView::updateWritableState()
1950 const bool wasFolderWritable
= m_isFolderWritable
;
1951 m_isFolderWritable
= false;
1953 KFileItem item
= m_model
->rootItem();
1954 if (item
.isNull()) {
1955 // Try to find out if the URL is writable even if the "root item" is
1956 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1957 item
= KFileItem(url());
1958 item
.setDelayedMimeTypes(true);
1961 KFileItemListProperties
capabilities(KFileItemList() << item
);
1962 m_isFolderWritable
= capabilities
.supportsWriting();
1964 if (m_isFolderWritable
!= wasFolderWritable
) {
1965 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1969 QUrl
DolphinView::viewPropertiesUrl() const
1971 if (m_viewPropertiesContext
.isEmpty()) {
1976 url
.setScheme(m_url
.scheme());
1977 url
.setPath(m_viewPropertiesContext
);
1981 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
1983 forceUrlsSelection(urls
.first(), urls
);
1986 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
1989 m_clearSelectionBeforeSelectingNewItems
= true;
1990 markUrlAsCurrent(current
);
1991 markUrlsAsSelected(selected
);
1994 void DolphinView::copyPathToClipboard()
1996 const KFileItemList list
= selectedItems();
1997 if (list
.isEmpty()) {
2000 const KFileItem
& item
= list
.at(0);
2001 QString path
= item
.localPath();
2002 if (path
.isEmpty()) {
2003 path
= item
.url().toDisplayString();
2005 QClipboard
* clipboard
= QApplication::clipboard();
2006 if (clipboard
== nullptr) {
2009 clipboard
->setText(path
);
2012 void DolphinView::slotIncreaseZoom()
2014 setZoomLevel(zoomLevel() + 1);
2017 void DolphinView::slotDecreaseZoom()
2019 setZoomLevel(zoomLevel() - 1);
2022 void DolphinView::slotSwipeUp()
2024 Q_EMIT
goUpRequested();
2027 void DolphinView::updatePlaceholderLabel()
2029 if (m_loading
|| itemsCount() > 0) {
2030 m_placeholderLabel
->setVisible(false);
2034 if (!nameFilter().isEmpty()) {
2035 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2036 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2037 m_placeholderLabel
->setText(i18n("No items matching the search"));
2038 } else if (m_url
.scheme() == QLatin1String("trash")) {
2039 m_placeholderLabel
->setText(i18n("Trash is empty"));
2040 } else if (m_url
.scheme() == QLatin1String("tags")) {
2041 m_placeholderLabel
->setText(i18n("No tags"));
2042 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2043 m_placeholderLabel
->setText(i18n("No recently used items"));
2044 } else if (m_url
.scheme() == QLatin1String("smb")) {
2045 m_placeholderLabel
->setText(i18n("No shared folders found"));
2046 } else if (m_url
.scheme() == QLatin1String("network")) {
2047 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2048 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2049 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2050 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2051 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2053 m_placeholderLabel
->setText(i18n("Folder is empty"));
2056 m_placeholderLabel
->setVisible(true);