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_compactmodesettings.h"
11 #include "dolphin_detailsmodesettings.h"
12 #include "dolphin_iconsmodesettings.h"
13 #include "dolphin_generalsettings.h"
14 #include "dolphinitemlistview.h"
15 #include "dolphinnewfilemenuobserver.h"
16 #include "draganddrophelper.h"
17 #include "kitemviews/kfileitemlistview.h"
18 #include "kitemviews/kfileitemmodel.h"
19 #include "kitemviews/kitemlistcontainer.h"
20 #include "kitemviews/kitemlistcontroller.h"
21 #include "kitemviews/kitemlistheader.h"
22 #include "kitemviews/kitemlistselectionmanager.h"
23 #include "kitemviews/private/kitemlistroleeditor.h"
24 #include "versioncontrol/versioncontrolobserver.h"
25 #include "viewproperties.h"
26 #include "views/tooltips/tooltipmanager.h"
27 #include "zoomlevelinfo.h"
30 #include <Baloo/IndexerConfig>
32 #include <KColorScheme>
33 #include <KDesktopFile>
35 #include <KFileItemListProperties>
37 #include <KIO/CopyJob>
38 #include <KIO/DeleteJob>
39 #include <KIO/DropJob>
40 #include <KIO/JobUiDelegate>
42 #include <KIO/PasteJob>
43 #include <KIO/PreviewJob>
44 #include <KIO/RenameFileDialog>
45 #include <KJobWidgets>
46 #include <KLocalizedString>
47 #include <KMessageBox>
48 #include <KProtocolManager>
50 #include <QAbstractItemView>
51 #include <QActionGroup>
52 #include <QApplication>
55 #include <QGraphicsOpacityEffect>
56 #include <QGraphicsSceneDragDropEvent>
59 #include <QMimeDatabase>
60 #include <QPixmapCache>
65 #include <QVBoxLayout>
67 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
70 m_tabsForFiles(false),
71 m_assureVisibleCurrentIndex(false),
72 m_isFolderWritable(true),
76 m_viewPropertiesContext(),
77 m_mode(DolphinView::IconsView
),
83 m_toolTipManager(nullptr),
84 m_selectionChangedTimer(nullptr),
86 m_scrollToCurrentItem(false),
87 m_restoredContentsPosition(),
89 m_clearSelectionBeforeSelectingNewItems(false),
90 m_markFirstNewlySelectedItemAsCurrent(false),
91 m_versionControlObserver(nullptr),
92 m_twoClicksRenamingTimer(nullptr),
93 m_placeholderLabel(nullptr),
94 m_showLoadingPlaceholderTimer(nullptr)
96 m_topLayout
= new QVBoxLayout(this);
97 m_topLayout
->setSpacing(0);
98 m_topLayout
->setContentsMargins(0, 0, 0, 0);
100 // When a new item has been created by the "Create New..." menu, the item should
101 // get selected and it must be assured that the item will get visible. As the
102 // creation is done asynchronously, several signals must be checked:
103 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
104 this, &DolphinView::observeCreatedItem
);
106 m_selectionChangedTimer
= new QTimer(this);
107 m_selectionChangedTimer
->setSingleShot(true);
108 m_selectionChangedTimer
->setInterval(300);
109 connect(m_selectionChangedTimer
, &QTimer::timeout
,
110 this, &DolphinView::emitSelectionChangedSignal
);
112 m_model
= new KFileItemModel(this);
113 m_view
= new DolphinItemListView();
114 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
115 m_view
->setVisibleRoles({"text"});
118 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
119 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
120 controller
->setAutoActivationDelay(delay
);
122 // The EnlargeSmallPreviews setting can only be changed after the model
123 // has been set in the view by KItemListController.
124 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
126 m_container
= new KItemListContainer(controller
, this);
127 m_container
->installEventFilter(this);
128 setFocusProxy(m_container
);
129 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
130 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
132 m_showLoadingPlaceholderTimer
= new QTimer(this);
133 m_showLoadingPlaceholderTimer
->setInterval(500);
134 m_showLoadingPlaceholderTimer
->setSingleShot(true);
135 connect(m_showLoadingPlaceholderTimer
, &QTimer::timeout
, this, &DolphinView::showLoadingPlaceholder
);
137 // Show some placeholder text for empty folders
138 // This is made using a heavily-modified QLabel rather than a KTitleWidget
139 // because KTitleWidget can't be told to turn off mouse-selectable text
140 m_placeholderLabel
= new QLabel(this);
141 QFont placeholderLabelFont
;
142 // To match the size of a level 2 Heading/KTitleWidget
143 placeholderLabelFont
.setPointSize(qRound(placeholderLabelFont
.pointSize() * 1.3));
144 m_placeholderLabel
->setFont(placeholderLabelFont
);
145 m_placeholderLabel
->setTextInteractionFlags(Qt::NoTextInteraction
);
146 m_placeholderLabel
->setWordWrap(true);
147 m_placeholderLabel
->setAlignment(Qt::AlignCenter
);
148 // Match opacity of QML placeholder label component
149 auto *effect
= new QGraphicsOpacityEffect(m_placeholderLabel
);
150 effect
->setOpacity(0.5);
151 m_placeholderLabel
->setGraphicsEffect(effect
);
152 // Set initial text and visibility
153 updatePlaceholderLabel();
155 auto *centeringLayout
= new QVBoxLayout(m_container
);
156 centeringLayout
->addWidget(m_placeholderLabel
);
157 centeringLayout
->setAlignment(m_placeholderLabel
, Qt::AlignCenter
);
159 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
160 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
161 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
162 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
163 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
164 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
165 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
166 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
167 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
168 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
169 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
170 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
171 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
172 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
173 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
174 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
175 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
177 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
178 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
179 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::slotDirectoryLoadingCanceled
);
180 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
181 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
182 connect(m_model
, &KFileItemModel::itemsChanged
,
183 this, &DolphinView::slotItemsChanged
);
184 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
185 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
186 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
187 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
188 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
189 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
190 connect(m_model
, &KFileItemModel::fileItemsChanged
, this, &DolphinView::fileItemsChanged
);
192 connect(this, &DolphinView::itemCountChanged
,
193 this, &DolphinView::updatePlaceholderLabel
);
195 m_view
->installEventFilter(this);
196 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
197 this, &DolphinView::slotSortOrderChangedByHeader
);
198 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
199 this, &DolphinView::slotSortRoleChangedByHeader
);
200 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
201 this, &DolphinView::slotVisibleRolesChangedByHeader
);
202 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
203 this, &DolphinView::slotRoleEditingCanceled
);
204 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
205 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
207 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
208 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
209 this, &DolphinView::slotSelectionChanged
);
212 m_toolTipManager
= new ToolTipManager(this);
213 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
216 m_versionControlObserver
= new VersionControlObserver(this);
217 m_versionControlObserver
->setView(this);
218 m_versionControlObserver
->setModel(m_model
);
219 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
220 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
221 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
223 m_twoClicksRenamingTimer
= new QTimer(this);
224 m_twoClicksRenamingTimer
->setSingleShot(true);
225 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
227 applyViewProperties();
228 m_topLayout
->addWidget(m_container
);
233 DolphinView::~DolphinView()
237 QUrl
DolphinView::url() const
242 void DolphinView::setActive(bool active
)
244 if (active
== m_active
) {
253 m_container
->setFocus();
255 Q_EMIT
writeStateChanged(m_isFolderWritable
);
259 bool DolphinView::isActive() const
264 void DolphinView::setMode(Mode mode
)
266 if (mode
!= m_mode
) {
267 ViewProperties
props(viewPropertiesUrl());
268 props
.setViewMode(mode
);
270 // We pass the new ViewProperties to applyViewProperties, rather than
271 // storing them on disk and letting applyViewProperties() read them
272 // from there, to prevent that changing the view mode fails if the
273 // .directory file is not writable (see bug 318534).
274 applyViewProperties(props
);
278 DolphinView::Mode
DolphinView::mode() const
283 void DolphinView::setPreviewsShown(bool show
)
285 if (previewsShown() == show
) {
289 ViewProperties
props(viewPropertiesUrl());
290 props
.setPreviewsShown(show
);
292 const int oldZoomLevel
= m_view
->zoomLevel();
293 m_view
->setPreviewsShown(show
);
294 Q_EMIT
previewsShownChanged(show
);
296 const int newZoomLevel
= m_view
->zoomLevel();
297 if (newZoomLevel
!= oldZoomLevel
) {
298 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
302 bool DolphinView::previewsShown() const
304 return m_view
->previewsShown();
307 void DolphinView::setHiddenFilesShown(bool show
)
309 if (m_model
->showHiddenFiles() == show
) {
313 const KFileItemList itemList
= selectedItems();
314 m_selectedUrls
.clear();
315 m_selectedUrls
= itemList
.urlList();
317 ViewProperties
props(viewPropertiesUrl());
318 props
.setHiddenFilesShown(show
);
320 m_model
->setShowHiddenFiles(show
);
321 Q_EMIT
hiddenFilesShownChanged(show
);
324 bool DolphinView::hiddenFilesShown() const
326 return m_model
->showHiddenFiles();
329 void DolphinView::setGroupedSorting(bool grouped
)
331 if (grouped
== groupedSorting()) {
335 ViewProperties
props(viewPropertiesUrl());
336 props
.setGroupedSorting(grouped
);
339 m_container
->controller()->model()->setGroupedSorting(grouped
);
341 Q_EMIT
groupedSortingChanged(grouped
);
344 bool DolphinView::groupedSorting() const
346 return m_model
->groupedSorting();
349 KFileItemList
DolphinView::items() const
352 const int itemCount
= m_model
->count();
353 list
.reserve(itemCount
);
355 for (int i
= 0; i
< itemCount
; ++i
) {
356 list
.append(m_model
->fileItem(i
));
362 int DolphinView::itemsCount() const
364 return m_model
->count();
367 KFileItemList
DolphinView::selectedItems() const
369 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
371 KFileItemList selectedItems
;
372 const auto items
= selectionManager
->selectedItems();
373 selectedItems
.reserve(items
.count());
374 for (int index
: items
) {
375 selectedItems
.append(m_model
->fileItem(index
));
377 return selectedItems
;
380 int DolphinView::selectedItemsCount() const
382 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
383 return selectionManager
->selectedItems().count();
386 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
388 m_selectedUrls
= urls
;
391 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
393 m_currentItemUrl
= url
;
394 m_scrollToCurrentItem
= true;
397 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
399 const KItemListSelectionManager::SelectionMode mode
= enabled
400 ? KItemListSelectionManager::Select
401 : KItemListSelectionManager::Deselect
;
402 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
404 for (int index
= 0; index
< m_model
->count(); index
++) {
405 const KFileItem item
= m_model
->fileItem(index
);
406 if (regexp
.match(item
.text()).hasMatch()) {
407 // An alternative approach would be to store the matching items in a KItemSet and
408 // select them in one go after the loop, but we'd need a new function
409 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
411 selectionManager
->setSelected(index
, 1, mode
);
416 void DolphinView::setZoomLevel(int level
)
418 const int oldZoomLevel
= zoomLevel();
419 m_view
->setZoomLevel(level
);
420 if (zoomLevel() != oldZoomLevel
) {
422 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
426 int DolphinView::zoomLevel() const
428 return m_view
->zoomLevel();
431 void DolphinView::setSortRole(const QByteArray
& role
)
433 if (role
!= sortRole()) {
434 updateSortRole(role
);
438 QByteArray
DolphinView::sortRole() const
440 const KItemModelBase
* model
= m_container
->controller()->model();
441 return model
->sortRole();
444 void DolphinView::setSortOrder(Qt::SortOrder order
)
446 if (sortOrder() != order
) {
447 updateSortOrder(order
);
451 Qt::SortOrder
DolphinView::sortOrder() const
453 return m_model
->sortOrder();
456 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
458 if (sortFoldersFirst() != foldersFirst
) {
459 updateSortFoldersFirst(foldersFirst
);
463 bool DolphinView::sortFoldersFirst() const
465 return m_model
->sortDirectoriesFirst();
468 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
470 const QList
<QByteArray
> previousRoles
= roles
;
472 ViewProperties
props(viewPropertiesUrl());
473 props
.setVisibleRoles(roles
);
475 m_visibleRoles
= roles
;
476 m_view
->setVisibleRoles(roles
);
478 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
481 QList
<QByteArray
> DolphinView::visibleRoles() const
483 return m_visibleRoles
;
486 void DolphinView::reload()
488 QByteArray viewState
;
489 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
490 saveState(saveStream
);
493 loadDirectory(url(), true);
495 QDataStream
restoreStream(viewState
);
496 restoreState(restoreStream
);
499 void DolphinView::readSettings()
501 const int oldZoomLevel
= m_view
->zoomLevel();
503 GeneralSettings::self()->load();
504 m_view
->readSettings();
505 applyViewProperties();
507 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
508 m_container
->controller()->setAutoActivationDelay(delay
);
510 const int newZoomLevel
= m_view
->zoomLevel();
511 if (newZoomLevel
!= oldZoomLevel
) {
512 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
516 void DolphinView::writeSettings()
518 GeneralSettings::self()->save();
519 m_view
->writeSettings();
522 void DolphinView::setNameFilter(const QString
& nameFilter
)
524 m_model
->setNameFilter(nameFilter
);
527 QString
DolphinView::nameFilter() const
529 return m_model
->nameFilter();
532 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
534 return m_model
->setMimeTypeFilters(filters
);
537 QStringList
DolphinView::mimeTypeFilters() const
539 return m_model
->mimeTypeFilters();
542 void DolphinView::requestStatusBarText()
544 if (m_statJobForStatusBarText
) {
545 // Kill the pending request.
546 m_statJobForStatusBarText
->kill();
549 if (m_container
->controller()->selectionManager()->hasSelection()) {
552 KIO::filesize_t totalFileSize
= 0;
554 // Give a summary of the status of the selected files
555 const KFileItemList list
= selectedItems();
556 for (const KFileItem
& item
: list
) {
561 totalFileSize
+= item
.size();
565 if (folderCount
+ fileCount
== 1) {
566 // If only one item is selected, show info about it
567 Q_EMIT
statusBarTextChanged(list
.first().getStatusBarInfo());
569 // At least 2 items are selected
570 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, HasSelection
);
572 } else { // has no selection
573 if (!m_model
->rootItem().url().isValid()) {
577 m_statJobForStatusBarText
= KIO::statDetails(m_model
->rootItem().url(),
578 KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
579 connect(m_statJobForStatusBarText
, &KJob::result
,
580 this, &DolphinView::slotStatJobResult
);
581 m_statJobForStatusBarText
->start();
585 void DolphinView::emitStatusBarText(const int folderCount
, const int fileCount
,
586 KIO::filesize_t totalFileSize
, const Selection selection
)
592 if (selection
== HasSelection
) {
593 // At least 2 items are selected because the case of 1 selected item is handled in
594 // DolphinView::requestStatusBarText().
595 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
596 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
598 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
599 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
602 if (fileCount
> 0 && folderCount
> 0) {
603 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
604 foldersText
, filesText
,
605 KFormat().formatByteSize(totalFileSize
));
606 } else if (fileCount
> 0) {
607 summary
= i18nc("@info:status files (size)", "%1 (%2)",
609 KFormat().formatByteSize(totalFileSize
));
610 } else if (folderCount
> 0) {
611 summary
= foldersText
;
613 summary
= i18nc("@info:status", "0 Folders, 0 Files");
615 Q_EMIT
statusBarTextChanged(summary
);
618 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
620 QList
<QAction
*> actions
;
622 if (items
.isEmpty()) {
623 const KFileItem item
= m_model
->rootItem();
624 if (!item
.isNull()) {
625 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
628 actions
= m_versionControlObserver
->actions(items
);
634 void DolphinView::setUrl(const QUrl
& url
)
646 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
647 this, &DolphinView::slotRoleEditingFinished
);
649 // It is important to clear the items from the model before
650 // applying the view properties, otherwise expensive operations
651 // might be done on the existing items although they get cleared
652 // anyhow afterwards by loadDirectory().
654 applyViewProperties();
657 Q_EMIT
urlChanged(url
);
660 void DolphinView::selectAll()
662 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
663 selectionManager
->setSelected(0, m_model
->count());
666 void DolphinView::invertSelection()
668 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
669 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
672 void DolphinView::clearSelection()
674 m_selectedUrls
.clear();
675 m_container
->controller()->selectionManager()->clearSelection();
678 void DolphinView::renameSelectedItems()
680 const KFileItemList items
= selectedItems();
681 if (items
.isEmpty()) {
685 if (items
.count() == 1 && GeneralSettings::renameInline()) {
686 const int index
= m_model
->index(items
.first());
688 QMetaObject::Connection
* const connection
= new QMetaObject::Connection
;
689 *connection
= connect(m_view
, &KItemListView::scrollingStopped
, this, [=](){
690 QObject::disconnect(*connection
);
693 m_view
->editRole(index
, "text");
697 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
698 this, &DolphinView::slotRoleEditingFinished
);
700 m_view
->scrollToItem(index
);
703 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
704 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
705 this, &DolphinView::slotRenameDialogRenamingFinished
);
710 // Assure that the current index remains visible when KFileItemModel
711 // will notify the view about changed items (which might result in
712 // a changed sorting).
713 m_assureVisibleCurrentIndex
= true;
716 void DolphinView::trashSelectedItems()
718 const QList
<QUrl
> list
= simplifiedSelectedUrls();
719 KIO::JobUiDelegate uiDelegate
;
720 uiDelegate
.setWindow(window());
721 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
722 KIO::Job
* job
= KIO::trash(list
);
723 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
724 KJobWidgets::setWindow(job
, this);
725 connect(job
, &KIO::Job::result
,
726 this, &DolphinView::slotTrashFileFinished
);
730 void DolphinView::deleteSelectedItems()
732 const QList
<QUrl
> list
= simplifiedSelectedUrls();
734 KIO::JobUiDelegate uiDelegate
;
735 uiDelegate
.setWindow(window());
736 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
737 KIO::Job
* job
= KIO::del(list
);
738 KJobWidgets::setWindow(job
, this);
739 connect(job
, &KIO::Job::result
,
740 this, &DolphinView::slotDeleteFileFinished
);
744 void DolphinView::cutSelectedItemsToClipboard()
746 QMimeData
* mimeData
= selectionMimeData();
747 KIO::setClipboardDataCut(mimeData
, true);
748 QApplication::clipboard()->setMimeData(mimeData
);
751 void DolphinView::copySelectedItemsToClipboard()
753 QMimeData
* mimeData
= selectionMimeData();
754 QApplication::clipboard()->setMimeData(mimeData
);
757 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
759 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
760 KJobWidgets::setWindow(job
, this);
762 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
763 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
764 KIO::FileUndoManager::self()->recordCopyJob(job
);
767 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
769 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
770 KJobWidgets::setWindow(job
, this);
772 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
773 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
774 KIO::FileUndoManager::self()->recordCopyJob(job
);
778 void DolphinView::paste()
783 void DolphinView::pasteIntoFolder()
785 const KFileItemList items
= selectedItems();
786 if ((items
.count() == 1) && items
.first().isDir()) {
787 pasteToUrl(items
.first().url());
791 void DolphinView::duplicateSelectedItems()
793 const KFileItemList itemList
= selectedItems();
794 if (itemList
.isEmpty()) {
798 const QMimeDatabase db
;
800 // Duplicate all selected items and append "copy" to the end of the file name
801 // but before the filename extension, if present
802 QList
<QUrl
> newSelection
;
803 for (const auto &item
: itemList
) {
804 const QUrl originalURL
= item
.url();
805 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
806 const QString originalFileName
= item
.name();
808 QString extension
= db
.suffixForFileName(originalFileName
);
810 QUrl duplicateURL
= originalURL
;
812 // No extension; new filename is "<oldfilename> copy"
813 if (extension
.isEmpty()) {
814 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
815 // There's an extension; new filename is "<oldfilename> copy.<extension>"
817 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
818 extension
= QLatin1String(".") + extension
;
819 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
820 // Preserve file's original filename extension in case the casing differs
821 // from what QMimeDatabase::suffixForFileName() returned
822 const QString originalExtension
= originalFileName
.right(extension
.size());
823 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
826 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
827 KJobWidgets::setWindow(job
, this);
830 newSelection
<< duplicateURL
;
831 KIO::FileUndoManager::self()->recordCopyJob(job
);
835 forceUrlsSelection(newSelection
.first(), newSelection
);
838 void DolphinView::stopLoading()
840 m_model
->cancelDirectoryLoading();
843 void DolphinView::updatePalette()
845 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
850 QWidget
* viewport
= m_container
->viewport();
853 palette
.setColor(viewport
->backgroundRole(), color
);
854 viewport
->setPalette(palette
);
860 void DolphinView::abortTwoClicksRenaming()
862 m_twoClicksRenamingItemUrl
.clear();
863 m_twoClicksRenamingTimer
->stop();
866 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
868 switch (event
->type()) {
869 case QEvent::PaletteChange
:
871 QPixmapCache::clear();
874 case QEvent::WindowActivate
:
875 case QEvent::WindowDeactivate
:
879 case QEvent::KeyPress
:
880 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
881 if (GeneralSettings::useTabForSwitchingSplitView()) {
882 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
883 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
884 Q_EMIT
toggleActiveViewRequested();
889 case QEvent::FocusIn
:
890 if (watched
== m_container
) {
895 case QEvent::GraphicsSceneDragEnter
:
896 if (watched
== m_view
) {
898 abortTwoClicksRenaming();
902 case QEvent::GraphicsSceneDragLeave
:
903 if (watched
== m_view
) {
908 case QEvent::GraphicsSceneDrop
:
909 if (watched
== m_view
) {
916 return QWidget::eventFilter(watched
, event
);
919 void DolphinView::wheelEvent(QWheelEvent
* event
)
921 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
922 const QPoint numDegrees
= event
->angleDelta() / 8;
923 const QPoint numSteps
= numDegrees
/ 15;
925 setZoomLevel(zoomLevel() + numSteps
.y());
932 void DolphinView::hideEvent(QHideEvent
* event
)
935 QWidget::hideEvent(event
);
938 bool DolphinView::event(QEvent
* event
)
940 if (event
->type() == QEvent::WindowDeactivate
) {
942 * Dolphin leaves file preview tooltips open even when is not visible.
944 * Hide tool-tip when Dolphin loses focus.
947 abortTwoClicksRenaming();
950 return QWidget::event(event
);
953 void DolphinView::activate()
958 void DolphinView::slotItemActivated(int index
)
960 abortTwoClicksRenaming();
962 const KFileItem item
= m_model
->fileItem(index
);
963 if (!item
.isNull()) {
964 Q_EMIT
itemActivated(item
);
968 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
970 Q_ASSERT(indexes
.count() >= 2);
972 abortTwoClicksRenaming();
974 if (indexes
.count() > 5) {
975 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
976 const int answer
= KMessageBox::warningYesNo(this, question
);
977 if (answer
!= KMessageBox::Yes
) {
983 items
.reserve(indexes
.count());
985 for (int index
: indexes
) {
986 KFileItem item
= m_model
->fileItem(index
);
987 const QUrl
& url
= openItemAsFolderUrl(item
);
989 if (!url
.isEmpty()) { // Open folders in new tabs
990 Q_EMIT
tabRequested(url
);
996 if (items
.count() == 1) {
997 Q_EMIT
itemActivated(items
.first());
998 } else if (items
.count() > 1) {
999 Q_EMIT
itemsActivated(items
);
1003 void DolphinView::slotItemMiddleClicked(int index
)
1005 const KFileItem
& item
= m_model
->fileItem(index
);
1006 const QUrl
& url
= openItemAsFolderUrl(item
);
1007 if (!url
.isEmpty()) {
1008 Q_EMIT
tabRequested(url
);
1009 } else if (isTabsForFilesEnabled()) {
1010 Q_EMIT
tabRequested(item
.url());
1014 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
1016 // Force emit of a selection changed signal before we request the
1017 // context menu, to update the edit-actions first. (See Bug 294013)
1018 if (m_selectionChangedTimer
->isActive()) {
1019 emitSelectionChangedSignal();
1022 const KFileItem item
= m_model
->fileItem(index
);
1023 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
1026 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
1028 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
1031 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
1033 ViewProperties
props(viewPropertiesUrl());
1035 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
1037 KItemListView
* view
= m_container
->controller()->view();
1038 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
1040 bool indexingEnabled
= false;
1042 Baloo::IndexerConfig config
;
1043 indexingEnabled
= config
.fileIndexingEnabled();
1047 QMenu
* groupMenu
= nullptr;
1049 // Add all roles to the menu that can be shown or hidden by the user
1050 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
1051 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
1052 if (info
.role
== "text") {
1053 // It should not be possible to hide the "text" role
1057 const QString text
= m_model
->roleDescription(info
.role
);
1058 QAction
* action
= nullptr;
1059 if (info
.group
.isEmpty()) {
1060 action
= menu
->addAction(text
);
1062 if (!groupMenu
|| info
.group
!= groupName
) {
1063 groupName
= info
.group
;
1064 groupMenu
= menu
->addMenu(groupName
);
1067 action
= groupMenu
->addAction(text
);
1070 action
->setCheckable(true);
1071 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1072 action
->setData(info
.role
);
1074 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1075 (info
.requiresBaloo
) ||
1076 (info
.requiresIndexer
&& indexingEnabled
);
1077 action
->setEnabled(enable
);
1080 menu
->addSeparator();
1082 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1083 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1085 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1086 autoAdjustWidthsAction
->setCheckable(true);
1087 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1088 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1090 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1091 customWidthsAction
->setCheckable(true);
1092 customWidthsAction
->setChecked(!autoColumnWidths
);
1093 customWidthsAction
->setActionGroup(widthsGroup
);
1095 QAction
* action
= menu
->exec(pos
.toPoint());
1096 if (menu
&& action
) {
1097 KItemListHeader
* header
= view
->header();
1099 if (action
== autoAdjustWidthsAction
) {
1100 // Clear the column-widths from the viewproperties and turn on
1101 // the automatic resizing of the columns
1102 props
.setHeaderColumnWidths(QList
<int>());
1103 header
->setAutomaticColumnResizing(true);
1104 } else if (action
== customWidthsAction
) {
1105 // Apply the current column-widths as custom column-widths and turn
1106 // off the automatic resizing of the columns
1107 QList
<int> columnWidths
;
1108 const auto visibleRoles
= view
->visibleRoles();
1109 columnWidths
.reserve(visibleRoles
.count());
1110 for (const QByteArray
& role
: visibleRoles
) {
1111 columnWidths
.append(header
->columnWidth(role
));
1113 props
.setHeaderColumnWidths(columnWidths
);
1114 header
->setAutomaticColumnResizing(false);
1116 // Show or hide the selected role
1117 const QByteArray selectedRole
= action
->data().toByteArray();
1119 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1120 if (action
->isChecked()) {
1121 visibleRoles
.append(selectedRole
);
1123 visibleRoles
.removeOne(selectedRole
);
1126 view
->setVisibleRoles(visibleRoles
);
1127 props
.setVisibleRoles(visibleRoles
);
1129 QList
<int> columnWidths
;
1130 if (!header
->automaticColumnResizing()) {
1131 const auto visibleRoles
= view
->visibleRoles();
1132 columnWidths
.reserve(visibleRoles
.count());
1133 for (const QByteArray
& role
: visibleRoles
) {
1134 columnWidths
.append(header
->columnWidth(role
));
1137 props
.setHeaderColumnWidths(columnWidths
);
1144 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1146 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1148 ViewProperties
props(viewPropertiesUrl());
1149 QList
<int> columnWidths
= props
.headerColumnWidths();
1150 if (columnWidths
.count() != visibleRoles
.count()) {
1151 columnWidths
.clear();
1152 columnWidths
.reserve(visibleRoles
.count());
1153 const KItemListHeader
* header
= m_view
->header();
1154 for (const QByteArray
& role
: visibleRoles
) {
1155 const int width
= header
->columnWidth(role
);
1156 columnWidths
.append(width
);
1160 const int roleIndex
= visibleRoles
.indexOf(role
);
1161 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1162 columnWidths
[roleIndex
] = current
;
1164 props
.setHeaderColumnWidths(columnWidths
);
1167 void DolphinView::slotItemHovered(int index
)
1169 const KFileItem item
= m_model
->fileItem(index
);
1171 if (GeneralSettings::showToolTips() && !m_dragging
) {
1172 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1173 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1174 itemRect
.moveTo(pos
);
1177 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1181 Q_EMIT
requestItemInfo(item
);
1184 void DolphinView::slotItemUnhovered(int index
)
1188 Q_EMIT
requestItemInfo(KFileItem());
1191 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1194 KFileItem destItem
= m_model
->fileItem(index
);
1195 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1196 // Use the URL of the view as drop target if the item is no directory
1198 destItem
= m_model
->rootItem();
1201 // The item represents a directory or desktop-file
1202 destUrl
= destItem
.mostLocalUrl();
1205 QDropEvent
dropEvent(event
->pos().toPoint(),
1206 event
->possibleActions(),
1209 event
->modifiers());
1210 dropUrls(destUrl
, &dropEvent
, this);
1215 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1217 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1220 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1222 if (destUrl
== url()) {
1223 // Mark the dropped urls as selected.
1224 m_clearSelectionBeforeSelectingNewItems
= true;
1225 m_markFirstNewlySelectedItemAsCurrent
= true;
1226 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1231 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1233 if (previous
!= nullptr) {
1234 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1235 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1236 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1237 m_versionControlObserver
->setModel(nullptr);
1241 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1242 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1243 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1244 m_versionControlObserver
->setModel(fileItemModel
);
1248 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1254 if (buttons
& Qt::BackButton
) {
1255 Q_EMIT
goBackRequested();
1256 } else if (buttons
& Qt::ForwardButton
) {
1257 Q_EMIT
goForwardRequested();
1261 void DolphinView::slotSelectedItemTextPressed(int index
)
1263 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1264 const KFileItem item
= m_model
->fileItem(index
);
1265 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1266 if (capabilities
.supportsMoving()) {
1267 m_twoClicksRenamingItemUrl
= item
.url();
1268 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1273 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1275 slotItemCreated(to
);
1278 void DolphinView::slotItemCreated(const QUrl
& url
)
1280 if (m_markFirstNewlySelectedItemAsCurrent
) {
1281 markUrlAsCurrent(url
);
1282 m_markFirstNewlySelectedItemAsCurrent
= false;
1284 m_selectedUrls
<< url
;
1287 void DolphinView::slotJobResult(KJob
*job
)
1290 Q_EMIT
errorMessage(job
->errorString());
1292 if (!m_selectedUrls
.isEmpty()) {
1293 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1297 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1299 const int currentCount
= current
.count();
1300 const int previousCount
= previous
.count();
1301 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1302 (currentCount
> 0 && previousCount
== 0);
1304 // If nothing has been selected before and something got selected (or if something
1305 // was selected before and now nothing is selected) the selectionChangedSignal must
1306 // be emitted asynchronously as fast as possible to update the edit-actions.
1307 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1308 m_selectionChangedTimer
->start();
1311 void DolphinView::emitSelectionChangedSignal()
1313 m_selectionChangedTimer
->stop();
1314 Q_EMIT
selectionChanged(selectedItems());
1317 void DolphinView::slotStatJobResult(KJob
*job
)
1319 int folderCount
= 0;
1321 KIO::filesize_t totalFileSize
= 0;
1322 bool countFileSize
= true;
1324 const auto entry
= static_cast<KIO::StatJob
*>(job
)->statResult();
1325 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1326 // We have a precomputed value.
1327 totalFileSize
= static_cast<KIO::filesize_t
>(
1328 entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1329 countFileSize
= false;
1332 const int itemCount
= m_model
->count();
1333 for (int i
= 0; i
< itemCount
; ++i
) {
1334 const KFileItem item
= m_model
->fileItem(i
);
1339 if (countFileSize
) {
1340 totalFileSize
+= item
.size();
1344 emitStatusBarText(folderCount
, fileCount
, totalFileSize
, NoSelection
);
1347 void DolphinView::updateSortRole(const QByteArray
& role
)
1349 ViewProperties
props(viewPropertiesUrl());
1350 props
.setSortRole(role
);
1352 KItemModelBase
* model
= m_container
->controller()->model();
1353 model
->setSortRole(role
);
1355 Q_EMIT
sortRoleChanged(role
);
1358 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1360 ViewProperties
props(viewPropertiesUrl());
1361 props
.setSortOrder(order
);
1363 m_model
->setSortOrder(order
);
1365 Q_EMIT
sortOrderChanged(order
);
1368 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1370 ViewProperties
props(viewPropertiesUrl());
1371 props
.setSortFoldersFirst(foldersFirst
);
1373 m_model
->setSortDirectoriesFirst(foldersFirst
);
1375 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1378 QPair
<bool, QString
> DolphinView::pasteInfo() const
1380 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1381 QPair
<bool, QString
> info
;
1382 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1386 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1388 m_tabsForFiles
= tabsForFiles
;
1391 bool DolphinView::isTabsForFilesEnabled() const
1393 return m_tabsForFiles
;
1396 bool DolphinView::itemsExpandable() const
1398 return m_mode
== DetailsView
;
1401 void DolphinView::restoreState(QDataStream
& stream
)
1403 // Read the version number of the view state and check if the version is supported.
1404 quint32 version
= 0;
1407 // The version of the view state isn't supported, we can't restore it.
1411 // Restore the current item that had the keyboard focus
1412 stream
>> m_currentItemUrl
;
1414 // Restore the previously selected items
1415 stream
>> m_selectedUrls
;
1417 // Restore the view position
1418 stream
>> m_restoredContentsPosition
;
1420 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1423 m_model
->restoreExpandedDirectories(urls
);
1426 void DolphinView::saveState(QDataStream
& stream
)
1428 stream
<< quint32(1); // View state version
1430 // Save the current item that has the keyboard focus
1431 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1432 if (currentIndex
!= -1) {
1433 KFileItem item
= m_model
->fileItem(currentIndex
);
1434 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1435 QUrl currentItemUrl
= item
.url();
1436 stream
<< currentItemUrl
;
1441 // Save the selected urls
1442 stream
<< selectedItems().urlList();
1444 // Save view position
1445 const qreal x
= m_container
->horizontalScrollBar()->value();
1446 const qreal y
= m_container
->verticalScrollBar()->value();
1447 stream
<< QPoint(x
, y
);
1449 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1450 stream
<< m_model
->expandedDirectories();
1453 KFileItem
DolphinView::rootItem() const
1455 return m_model
->rootItem();
1458 void DolphinView::setViewPropertiesContext(const QString
& context
)
1460 m_viewPropertiesContext
= context
;
1463 QString
DolphinView::viewPropertiesContext() const
1465 return m_viewPropertiesContext
;
1468 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1470 if (item
.isNull()) {
1474 QUrl url
= item
.targetUrl();
1480 if (item
.isMimeTypeKnown()) {
1481 const QString
& mimetype
= item
.mimetype();
1483 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1484 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1485 // zip:/<path>/ when clicking on a zip file, etc.
1486 // The .protocol file specifies the mimetype that the kioslave handles.
1487 // Note that we don't use mimetype inheritance since we don't want to
1488 // open OpenDocument files as zip folders...
1489 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1490 if (!protocol
.isEmpty()) {
1491 url
.setScheme(protocol
);
1496 if (mimetype
== QLatin1String("application/x-desktop")) {
1497 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1498 KDesktopFile
desktopFile(url
.toLocalFile());
1499 if (desktopFile
.hasLinkType()) {
1500 const QString linkUrl
= desktopFile
.readUrl();
1501 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1502 return QUrl::fromUserInput(linkUrl
);
1511 void DolphinView::resetZoomLevel()
1513 // TODO : Switch to using ViewModeSettings after MR #256 is merged
1514 int defaultIconSize
= KIconLoader::SizeSmall
;
1517 IconsModeSettings::self()->useDefaults(true);
1518 defaultIconSize
= IconsModeSettings::iconSize();
1519 IconsModeSettings::self()->useDefaults(false);
1522 DetailsModeSettings::self()->useDefaults(true);
1523 defaultIconSize
= DetailsModeSettings::iconSize();
1524 DetailsModeSettings::self()->useDefaults(false);
1527 CompactModeSettings::self()->useDefaults(true);
1528 defaultIconSize
= CompactModeSettings::iconSize();
1529 CompactModeSettings::self()->useDefaults(false);
1536 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize
, defaultIconSize
)));
1539 void DolphinView::observeCreatedItem(const QUrl
& url
)
1542 forceUrlsSelection(url
, {url
});
1546 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1548 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1549 Q_EMIT
redirection(oldUrl
, newUrl
);
1550 m_url
= newUrl
; // #186947
1554 void DolphinView::updateViewState()
1556 if (m_currentItemUrl
!= QUrl()) {
1557 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1559 // if there is a selection already, leave it that way
1560 if (!selectionManager
->hasSelection()) {
1561 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1562 if (currentIndex
!= -1) {
1563 selectionManager
->setCurrentItem(currentIndex
);
1565 // scroll to current item and reset the state
1566 if (m_scrollToCurrentItem
) {
1567 m_view
->scrollToItem(currentIndex
);
1568 m_scrollToCurrentItem
= false;
1571 selectionManager
->setCurrentItem(0);
1575 m_currentItemUrl
= QUrl();
1578 if (!m_restoredContentsPosition
.isNull()) {
1579 const int x
= m_restoredContentsPosition
.x();
1580 const int y
= m_restoredContentsPosition
.y();
1581 m_restoredContentsPosition
= QPoint();
1583 m_container
->horizontalScrollBar()->setValue(x
);
1584 m_container
->verticalScrollBar()->setValue(y
);
1587 if (!m_selectedUrls
.isEmpty()) {
1588 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1590 // if there is a selection already, leave it that way
1591 if (!selectionManager
->hasSelection()) {
1592 if (m_clearSelectionBeforeSelectingNewItems
) {
1593 selectionManager
->clearSelection();
1594 m_clearSelectionBeforeSelectingNewItems
= false;
1597 KItemSet selectedItems
= selectionManager
->selectedItems();
1599 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1600 while (it
!= m_selectedUrls
.end()) {
1601 const int index
= m_model
->index(*it
);
1603 selectedItems
.insert(index
);
1604 it
= m_selectedUrls
.erase(it
);
1610 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1611 selectionManager
->setSelectedItems(selectedItems
);
1616 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1619 if (GeneralSettings::showToolTips()) {
1620 m_toolTipManager
->hideToolTip(behavior
);
1627 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1629 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1631 // verify that only one item is selected
1632 if (selectionManager
->selectedItems().count() == 1) {
1633 const int index
= selectionManager
->currentItem();
1634 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1636 // check if the selected item was the same item that started the twoClicksRenaming
1637 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1638 renameSelectedItems();
1643 void DolphinView::slotTrashFileFinished(KJob
* job
)
1645 if (job
->error() == 0) {
1646 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1647 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1648 Q_EMIT
errorMessage(job
->errorString());
1652 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1654 if (job
->error() == 0) {
1655 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1656 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1657 Q_EMIT
errorMessage(job
->errorString());
1661 void DolphinView::slotRenamingResult(KJob
* job
)
1664 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1666 const QUrl newUrl
= copyJob
->destUrl();
1667 const int index
= m_model
->index(newUrl
);
1669 QHash
<QByteArray
, QVariant
> data
;
1670 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1671 data
.insert("text", oldUrl
.fileName());
1672 m_model
->setData(index
, data
);
1677 void DolphinView::slotDirectoryLoadingStarted()
1680 updatePlaceholderLabel();
1682 // Disable the writestate temporary until it can be determined in a fast way
1683 // in DolphinView::slotDirectoryLoadingCompleted()
1684 if (m_isFolderWritable
) {
1685 m_isFolderWritable
= false;
1686 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1689 Q_EMIT
directoryLoadingStarted();
1692 void DolphinView::slotDirectoryLoadingCompleted()
1696 // Update the view-state. This has to be done asynchronously
1697 // because the view might not be in its final state yet.
1698 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1700 // Update the placeholder label in case we found that the folder was empty
1703 Q_EMIT
directoryLoadingCompleted();
1705 updatePlaceholderLabel();
1706 updateWritableState();
1709 void DolphinView::slotDirectoryLoadingCanceled()
1713 updatePlaceholderLabel();
1715 Q_EMIT
directoryLoadingCanceled();
1718 void DolphinView::slotItemsChanged()
1720 m_assureVisibleCurrentIndex
= false;
1723 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1726 Q_ASSERT(m_model
->sortOrder() == current
);
1728 ViewProperties
props(viewPropertiesUrl());
1729 props
.setSortOrder(current
);
1731 Q_EMIT
sortOrderChanged(current
);
1734 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1737 Q_ASSERT(m_model
->sortRole() == current
);
1739 ViewProperties
props(viewPropertiesUrl());
1740 props
.setSortRole(current
);
1742 Q_EMIT
sortRoleChanged(current
);
1745 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1746 const QList
<QByteArray
>& previous
)
1749 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1751 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1753 m_visibleRoles
= current
;
1755 ViewProperties
props(viewPropertiesUrl());
1756 props
.setVisibleRoles(m_visibleRoles
);
1758 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1761 void DolphinView::slotRoleEditingCanceled()
1763 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1764 this, &DolphinView::slotRoleEditingFinished
);
1767 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1769 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1770 this, &DolphinView::slotRoleEditingFinished
);
1772 const KFileItemList items
= selectedItems();
1773 if (items
.count() != 1) {
1777 if (role
== "text") {
1778 const KFileItem oldItem
= items
.first();
1779 const EditResult retVal
= value
.value
<EditResult
>();
1780 const QString newName
= retVal
.newName
;
1781 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1782 const QUrl oldUrl
= oldItem
.url();
1784 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1785 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1788 //Confirm hiding file/directory by renaming inline
1789 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1790 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1791 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1793 const auto code
= KMessageBox::questionYesNo(this,
1794 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1795 "Do you still want to rename it?")
1796 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1797 "Do you still want to rename it?"),
1798 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1800 KStandardGuiItem::cancel(),
1801 QStringLiteral("ConfirmHide")
1804 if (code
== KMessageBox::No
) {
1810 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1811 if (!newNameExistsAlready
&& m_model
->index(oldUrl
) == index
) {
1812 // Only change the data in the model if no item with the new name
1813 // is in the model yet. If there is an item with the new name
1814 // already, calling KIO::CopyJob will open a dialog
1815 // asking for a new name, and KFileItemModel will update the
1816 // data when the dir lister signals that the file name has changed.
1817 QHash
<QByteArray
, QVariant
> data
;
1818 data
.insert(role
, retVal
.newName
);
1819 m_model
->setData(index
, data
);
1822 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1823 KJobWidgets::setWindow(job
, this);
1824 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1825 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1827 forceUrlsSelection(newUrl
, {newUrl
});
1829 if (!newNameExistsAlready
) {
1830 // Only connect the result signal if there is no item with the new name
1831 // in the model yet, see bug 328262.
1832 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1835 if (retVal
.direction
!= EditDone
) {
1836 const short indexShift
= retVal
.direction
== EditNext
? 1 : -1;
1837 m_container
->controller()->selectionManager()->setSelected(index
, 1, KItemListSelectionManager::Deselect
);
1838 m_container
->controller()->selectionManager()->setSelected(index
+ indexShift
, 1,
1839 KItemListSelectionManager::Select
);
1840 renameSelectedItems();
1845 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1847 if (!url
.isValid()) {
1848 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1849 if (location
.isEmpty()) {
1850 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1852 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1858 m_model
->refreshDirectory(url
);
1860 m_model
->loadDirectory(url
);
1864 void DolphinView::applyViewProperties()
1866 const ViewProperties
props(viewPropertiesUrl());
1867 applyViewProperties(props
);
1870 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1872 m_view
->beginTransaction();
1874 const Mode mode
= props
.viewMode();
1875 if (m_mode
!= mode
) {
1876 const Mode previousMode
= m_mode
;
1879 // Changing the mode might result in changing
1880 // the zoom level. Remember the old zoom level so
1881 // that zoomLevelChanged() can get emitted.
1882 const int oldZoomLevel
= m_view
->zoomLevel();
1885 Q_EMIT
modeChanged(m_mode
, previousMode
);
1887 if (m_view
->zoomLevel() != oldZoomLevel
) {
1888 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1892 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1893 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1894 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1895 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1898 const bool groupedSorting
= props
.groupedSorting();
1899 if (groupedSorting
!= m_model
->groupedSorting()) {
1900 m_model
->setGroupedSorting(groupedSorting
);
1901 Q_EMIT
groupedSortingChanged(groupedSorting
);
1904 const QByteArray sortRole
= props
.sortRole();
1905 if (sortRole
!= m_model
->sortRole()) {
1906 m_model
->setSortRole(sortRole
);
1907 Q_EMIT
sortRoleChanged(sortRole
);
1910 const Qt::SortOrder sortOrder
= props
.sortOrder();
1911 if (sortOrder
!= m_model
->sortOrder()) {
1912 m_model
->setSortOrder(sortOrder
);
1913 Q_EMIT
sortOrderChanged(sortOrder
);
1916 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1917 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1918 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1919 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1922 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1923 if (visibleRoles
!= m_visibleRoles
) {
1924 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1925 m_visibleRoles
= visibleRoles
;
1926 m_view
->setVisibleRoles(visibleRoles
);
1927 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1930 const bool previewsShown
= props
.previewsShown();
1931 if (previewsShown
!= m_view
->previewsShown()) {
1932 const int oldZoomLevel
= zoomLevel();
1934 m_view
->setPreviewsShown(previewsShown
);
1935 Q_EMIT
previewsShownChanged(previewsShown
);
1937 // Changing the preview-state might result in a changed zoom-level
1938 if (oldZoomLevel
!= zoomLevel()) {
1939 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1943 KItemListView
* itemListView
= m_container
->controller()->view();
1944 if (itemListView
->isHeaderVisible()) {
1945 KItemListHeader
* header
= itemListView
->header();
1946 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1947 const int rolesCount
= m_visibleRoles
.count();
1948 if (headerColumnWidths
.count() == rolesCount
) {
1949 header
->setAutomaticColumnResizing(false);
1951 QHash
<QByteArray
, qreal
> columnWidths
;
1952 for (int i
= 0; i
< rolesCount
; ++i
) {
1953 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1955 header
->setColumnWidths(columnWidths
);
1957 header
->setAutomaticColumnResizing(true);
1961 m_view
->endTransaction();
1964 void DolphinView::applyModeToView()
1967 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1968 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1969 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1970 default: Q_ASSERT(false); break;
1974 void DolphinView::pasteToUrl(const QUrl
& url
)
1976 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1977 KJobWidgets::setWindow(job
, this);
1978 m_clearSelectionBeforeSelectingNewItems
= true;
1979 m_markFirstNewlySelectedItemAsCurrent
= true;
1980 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1981 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1984 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1988 const KFileItemList items
= selectedItems();
1989 urls
.reserve(items
.count());
1990 for (const KFileItem
& item
: items
) {
1991 urls
.append(item
.url());
1994 if (itemsExpandable()) {
1995 // TODO: Check if we still need KDirModel for this in KDE 5.0
1996 urls
= KDirModel::simplifiedUrlList(urls
);
2002 QMimeData
* DolphinView::selectionMimeData() const
2004 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
2005 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
2007 return m_model
->createMimeData(selectedIndexes
);
2010 void DolphinView::updateWritableState()
2012 const bool wasFolderWritable
= m_isFolderWritable
;
2013 m_isFolderWritable
= false;
2015 KFileItem item
= m_model
->rootItem();
2016 if (item
.isNull()) {
2017 // Try to find out if the URL is writable even if the "root item" is
2018 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2019 item
= KFileItem(url());
2020 item
.setDelayedMimeTypes(true);
2023 KFileItemListProperties
capabilities(KFileItemList() << item
);
2024 m_isFolderWritable
= capabilities
.supportsWriting();
2026 if (m_isFolderWritable
!= wasFolderWritable
) {
2027 Q_EMIT
writeStateChanged(m_isFolderWritable
);
2031 QUrl
DolphinView::viewPropertiesUrl() const
2033 if (m_viewPropertiesContext
.isEmpty()) {
2038 url
.setScheme(m_url
.scheme());
2039 url
.setPath(m_viewPropertiesContext
);
2043 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
2045 forceUrlsSelection(urls
.first(), urls
);
2048 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
2051 m_clearSelectionBeforeSelectingNewItems
= true;
2052 markUrlAsCurrent(current
);
2053 markUrlsAsSelected(selected
);
2056 void DolphinView::copyPathToClipboard()
2058 const KFileItemList list
= selectedItems();
2059 if (list
.isEmpty()) {
2062 const KFileItem
& item
= list
.at(0);
2063 QString path
= item
.localPath();
2064 if (path
.isEmpty()) {
2065 path
= item
.url().toDisplayString();
2067 QClipboard
* clipboard
= QApplication::clipboard();
2068 if (clipboard
== nullptr) {
2071 clipboard
->setText(path
);
2074 void DolphinView::slotIncreaseZoom()
2076 setZoomLevel(zoomLevel() + 1);
2079 void DolphinView::slotDecreaseZoom()
2081 setZoomLevel(zoomLevel() - 1);
2084 void DolphinView::slotSwipeUp()
2086 Q_EMIT
goUpRequested();
2089 void DolphinView::showLoadingPlaceholder()
2091 m_placeholderLabel
->setText(i18n("Loading..."));
2092 m_placeholderLabel
->setVisible(true);
2095 void DolphinView::updatePlaceholderLabel()
2097 m_showLoadingPlaceholderTimer
->stop();
2098 if (itemsCount() > 0) {
2099 m_placeholderLabel
->setVisible(false);
2104 m_placeholderLabel
->setVisible(false);
2105 m_showLoadingPlaceholderTimer
->start();
2109 if (!nameFilter().isEmpty()) {
2110 m_placeholderLabel
->setText(i18n("No items matching the filter"));
2111 } else if (m_url
.scheme() == QLatin1String("baloosearch") || m_url
.scheme() == QLatin1String("filenamesearch")) {
2112 m_placeholderLabel
->setText(i18n("No items matching the search"));
2113 } else if (m_url
.scheme() == QLatin1String("trash") && m_url
.path() == QLatin1String("/")) {
2114 m_placeholderLabel
->setText(i18n("Trash is empty"));
2115 } else if (m_url
.scheme() == QLatin1String("tags")) {
2116 m_placeholderLabel
->setText(i18n("No tags"));
2117 } else if (m_url
.scheme() == QLatin1String("recentlyused")) {
2118 m_placeholderLabel
->setText(i18n("No recently used items"));
2119 } else if (m_url
.scheme() == QLatin1String("smb")) {
2120 m_placeholderLabel
->setText(i18n("No shared folders found"));
2121 } else if (m_url
.scheme() == QLatin1String("network")) {
2122 m_placeholderLabel
->setText(i18n("No relevant network resources found"));
2123 } else if (m_url
.scheme() == QLatin1String("mtp") && m_url
.path() == QLatin1String("/")) {
2124 m_placeholderLabel
->setText(i18n("No MTP-compatible devices found"));
2125 } else if (m_url
.scheme() == QLatin1String("bluetooth")) {
2126 m_placeholderLabel
->setText(i18n("No Bluetooth devices found"));
2128 m_placeholderLabel
->setText(i18n("Folder is empty"));
2131 m_placeholderLabel
->setVisible(true);