2 * SPDX-FileCopyrightText: 2006-2009 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2006 Gregor Kališnik <gregor@podnapisi.net>
5 * SPDX-License-Identifier: GPL-2.0-or-later
8 #include "dolphinview.h"
10 #include "dolphin_detailsmodesettings.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphinitemlistview.h"
13 #include "dolphinnewfilemenuobserver.h"
14 #include "draganddrophelper.h"
15 #include "kitemviews/kfileitemlistview.h"
16 #include "kitemviews/kfileitemmodel.h"
17 #include "kitemviews/kitemlistcontainer.h"
18 #include "kitemviews/kitemlistcontroller.h"
19 #include "kitemviews/kitemlistheader.h"
20 #include "kitemviews/kitemlistselectionmanager.h"
21 #include "versioncontrol/versioncontrolobserver.h"
22 #include "viewproperties.h"
23 #include "views/tooltips/tooltipmanager.h"
24 #include "zoomlevelinfo.h"
27 #include <Baloo/IndexerConfig>
29 #include <KColorScheme>
30 #include <KDesktopFile>
32 #include <KFileItemListProperties>
34 #include <KIO/CopyJob>
35 #include <KIO/DeleteJob>
36 #include <KIO/DropJob>
37 #include <KIO/JobUiDelegate>
39 #include <KIO/PasteJob>
40 #include <KIO/PreviewJob>
41 #include <KIO/RenameFileDialog>
42 #include <KJobWidgets>
43 #include <KLocalizedString>
44 #include <KMessageBox>
45 #include <KProtocolManager>
47 #include <QAbstractItemView>
48 #include <QApplication>
51 #include <QGraphicsOpacityEffect>
52 #include <QGraphicsSceneDragDropEvent>
55 #include <QMimeDatabase>
56 #include <QPixmapCache>
61 #include <QVBoxLayout>
63 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
66 m_tabsForFiles(false),
67 m_assureVisibleCurrentIndex(false),
68 m_isFolderWritable(true),
71 m_viewPropertiesContext(),
72 m_mode(DolphinView::IconsView
),
78 m_toolTipManager(nullptr),
79 m_selectionChangedTimer(nullptr),
81 m_scrollToCurrentItem(false),
82 m_restoredContentsPosition(),
84 m_clearSelectionBeforeSelectingNewItems(false),
85 m_markFirstNewlySelectedItemAsCurrent(false),
86 m_versionControlObserver(nullptr),
87 m_twoClicksRenamingTimer(nullptr),
88 m_placeholderLabel(nullptr)
90 m_topLayout
= new QVBoxLayout(this);
91 m_topLayout
->setSpacing(0);
92 m_topLayout
->setContentsMargins(0, 0, 0, 0);
94 // When a new item has been created by the "Create New..." menu, the item should
95 // get selected and it must be assured that the item will get visible. As the
96 // creation is done asynchronously, several signals must be checked:
97 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
98 this, &DolphinView::observeCreatedItem
);
100 m_selectionChangedTimer
= new QTimer(this);
101 m_selectionChangedTimer
->setSingleShot(true);
102 m_selectionChangedTimer
->setInterval(300);
103 connect(m_selectionChangedTimer
, &QTimer::timeout
,
104 this, &DolphinView::emitSelectionChangedSignal
);
106 m_model
= new KFileItemModel(this);
107 m_view
= new DolphinItemListView();
108 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
109 m_view
->setVisibleRoles({"text"});
112 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
113 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
114 controller
->setAutoActivationDelay(delay
);
116 // The EnlargeSmallPreviews setting can only be changed after the model
117 // has been set in the view by KItemListController.
118 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
120 m_container
= new KItemListContainer(controller
, this);
121 m_container
->installEventFilter(this);
122 setFocusProxy(m_container
);
123 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
124 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
126 // Show some placeholder text for empty folders
127 // This is made using a heavily-modified QLabel rather than a KTitleWidget
128 // because KTitleWidget can't be told to turn off mouse-selectable text
129 m_placeholderLabel
= new QLabel(this);
130 QFont placeholderLabelFont
;
131 // To match the size of a level 2 Heading/KTitleWidget
132 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
133 m_placeholderLabel
->setFont(placeholderLabelFont
);
134 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
135 m_placeholderLabel
->setWordWrap(true);
136 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
137 // Match opacity of QML placeholder label component
138 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
139 effect
->setOpacity(0.5);
140 m_placeholderLabel
->setGraphicsEffect(effect
);
141 // Set initial text and visibility
142 updatePlaceholderLabel();
144 auto *centeringLayout
= new QVBoxLayout(m_container
);
145 centeringLayout
->addWidget(m_placeholderLabel
);
146 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
148 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
149 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
150 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
151 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
152 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
153 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
154 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
155 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
156 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
157 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
158 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
159 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
160 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
161 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
162 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
163 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
164 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
166 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
167 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
168 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::directoryLoadingCanceled
);
169 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
170 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
171 connect(m_model
, &KFileItemModel::itemsChanged
,
172 this, &DolphinView::slotItemsChanged
);
173 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
174 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
175 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
176 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
177 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
178 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
180 connect(this, &DolphinView::itemCountChanged
,
181 this, &DolphinView::updatePlaceholderLabel
);
182 connect(this, &DolphinView::urlChanged
,
183 this, &DolphinView::updatePlaceholderLabel
);
185 m_view
->installEventFilter(this);
186 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
187 this, &DolphinView::slotSortOrderChangedByHeader
);
188 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
189 this, &DolphinView::slotSortRoleChangedByHeader
);
190 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
191 this, &DolphinView::slotVisibleRolesChangedByHeader
);
192 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
193 this, &DolphinView::slotRoleEditingCanceled
);
194 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
195 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
197 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
198 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
199 this, &DolphinView::slotSelectionChanged
);
202 m_toolTipManager
= new ToolTipManager(this);
203 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
206 m_versionControlObserver
= new VersionControlObserver(this);
207 m_versionControlObserver
->setView(this);
208 m_versionControlObserver
->setModel(m_model
);
209 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
210 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
211 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
213 m_twoClicksRenamingTimer
= new QTimer(this);
214 m_twoClicksRenamingTimer
->setSingleShot(true);
215 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
217 applyViewProperties();
218 m_topLayout
->addWidget(m_container
);
223 DolphinView::~DolphinView()
227 QUrl
DolphinView::url() const
232 void DolphinView::setActive(bool active
)
234 if (active
== m_active
) {
243 m_container
->setFocus();
245 Q_EMIT
writeStateChanged(m_isFolderWritable
);
249 bool DolphinView::isActive() const
254 void DolphinView::setMode(Mode mode
)
256 if (mode
!= m_mode
) {
257 ViewProperties
props(viewPropertiesUrl());
258 props
.setViewMode(mode
);
260 // We pass the new ViewProperties to applyViewProperties, rather than
261 // storing them on disk and letting applyViewProperties() read them
262 // from there, to prevent that changing the view mode fails if the
263 // .directory file is not writable (see bug 318534).
264 applyViewProperties(props
);
268 DolphinView::Mode
DolphinView::mode() const
273 void DolphinView::setPreviewsShown(bool show
)
275 if (previewsShown() == show
) {
279 ViewProperties
props(viewPropertiesUrl());
280 props
.setPreviewsShown(show
);
282 const int oldZoomLevel
= m_view
->zoomLevel();
283 m_view
->setPreviewsShown(show
);
284 Q_EMIT
previewsShownChanged(show
);
286 const int newZoomLevel
= m_view
->zoomLevel();
287 if (newZoomLevel
!= oldZoomLevel
) {
288 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
292 bool DolphinView::previewsShown() const
294 return m_view
->previewsShown();
297 void DolphinView::setHiddenFilesShown(bool show
)
299 if (m_model
->showHiddenFiles() == show
) {
303 const KFileItemList itemList
= selectedItems();
304 m_selectedUrls
.clear();
305 m_selectedUrls
= itemList
.urlList();
307 ViewProperties
props(viewPropertiesUrl());
308 props
.setHiddenFilesShown(show
);
310 m_model
->setShowHiddenFiles(show
);
311 Q_EMIT
hiddenFilesShownChanged(show
);
314 bool DolphinView::hiddenFilesShown() const
316 return m_model
->showHiddenFiles();
319 void DolphinView::setGroupedSorting(bool grouped
)
321 if (grouped
== groupedSorting()) {
325 ViewProperties
props(viewPropertiesUrl());
326 props
.setGroupedSorting(grouped
);
329 m_container
->controller()->model()->setGroupedSorting(grouped
);
331 Q_EMIT
groupedSortingChanged(grouped
);
334 bool DolphinView::groupedSorting() const
336 return m_model
->groupedSorting();
339 KFileItemList
DolphinView::items() const
342 const int itemCount
= m_model
->count();
343 list
.reserve(itemCount
);
345 for (int i
= 0; i
< itemCount
; ++i
) {
346 list
.append(m_model
->fileItem(i
));
352 int DolphinView::itemsCount() const
354 return m_model
->count();
357 KFileItemList
DolphinView::selectedItems() const
359 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
361 KFileItemList selectedItems
;
362 const auto items
= selectionManager
->selectedItems();
363 selectedItems
.reserve(items
.count());
364 for (int index
: items
) {
365 selectedItems
.append(m_model
->fileItem(index
));
367 return selectedItems
;
370 int DolphinView::selectedItemsCount() const
372 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
373 return selectionManager
->selectedItems().count();
376 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
378 m_selectedUrls
= urls
;
381 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
383 m_currentItemUrl
= url
;
384 m_scrollToCurrentItem
= true;
387 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
389 const KItemListSelectionManager::SelectionMode mode
= enabled
390 ? KItemListSelectionManager::Select
391 : KItemListSelectionManager::Deselect
;
392 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
394 for (int index
= 0; index
< m_model
->count(); index
++) {
395 const KFileItem item
= m_model
->fileItem(index
);
396 if (regexp
.match(item
.text()).hasMatch()) {
397 // An alternative approach would be to store the matching items in a KItemSet and
398 // select them in one go after the loop, but we'd need a new function
399 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
401 selectionManager
->setSelected(index
, 1, mode
);
406 void DolphinView::setZoomLevel(int level
)
408 const int oldZoomLevel
= zoomLevel();
409 m_view
->setZoomLevel(level
);
410 if (zoomLevel() != oldZoomLevel
) {
412 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
416 int DolphinView::zoomLevel() const
418 return m_view
->zoomLevel();
421 void DolphinView::setSortRole(const QByteArray
& role
)
423 if (role
!= sortRole()) {
424 updateSortRole(role
);
428 QByteArray
DolphinView::sortRole() const
430 const KItemModelBase
* model
= m_container
->controller()->model();
431 return model
->sortRole();
434 void DolphinView::setSortOrder(Qt::SortOrder order
)
436 if (sortOrder() != order
) {
437 updateSortOrder(order
);
441 Qt::SortOrder
DolphinView::sortOrder() const
443 return m_model
->sortOrder();
446 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
448 if (sortFoldersFirst() != foldersFirst
) {
449 updateSortFoldersFirst(foldersFirst
);
453 bool DolphinView::sortFoldersFirst() const
455 return m_model
->sortDirectoriesFirst();
458 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
460 const QList
<QByteArray
> previousRoles
= roles
;
462 ViewProperties
props(viewPropertiesUrl());
463 props
.setVisibleRoles(roles
);
465 m_visibleRoles
= roles
;
466 m_view
->setVisibleRoles(roles
);
468 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
471 QList
<QByteArray
> DolphinView::visibleRoles() const
473 return m_visibleRoles
;
476 void DolphinView::reload()
478 QByteArray viewState
;
479 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
480 saveState(saveStream
);
483 loadDirectory(url(), true);
485 QDataStream
restoreStream(viewState
);
486 restoreState(restoreStream
);
489 void DolphinView::readSettings()
491 const int oldZoomLevel
= m_view
->zoomLevel();
493 GeneralSettings::self()->load();
494 m_view
->readSettings();
495 applyViewProperties();
497 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
498 m_container
->controller()->setAutoActivationDelay(delay
);
500 const int newZoomLevel
= m_view
->zoomLevel();
501 if (newZoomLevel
!= oldZoomLevel
) {
502 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
506 void DolphinView::writeSettings()
508 GeneralSettings::self()->save();
509 m_view
->writeSettings();
512 void DolphinView::setNameFilter(const QString
& nameFilter
)
514 m_model
->setNameFilter(nameFilter
);
517 QString
DolphinView::nameFilter() const
519 return m_model
->nameFilter();
522 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
524 return m_model
->setMimeTypeFilters(filters
);
527 QStringList
DolphinView::mimeTypeFilters() const
529 return m_model
->mimeTypeFilters();
532 QString
DolphinView::statusBarText() const
540 KIO::filesize_t totalFileSize
= 0;
542 if (m_container
->controller()->selectionManager()->hasSelection()) {
543 // Give a summary of the status of the selected files
544 const KFileItemList list
= selectedItems();
545 for (const KFileItem
& item
: list
) {
550 totalFileSize
+= item
.size();
554 if (folderCount
+ fileCount
== 1) {
555 // If only one item is selected, show info about it
556 return list
.first().getStatusBarInfo();
558 // At least 2 items are selected
559 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
560 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
563 calculateItemCount(fileCount
, folderCount
, totalFileSize
);
564 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
565 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
568 if (fileCount
> 0 && folderCount
> 0) {
569 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
570 foldersText
, filesText
,
571 KFormat().formatByteSize(totalFileSize
));
572 } else if (fileCount
> 0) {
573 summary
= i18nc("@info:status files (size)", "%1 (%2)",
575 KFormat().formatByteSize(totalFileSize
));
576 } else if (folderCount
> 0) {
577 summary
= foldersText
;
579 summary
= i18nc("@info:status", "0 Folders, 0 Files");
585 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
587 QList
<QAction
*> actions
;
589 if (items
.isEmpty()) {
590 const KFileItem item
= m_model
->rootItem();
591 if (!item
.isNull()) {
592 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
595 actions
= m_versionControlObserver
->actions(items
);
601 void DolphinView::setUrl(const QUrl
& url
)
613 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
614 this, &DolphinView::slotRoleEditingFinished
);
616 // It is important to clear the items from the model before
617 // applying the view properties, otherwise expensive operations
618 // might be done on the existing items although they get cleared
619 // anyhow afterwards by loadDirectory().
621 applyViewProperties();
624 Q_EMIT
urlChanged(url
);
627 void DolphinView::selectAll()
629 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
630 selectionManager
->setSelected(0, m_model
->count());
633 void DolphinView::invertSelection()
635 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
636 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
639 void DolphinView::clearSelection()
641 m_selectedUrls
.clear();
642 m_container
->controller()->selectionManager()->clearSelection();
645 void DolphinView::renameSelectedItems()
647 const KFileItemList items
= selectedItems();
648 if (items
.isEmpty()) {
652 if (items
.count() == 1 && GeneralSettings::renameInline()) {
653 const int index
= m_model
->index(items
.first());
654 m_view
->editRole(index
, "text");
658 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
659 this, &DolphinView::slotRoleEditingFinished
);
661 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
662 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
663 this, &DolphinView::slotRenameDialogRenamingFinished
);
668 // Assure that the current index remains visible when KFileItemModel
669 // will notify the view about changed items (which might result in
670 // a changed sorting).
671 m_assureVisibleCurrentIndex
= true;
674 void DolphinView::trashSelectedItems()
676 const QList
<QUrl
> list
= simplifiedSelectedUrls();
677 KIO::JobUiDelegate uiDelegate
;
678 uiDelegate
.setWindow(window());
679 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
680 KIO::Job
* job
= KIO::trash(list
);
681 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
682 KJobWidgets::setWindow(job
, this);
683 connect(job
, &KIO::Job::result
,
684 this, &DolphinView::slotTrashFileFinished
);
688 void DolphinView::deleteSelectedItems()
690 const QList
<QUrl
> list
= simplifiedSelectedUrls();
692 KIO::JobUiDelegate uiDelegate
;
693 uiDelegate
.setWindow(window());
694 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
695 KIO::Job
* job
= KIO::del(list
);
696 KJobWidgets::setWindow(job
, this);
697 connect(job
, &KIO::Job::result
,
698 this, &DolphinView::slotDeleteFileFinished
);
702 void DolphinView::cutSelectedItemsToClipboard()
704 QMimeData
* mimeData
= selectionMimeData();
705 KIO::setClipboardDataCut(mimeData
, true);
706 QApplication::clipboard()->setMimeData(mimeData
);
709 void DolphinView::copySelectedItemsToClipboard()
711 QMimeData
* mimeData
= selectionMimeData();
712 QApplication::clipboard()->setMimeData(mimeData
);
715 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
717 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
718 KJobWidgets::setWindow(job
, this);
720 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
721 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
722 KIO::FileUndoManager::self()->recordCopyJob(job
);
725 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
727 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
728 KJobWidgets::setWindow(job
, this);
730 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
731 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
732 KIO::FileUndoManager::self()->recordCopyJob(job
);
736 void DolphinView::paste()
741 void DolphinView::pasteIntoFolder()
743 const KFileItemList items
= selectedItems();
744 if ((items
.count() == 1) && items
.first().isDir()) {
745 pasteToUrl(items
.first().url());
749 void DolphinView::duplicateSelectedItems()
751 const KFileItemList itemList
= selectedItems();
752 if (itemList
.isEmpty()) {
756 const QMimeDatabase db
;
758 // Duplicate all selected items and append "copy" to the end of the file name
759 // but before the filename extension, if present
760 QList
<QUrl
> newSelection
;
761 for (const auto &item
: itemList
) {
762 const QUrl originalURL
= item
.url();
763 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
764 const QString originalFileName
= item
.name();
766 QString extension
= db
.suffixForFileName(originalFileName
);
768 QUrl duplicateURL
= originalURL
;
770 // No extension; new filename is "<oldfilename> copy"
771 if (extension
.isEmpty()) {
772 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
773 // There's an extension; new filename is "<oldfilename> copy.<extension>"
775 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
776 extension
= QLatin1String(".") + extension
;
777 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
778 // Preserve file's original filename extension in case the casing differs
779 // from what QMimeDatabase::suffixForFileName() returned
780 const QString originalExtension
= originalFileName
.right(extension
.size());
781 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
784 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
785 KJobWidgets::setWindow(job
, this);
788 newSelection
<< duplicateURL
;
789 KIO::FileUndoManager::self()->recordCopyJob(job
);
793 forceUrlsSelection(newSelection
.first(), newSelection
);
796 void DolphinView::stopLoading()
798 m_model
->cancelDirectoryLoading();
801 void DolphinView::updatePalette()
803 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
808 QWidget
* viewport
= m_container
->viewport();
811 palette
.setColor(viewport
->backgroundRole(), color
);
812 viewport
->setPalette(palette
);
818 void DolphinView::abortTwoClicksRenaming()
820 m_twoClicksRenamingItemUrl
.clear();
821 m_twoClicksRenamingTimer
->stop();
824 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
826 switch (event
->type()) {
827 case QEvent::PaletteChange
:
829 QPixmapCache::clear();
832 case QEvent::WindowActivate
:
833 case QEvent::WindowDeactivate
:
837 case QEvent::KeyPress
:
838 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
839 if (GeneralSettings::useTabForSwitchingSplitView()) {
840 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
841 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
842 Q_EMIT
toggleActiveViewRequested();
847 case QEvent::FocusIn
:
848 if (watched
== m_container
) {
853 case QEvent::GraphicsSceneDragEnter
:
854 if (watched
== m_view
) {
856 abortTwoClicksRenaming();
860 case QEvent::GraphicsSceneDragLeave
:
861 if (watched
== m_view
) {
866 case QEvent::GraphicsSceneDrop
:
867 if (watched
== m_view
) {
874 return QWidget::eventFilter(watched
, event
);
877 void DolphinView::wheelEvent(QWheelEvent
* event
)
879 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
880 const QPoint numDegrees
= event
->angleDelta() / 8;
881 const QPoint numSteps
= numDegrees
/ 15;
883 setZoomLevel(zoomLevel() + numSteps
.y());
890 void DolphinView::hideEvent(QHideEvent
* event
)
893 QWidget::hideEvent(event
);
896 bool DolphinView::event(QEvent
* event
)
898 if (event
->type() == QEvent::WindowDeactivate
) {
900 * Dolphin leaves file preview tooltips open even when is not visible.
902 * Hide tool-tip when Dolphin loses focus.
905 abortTwoClicksRenaming();
908 return QWidget::event(event
);
911 void DolphinView::activate()
916 void DolphinView::slotItemActivated(int index
)
918 abortTwoClicksRenaming();
920 const KFileItem item
= m_model
->fileItem(index
);
921 if (!item
.isNull()) {
922 Q_EMIT
itemActivated(item
);
926 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
928 Q_ASSERT(indexes
.count() >= 2);
930 abortTwoClicksRenaming();
932 if (indexes
.count() > 5) {
933 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
934 const int answer
= KMessageBox::warningYesNo(this, question
);
935 if (answer
!= KMessageBox::Yes
) {
941 items
.reserve(indexes
.count());
943 for (int index
: indexes
) {
944 KFileItem item
= m_model
->fileItem(index
);
945 const QUrl
& url
= openItemAsFolderUrl(item
);
947 if (!url
.isEmpty()) { // Open folders in new tabs
948 Q_EMIT
tabRequested(url
, DolphinTabWidget::AfterLastTab
);
954 if (items
.count() == 1) {
955 Q_EMIT
itemActivated(items
.first());
956 } else if (items
.count() > 1) {
957 Q_EMIT
itemsActivated(items
);
961 void DolphinView::slotItemMiddleClicked(int index
)
963 const KFileItem
& item
= m_model
->fileItem(index
);
964 const QUrl
& url
= openItemAsFolderUrl(item
);
965 if (!url
.isEmpty()) {
966 Q_EMIT
tabRequested(url
, DolphinTabWidget::AfterCurrentTab
);
967 } else if (isTabsForFilesEnabled()) {
968 Q_EMIT
tabRequested(item
.url(), DolphinTabWidget::AfterCurrentTab
);
972 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
974 // Force emit of a selection changed signal before we request the
975 // context menu, to update the edit-actions first. (See Bug 294013)
976 if (m_selectionChangedTimer
->isActive()) {
977 emitSelectionChangedSignal();
980 const KFileItem item
= m_model
->fileItem(index
);
981 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
984 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
986 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
989 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
991 ViewProperties
props(viewPropertiesUrl());
993 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
995 KItemListView
* view
= m_container
->controller()->view();
996 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
998 bool indexingEnabled
= false;
1000 Baloo::IndexerConfig config
;
1001 indexingEnabled
= config
.fileIndexingEnabled();
1005 QMenu
* groupMenu
= nullptr;
1007 // Add all roles to the menu that can be shown or hidden by the user
1008 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1009 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1010 if (info
.role
== "text") {
1011 // It should not be possible to hide the "text" role
1015 const QString text
= m_model
->roleDescription(info
.role
);
1016 QAction
* action
= nullptr;
1017 if (info
.group
.isEmpty()) {
1018 action
= menu
->addAction(text
);
1020 if (!groupMenu
|| info
.group
!= groupName
) {
1021 groupName
= info
.group
;
1022 groupMenu
= menu
->addMenu(groupName
);
1025 action
= groupMenu
->addAction(text
);
1028 action
->setCheckable(true);
1029 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1030 action
->setData(info
.role
);
1032 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1033 (info
.requiresBaloo
) ||
1034 (info
.requiresIndexer
&& indexingEnabled
);
1035 action
->setEnabled(enable
);
1038 menu
->addSeparator();
1040 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1041 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1043 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1044 autoAdjustWidthsAction
->setCheckable(true);
1045 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1046 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1048 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1049 customWidthsAction
->setCheckable(true);
1050 customWidthsAction
->setChecked(!autoColumnWidths
);
1051 customWidthsAction
->setActionGroup(widthsGroup
);
1053 QAction
* action
= menu
->exec(pos
.toPoint());
1054 if (menu
&& action
) {
1055 KItemListHeader
* header
= view
->header();
1057 if (action
== autoAdjustWidthsAction
) {
1058 // Clear the column-widths from the viewproperties and turn on
1059 // the automatic resizing of the columns
1060 props
.setHeaderColumnWidths(QList
<int>());
1061 header
->setAutomaticColumnResizing(true);
1062 } else if (action
== customWidthsAction
) {
1063 // Apply the current column-widths as custom column-widths and turn
1064 // off the automatic resizing of the columns
1065 QList
<int> columnWidths
;
1066 const auto visibleRoles
= view
->visibleRoles();
1067 columnWidths
.reserve(visibleRoles
.count());
1068 for (const QByteArray
& role
: visibleRoles
) {
1069 columnWidths
.append(header
->columnWidth(role
));
1071 props
.setHeaderColumnWidths(columnWidths
);
1072 header
->setAutomaticColumnResizing(false);
1074 // Show or hide the selected role
1075 const QByteArray selectedRole
= action
->data().toByteArray();
1077 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1078 if (action
->isChecked()) {
1079 visibleRoles
.append(selectedRole
);
1081 visibleRoles
.removeOne(selectedRole
);
1084 view
->setVisibleRoles(visibleRoles
);
1085 props
.setVisibleRoles(visibleRoles
);
1087 QList
<int> columnWidths
;
1088 if (!header
->automaticColumnResizing()) {
1089 const auto visibleRoles
= view
->visibleRoles();
1090 columnWidths
.reserve(visibleRoles
.count());
1091 for (const QByteArray
& role
: visibleRoles
) {
1092 columnWidths
.append(header
->columnWidth(role
));
1095 props
.setHeaderColumnWidths(columnWidths
);
1102 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1104 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1106 ViewProperties
props(viewPropertiesUrl());
1107 QList
<int> columnWidths
= props
.headerColumnWidths();
1108 if (columnWidths
.count() != visibleRoles
.count()) {
1109 columnWidths
.clear();
1110 columnWidths
.reserve(visibleRoles
.count());
1111 const KItemListHeader
* header
= m_view
->header();
1112 for (const QByteArray
& role
: visibleRoles
) {
1113 const int width
= header
->columnWidth(role
);
1114 columnWidths
.append(width
);
1118 const int roleIndex
= visibleRoles
.indexOf(role
);
1119 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1120 columnWidths
[roleIndex
] = current
;
1122 props
.setHeaderColumnWidths(columnWidths
);
1125 void DolphinView::slotItemHovered(int index
)
1127 const KFileItem item
= m_model
->fileItem(index
);
1129 if (GeneralSettings::showToolTips() && !m_dragging
) {
1130 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1131 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1132 itemRect
.moveTo(pos
);
1135 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1139 Q_EMIT
requestItemInfo(item
);
1142 void DolphinView::slotItemUnhovered(int index
)
1146 Q_EMIT
requestItemInfo(KFileItem());
1149 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1152 KFileItem destItem
= m_model
->fileItem(index
);
1153 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1154 // Use the URL of the view as drop target if the item is no directory
1156 destItem
= m_model
->rootItem();
1159 // The item represents a directory or desktop-file
1160 destUrl
= destItem
.mostLocalUrl();
1163 QDropEvent
dropEvent(event
->pos().toPoint(),
1164 event
->possibleActions(),
1167 event
->modifiers());
1168 dropUrls(destUrl
, &dropEvent
, this);
1173 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1175 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1178 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1180 if (destUrl
== url()) {
1181 // Mark the dropped urls as selected.
1182 m_clearSelectionBeforeSelectingNewItems
= true;
1183 m_markFirstNewlySelectedItemAsCurrent
= true;
1184 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1189 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1191 if (previous
!= nullptr) {
1192 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1193 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1194 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1195 m_versionControlObserver
->setModel(nullptr);
1199 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1200 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1201 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1202 m_versionControlObserver
->setModel(fileItemModel
);
1206 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1212 if (buttons
& Qt::BackButton
) {
1213 Q_EMIT
goBackRequested();
1214 } else if (buttons
& Qt::ForwardButton
) {
1215 Q_EMIT
goForwardRequested();
1219 void DolphinView::slotSelectedItemTextPressed(int index
)
1221 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1222 const KFileItem item
= m_model
->fileItem(index
);
1223 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1224 if (capabilities
.supportsMoving()) {
1225 m_twoClicksRenamingItemUrl
= item
.url();
1226 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1231 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1233 slotItemCreated(to
);
1236 void DolphinView::slotItemCreated(const QUrl
& url
)
1238 if (m_markFirstNewlySelectedItemAsCurrent
) {
1239 markUrlAsCurrent(url
);
1240 m_markFirstNewlySelectedItemAsCurrent
= false;
1242 m_selectedUrls
<< url
;
1245 void DolphinView::slotJobResult(KJob
*job
)
1248 Q_EMIT
errorMessage(job
->errorString());
1250 if (!m_selectedUrls
.isEmpty()) {
1251 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1255 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1257 const int currentCount
= current
.count();
1258 const int previousCount
= previous
.count();
1259 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1260 (currentCount
> 0 && previousCount
== 0);
1262 // If nothing has been selected before and something got selected (or if something
1263 // was selected before and now nothing is selected) the selectionChangedSignal must
1264 // be emitted asynchronously as fast as possible to update the edit-actions.
1265 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1266 m_selectionChangedTimer
->start();
1269 void DolphinView::emitSelectionChangedSignal()
1271 m_selectionChangedTimer
->stop();
1272 Q_EMIT
selectionChanged(selectedItems());
1275 void DolphinView::updateSortRole(const QByteArray
& role
)
1277 ViewProperties
props(viewPropertiesUrl());
1278 props
.setSortRole(role
);
1280 KItemModelBase
* model
= m_container
->controller()->model();
1281 model
->setSortRole(role
);
1283 Q_EMIT
sortRoleChanged(role
);
1286 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1288 ViewProperties
props(viewPropertiesUrl());
1289 props
.setSortOrder(order
);
1291 m_model
->setSortOrder(order
);
1293 Q_EMIT
sortOrderChanged(order
);
1296 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1298 ViewProperties
props(viewPropertiesUrl());
1299 props
.setSortFoldersFirst(foldersFirst
);
1301 m_model
->setSortDirectoriesFirst(foldersFirst
);
1303 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1306 QPair
<bool, QString
> DolphinView::pasteInfo() const
1308 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1309 QPair
<bool, QString
> info
;
1310 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1314 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1316 m_tabsForFiles
= tabsForFiles
;
1319 bool DolphinView::isTabsForFilesEnabled() const
1321 return m_tabsForFiles
;
1324 bool DolphinView::itemsExpandable() const
1326 return m_mode
== DetailsView
;
1329 void DolphinView::restoreState(QDataStream
& stream
)
1331 // Read the version number of the view state and check if the version is supported.
1332 quint32 version
= 0;
1335 // The version of the view state isn't supported, we can't restore it.
1339 // Restore the current item that had the keyboard focus
1340 stream
>> m_currentItemUrl
;
1342 // Restore the previously selected items
1343 stream
>> m_selectedUrls
;
1345 // Restore the view position
1346 stream
>> m_restoredContentsPosition
;
1348 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1351 m_model
->restoreExpandedDirectories(urls
);
1354 void DolphinView::saveState(QDataStream
& stream
)
1356 stream
<< quint32(1); // View state version
1358 // Save the current item that has the keyboard focus
1359 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1360 if (currentIndex
!= -1) {
1361 KFileItem item
= m_model
->fileItem(currentIndex
);
1362 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1363 QUrl currentItemUrl
= item
.url();
1364 stream
<< currentItemUrl
;
1369 // Save the selected urls
1370 stream
<< selectedItems().urlList();
1372 // Save view position
1373 const qreal x
= m_container
->horizontalScrollBar()->value();
1374 const qreal y
= m_container
->verticalScrollBar()->value();
1375 stream
<< QPoint(x
, y
);
1377 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1378 stream
<< m_model
->expandedDirectories();
1381 KFileItem
DolphinView::rootItem() const
1383 return m_model
->rootItem();
1386 void DolphinView::setViewPropertiesContext(const QString
& context
)
1388 m_viewPropertiesContext
= context
;
1391 QString
DolphinView::viewPropertiesContext() const
1393 return m_viewPropertiesContext
;
1396 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1398 if (item
.isNull()) {
1402 QUrl url
= item
.targetUrl();
1408 if (item
.isMimeTypeKnown()) {
1409 const QString
& mimetype
= item
.mimetype();
1411 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1412 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1413 // zip:/<path>/ when clicking on a zip file, etc.
1414 // The .protocol file specifies the mimetype that the kioslave handles.
1415 // Note that we don't use mimetype inheritance since we don't want to
1416 // open OpenDocument files as zip folders...
1417 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1418 if (!protocol
.isEmpty()) {
1419 url
.setScheme(protocol
);
1424 if (mimetype
== QLatin1String("application/x-desktop")) {
1425 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1426 KDesktopFile
desktopFile(url
.toLocalFile());
1427 if (desktopFile
.hasLinkType()) {
1428 const QString linkUrl
= desktopFile
.readUrl();
1429 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1430 return QUrl::fromUserInput(linkUrl
);
1439 void DolphinView::resetZoomLevel()
1441 ViewModeSettings::ViewMode mode
;
1444 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1445 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1446 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1448 const ViewModeSettings
settings(mode
);
1449 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1450 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1453 void DolphinView::observeCreatedItem(const QUrl
& url
)
1456 forceUrlsSelection(url
, {url
});
1460 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1462 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1463 Q_EMIT
redirection(oldUrl
, newUrl
);
1464 m_url
= newUrl
; // #186947
1468 void DolphinView::updateViewState()
1470 if (m_currentItemUrl
!= QUrl()) {
1471 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1473 // if there is a selection already, leave it that way
1474 if (!selectionManager
->hasSelection()) {
1475 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1476 if (currentIndex
!= -1) {
1477 selectionManager
->setCurrentItem(currentIndex
);
1479 // scroll to current item and reset the state
1480 if (m_scrollToCurrentItem
) {
1481 m_view
->scrollToItem(currentIndex
);
1482 m_scrollToCurrentItem
= false;
1485 selectionManager
->setCurrentItem(0);
1489 m_currentItemUrl
= QUrl();
1492 if (!m_restoredContentsPosition
.isNull()) {
1493 const int x
= m_restoredContentsPosition
.x();
1494 const int y
= m_restoredContentsPosition
.y();
1495 m_restoredContentsPosition
= QPoint();
1497 m_container
->horizontalScrollBar()->setValue(x
);
1498 m_container
->verticalScrollBar()->setValue(y
);
1501 if (!m_selectedUrls
.isEmpty()) {
1502 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1504 // if there is a selection already, leave it that way
1505 if (!selectionManager
->hasSelection()) {
1506 if (m_clearSelectionBeforeSelectingNewItems
) {
1507 selectionManager
->clearSelection();
1508 m_clearSelectionBeforeSelectingNewItems
= false;
1511 KItemSet selectedItems
= selectionManager
->selectedItems();
1513 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1514 while (it
!= m_selectedUrls
.end()) {
1515 const int index
= m_model
->index(*it
);
1517 selectedItems
.insert(index
);
1518 it
= m_selectedUrls
.erase(it
);
1524 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1525 selectionManager
->setSelectedItems(selectedItems
);
1530 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1533 if (GeneralSettings::showToolTips()) {
1534 m_toolTipManager
->hideToolTip(behavior
);
1541 void DolphinView::calculateItemCount(int& fileCount
,
1543 KIO::filesize_t
& totalFileSize
) const
1545 const int itemCount
= m_model
->count();
1547 bool countFileSize
= true;
1549 if (!m_model
->rootItem().url().isValid()) {
1553 // In case we have a precomputed value
1554 const auto job
= KIO::statDetails(m_model
->rootItem().url(), KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
1556 const auto entry
= job
->statResult();
1557 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1558 totalFileSize
= static_cast<KIO::filesize_t
>(entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1559 countFileSize
= false;
1562 for (int i
= 0; i
< itemCount
; ++i
) {
1563 const KFileItem item
= m_model
->fileItem(i
);
1568 if (countFileSize
) {
1569 totalFileSize
+= item
.size();
1575 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1577 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1579 // verify that only one item is selected
1580 if (selectionManager
->selectedItems().count() == 1) {
1581 const int index
= selectionManager
->currentItem();
1582 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1584 // check if the selected item was the same item that started the twoClicksRenaming
1585 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1586 renameSelectedItems();
1591 void DolphinView::slotTrashFileFinished(KJob
* job
)
1593 if (job
->error() == 0) {
1594 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1595 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1596 Q_EMIT
errorMessage(job
->errorString());
1600 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1602 if (job
->error() == 0) {
1603 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1604 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1605 Q_EMIT
errorMessage(job
->errorString());
1609 void DolphinView::slotRenamingResult(KJob
* job
)
1612 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1614 const QUrl newUrl
= copyJob
->destUrl();
1615 const int index
= m_model
->index(newUrl
);
1617 QHash
<QByteArray
, QVariant
> data
;
1618 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1619 data
.insert("text", oldUrl
.fileName());
1620 m_model
->setData(index
, data
);
1625 void DolphinView::slotDirectoryLoadingStarted()
1627 // We don't want the placeholder label to flicker while the folder is loading
1628 m_placeholderLabel
->setVisible(false);
1630 // Disable the writestate temporary until it can be determined in a fast way
1631 // in DolphinView::slotDirectoryLoadingCompleted()
1632 if (m_isFolderWritable
) {
1633 m_isFolderWritable
= false;
1634 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1637 Q_EMIT
directoryLoadingStarted();
1640 void DolphinView::slotDirectoryLoadingCompleted()
1642 // Update the view-state. This has to be done asynchronously
1643 // because the view might not be in its final state yet.
1644 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1646 // Update the placeholder label in case we found that the folder was empty
1649 Q_EMIT
directoryLoadingCompleted();
1651 updatePlaceholderLabel();
1652 updateWritableState();
1655 void DolphinView::slotItemsChanged()
1657 m_assureVisibleCurrentIndex
= false;
1660 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1663 Q_ASSERT(m_model
->sortOrder() == current
);
1665 ViewProperties
props(viewPropertiesUrl());
1666 props
.setSortOrder(current
);
1668 Q_EMIT
sortOrderChanged(current
);
1671 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1674 Q_ASSERT(m_model
->sortRole() == current
);
1676 ViewProperties
props(viewPropertiesUrl());
1677 props
.setSortRole(current
);
1679 Q_EMIT
sortRoleChanged(current
);
1682 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1683 const QList
<QByteArray
>& previous
)
1686 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1688 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1690 m_visibleRoles
= current
;
1692 ViewProperties
props(viewPropertiesUrl());
1693 props
.setVisibleRoles(m_visibleRoles
);
1695 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1698 void DolphinView::slotRoleEditingCanceled()
1700 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1701 this, &DolphinView::slotRoleEditingFinished
);
1704 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1706 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1707 this, &DolphinView::slotRoleEditingFinished
);
1709 if (index
< 0 || index
>= m_model
->count()) {
1713 if (role
== "text") {
1714 const KFileItem oldItem
= m_model
->fileItem(index
);
1715 const QString newName
= value
.toString();
1716 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1717 const QUrl oldUrl
= oldItem
.url();
1719 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1720 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1723 //Confirm hiding file/directory by renaming inline
1724 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1725 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1726 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1728 const auto code
= KMessageBox::questionYesNo(this,
1729 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1730 "Do you still want to rename it?")
1731 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1732 "Do you still want to rename it?"),
1733 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1735 KStandardGuiItem::cancel(),
1736 QStringLiteral("ConfirmHide")
1739 if (code
== KMessageBox::No
) {
1745 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1746 if (!newNameExistsAlready
) {
1747 // Only change the data in the model if no item with the new name
1748 // is in the model yet. If there is an item with the new name
1749 // already, calling KIO::CopyJob will open a dialog
1750 // asking for a new name, and KFileItemModel will update the
1751 // data when the dir lister signals that the file name has changed.
1752 QHash
<QByteArray
, QVariant
> data
;
1753 data
.insert(role
, value
);
1754 m_model
->setData(index
, data
);
1757 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1758 KJobWidgets::setWindow(job
, this);
1759 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1760 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1762 forceUrlsSelection(newUrl
, {newUrl
});
1764 if (!newNameExistsAlready
) {
1765 // Only connect the result signal if there is no item with the new name
1766 // in the model yet, see bug 328262.
1767 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1773 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1775 if (!url
.isValid()) {
1776 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1777 if (location
.isEmpty()) {
1778 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1780 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1786 m_model
->refreshDirectory(url
);
1788 m_model
->loadDirectory(url
);
1792 void DolphinView::applyViewProperties()
1794 const ViewProperties
props(viewPropertiesUrl());
1795 applyViewProperties(props
);
1798 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1800 m_view
->beginTransaction();
1802 const Mode mode
= props
.viewMode();
1803 if (m_mode
!= mode
) {
1804 const Mode previousMode
= m_mode
;
1807 // Changing the mode might result in changing
1808 // the zoom level. Remember the old zoom level so
1809 // that zoomLevelChanged() can get emitted.
1810 const int oldZoomLevel
= m_view
->zoomLevel();
1813 Q_EMIT
modeChanged(m_mode
, previousMode
);
1815 if (m_view
->zoomLevel() != oldZoomLevel
) {
1816 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1820 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1821 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1822 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1823 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1826 const bool groupedSorting
= props
.groupedSorting();
1827 if (groupedSorting
!= m_model
->groupedSorting()) {
1828 m_model
->setGroupedSorting(groupedSorting
);
1829 Q_EMIT
groupedSortingChanged(groupedSorting
);
1832 const QByteArray sortRole
= props
.sortRole();
1833 if (sortRole
!= m_model
->sortRole()) {
1834 m_model
->setSortRole(sortRole
);
1835 Q_EMIT
sortRoleChanged(sortRole
);
1838 const Qt::SortOrder sortOrder
= props
.sortOrder();
1839 if (sortOrder
!= m_model
->sortOrder()) {
1840 m_model
->setSortOrder(sortOrder
);
1841 Q_EMIT
sortOrderChanged(sortOrder
);
1844 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1845 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1846 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1847 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1850 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1851 if (visibleRoles
!= m_visibleRoles
) {
1852 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1853 m_visibleRoles
= visibleRoles
;
1854 m_view
->setVisibleRoles(visibleRoles
);
1855 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1858 const bool previewsShown
= props
.previewsShown();
1859 if (previewsShown
!= m_view
->previewsShown()) {
1860 const int oldZoomLevel
= zoomLevel();
1862 m_view
->setPreviewsShown(previewsShown
);
1863 Q_EMIT
previewsShownChanged(previewsShown
);
1865 // Changing the preview-state might result in a changed zoom-level
1866 if (oldZoomLevel
!= zoomLevel()) {
1867 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1871 KItemListView
* itemListView
= m_container
->controller()->view();
1872 if (itemListView
->isHeaderVisible()) {
1873 KItemListHeader
* header
= itemListView
->header();
1874 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1875 const int rolesCount
= m_visibleRoles
.count();
1876 if (headerColumnWidths
.count() == rolesCount
) {
1877 header
->setAutomaticColumnResizing(false);
1879 QHash
<QByteArray
, qreal
> columnWidths
;
1880 for (int i
= 0; i
< rolesCount
; ++i
) {
1881 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1883 header
->setColumnWidths(columnWidths
);
1885 header
->setAutomaticColumnResizing(true);
1889 m_view
->endTransaction();
1892 void DolphinView::applyModeToView()
1895 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1896 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1897 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1898 default: Q_ASSERT(false); break;
1902 void DolphinView::pasteToUrl(const QUrl
& url
)
1904 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1905 KJobWidgets::setWindow(job
, this);
1906 m_clearSelectionBeforeSelectingNewItems
= true;
1907 m_markFirstNewlySelectedItemAsCurrent
= true;
1908 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1909 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1912 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1916 const KFileItemList items
= selectedItems();
1917 urls
.reserve(items
.count());
1918 for (const KFileItem
& item
: items
) {
1919 urls
.append(item
.url());
1922 if (itemsExpandable()) {
1923 // TODO: Check if we still need KDirModel for this in KDE 5.0
1924 urls
= KDirModel::simplifiedUrlList(urls
);
1930 QMimeData
* DolphinView::selectionMimeData() const
1932 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1933 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1935 return m_model
->createMimeData(selectedIndexes
);
1938 void DolphinView::updateWritableState()
1940 const bool wasFolderWritable
= m_isFolderWritable
;
1941 m_isFolderWritable
= false;
1943 KFileItem item
= m_model
->rootItem();
1944 if (item
.isNull()) {
1945 // Try to find out if the URL is writable even if the "root item" is
1946 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1947 item
= KFileItem(url());
1948 item
.setDelayedMimeTypes(true);
1951 KFileItemListProperties
capabilities(KFileItemList() << item
);
1952 m_isFolderWritable
= capabilities
.supportsWriting();
1954 if (m_isFolderWritable
!= wasFolderWritable
) {
1955 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1959 QUrl
DolphinView::viewPropertiesUrl() const
1961 if (m_viewPropertiesContext
.isEmpty()) {
1966 url
.setScheme(m_url
.scheme());
1967 url
.setPath(m_viewPropertiesContext
);
1971 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
1973 forceUrlsSelection(urls
.first(), urls
);
1976 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
1979 m_clearSelectionBeforeSelectingNewItems
= true;
1980 markUrlAsCurrent(current
);
1981 markUrlsAsSelected(selected
);
1984 void DolphinView::copyPathToClipboard()
1986 const KFileItemList list
= selectedItems();
1987 if (list
.isEmpty()) {
1990 const KFileItem
& item
= list
.at(0);
1991 QString path
= item
.localPath();
1992 if (path
.isEmpty()) {
1993 path
= item
.url().toDisplayString();
1995 QClipboard
* clipboard
= QApplication::clipboard();
1996 if (clipboard
== nullptr) {
1999 clipboard
->setText(path
);
2002 void DolphinView::slotIncreaseZoom()
2004 setZoomLevel(zoomLevel() + 1);
2007 void DolphinView::slotDecreaseZoom()
2009 setZoomLevel(zoomLevel() - 1);
2012 void DolphinView::slotSwipeUp()
2014 Q_EMIT
goUpRequested();
2017 void DolphinView::updatePlaceholderLabel()
2019 if (itemsCount() > 0) {
2020 m_placeholderLabel
->setVisible(false);
2024 if (!nameFilter().isEmpty()) {
2025 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2026 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2027 m_placeholderLabel
->setText(i18n("No items matching the search"));
2028 } else if (m_url
.scheme() == QLatin1String("trash")) {
2029 m_placeholderLabel
->setText(i18n("Trash is empty"));
2030 } else if (m_url
.scheme() == QLatin1String("tags")) {
2031 m_placeholderLabel
->setText(i18n("No tags"));
2032 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2033 m_placeholderLabel
->setText(i18n("No recently used items"));
2034 } else if (m_url
.scheme() == QLatin1String("smb")) {
2035 m_placeholderLabel
->setText(i18n("No shared folders found"));
2036 } else if (m_url
.scheme() == QLatin1String("network")) {
2037 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2038 } else if (m_url
.scheme() == QLatin1String("mtp")) {
2039 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2040 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2041 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2043 m_placeholderLabel
->setText(i18n("Folder is empty"));
2046 m_placeholderLabel
->setVisible(true);