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 <QGraphicsSceneDragDropEvent>
53 #include <QMimeDatabase>
54 #include <QPixmapCache>
59 #include <QVBoxLayout>
61 DolphinView::DolphinView(const QUrl
& url
, QWidget
* parent
) :
64 m_tabsForFiles(false),
65 m_assureVisibleCurrentIndex(false),
66 m_isFolderWritable(true),
69 m_viewPropertiesContext(),
70 m_mode(DolphinView::IconsView
),
76 m_toolTipManager(nullptr),
77 m_selectionChangedTimer(nullptr),
79 m_scrollToCurrentItem(false),
80 m_restoredContentsPosition(),
82 m_clearSelectionBeforeSelectingNewItems(false),
83 m_markFirstNewlySelectedItemAsCurrent(false),
84 m_versionControlObserver(nullptr),
85 m_twoClicksRenamingTimer(nullptr)
87 m_topLayout
= new QVBoxLayout(this);
88 m_topLayout
->setSpacing(0);
89 m_topLayout
->setContentsMargins(0, 0, 0, 0);
91 // When a new item has been created by the "Create New..." menu, the item should
92 // get selected and it must be assured that the item will get visible. As the
93 // creation is done asynchronously, several signals must be checked:
94 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated
,
95 this, &DolphinView::observeCreatedItem
);
97 m_selectionChangedTimer
= new QTimer(this);
98 m_selectionChangedTimer
->setSingleShot(true);
99 m_selectionChangedTimer
->setInterval(300);
100 connect(m_selectionChangedTimer
, &QTimer::timeout
,
101 this, &DolphinView::emitSelectionChangedSignal
);
103 m_model
= new KFileItemModel(this);
104 m_view
= new DolphinItemListView();
105 m_view
->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
106 m_view
->setVisibleRoles({"text"});
109 KItemListController
* controller
= new KItemListController(m_model
, m_view
, this);
110 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
111 controller
->setAutoActivationDelay(delay
);
113 // The EnlargeSmallPreviews setting can only be changed after the model
114 // has been set in the view by KItemListController.
115 m_view
->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
117 m_container
= new KItemListContainer(controller
, this);
118 m_container
->installEventFilter(this);
119 setFocusProxy(m_container
);
120 connect(m_container
->horizontalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
121 connect(m_container
->verticalScrollBar(), &QScrollBar::valueChanged
, this, [=] { hideToolTip(); });
123 controller
->setSelectionBehavior(KItemListController::MultiSelection
);
124 connect(controller
, &KItemListController::itemActivated
, this, &DolphinView::slotItemActivated
);
125 connect(controller
, &KItemListController::itemsActivated
, this, &DolphinView::slotItemsActivated
);
126 connect(controller
, &KItemListController::itemMiddleClicked
, this, &DolphinView::slotItemMiddleClicked
);
127 connect(controller
, &KItemListController::itemContextMenuRequested
, this, &DolphinView::slotItemContextMenuRequested
);
128 connect(controller
, &KItemListController::viewContextMenuRequested
, this, &DolphinView::slotViewContextMenuRequested
);
129 connect(controller
, &KItemListController::headerContextMenuRequested
, this, &DolphinView::slotHeaderContextMenuRequested
);
130 connect(controller
, &KItemListController::mouseButtonPressed
, this, &DolphinView::slotMouseButtonPressed
);
131 connect(controller
, &KItemListController::itemHovered
, this, &DolphinView::slotItemHovered
);
132 connect(controller
, &KItemListController::itemUnhovered
, this, &DolphinView::slotItemUnhovered
);
133 connect(controller
, &KItemListController::itemDropEvent
, this, &DolphinView::slotItemDropEvent
);
134 connect(controller
, &KItemListController::escapePressed
, this, &DolphinView::stopLoading
);
135 connect(controller
, &KItemListController::modelChanged
, this, &DolphinView::slotModelChanged
);
136 connect(controller
, &KItemListController::selectedItemTextPressed
, this, &DolphinView::slotSelectedItemTextPressed
);
137 connect(controller
, &KItemListController::increaseZoom
, this, &DolphinView::slotIncreaseZoom
);
138 connect(controller
, &KItemListController::decreaseZoom
, this, &DolphinView::slotDecreaseZoom
);
139 connect(controller
, &KItemListController::swipeUp
, this, &DolphinView::slotSwipeUp
);
141 connect(m_model
, &KFileItemModel::directoryLoadingStarted
, this, &DolphinView::slotDirectoryLoadingStarted
);
142 connect(m_model
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
143 connect(m_model
, &KFileItemModel::directoryLoadingCanceled
, this, &DolphinView::directoryLoadingCanceled
);
144 connect(m_model
, &KFileItemModel::directoryLoadingProgress
, this, &DolphinView::directoryLoadingProgress
);
145 connect(m_model
, &KFileItemModel::directorySortingProgress
, this, &DolphinView::directorySortingProgress
);
146 connect(m_model
, &KFileItemModel::itemsChanged
,
147 this, &DolphinView::slotItemsChanged
);
148 connect(m_model
, &KFileItemModel::itemsRemoved
, this, &DolphinView::itemCountChanged
);
149 connect(m_model
, &KFileItemModel::itemsInserted
, this, &DolphinView::itemCountChanged
);
150 connect(m_model
, &KFileItemModel::infoMessage
, this, &DolphinView::infoMessage
);
151 connect(m_model
, &KFileItemModel::errorMessage
, this, &DolphinView::errorMessage
);
152 connect(m_model
, &KFileItemModel::directoryRedirection
, this, &DolphinView::slotDirectoryRedirection
);
153 connect(m_model
, &KFileItemModel::urlIsFileError
, this, &DolphinView::urlIsFileError
);
155 m_view
->installEventFilter(this);
156 connect(m_view
, &DolphinItemListView::sortOrderChanged
,
157 this, &DolphinView::slotSortOrderChangedByHeader
);
158 connect(m_view
, &DolphinItemListView::sortRoleChanged
,
159 this, &DolphinView::slotSortRoleChangedByHeader
);
160 connect(m_view
, &DolphinItemListView::visibleRolesChanged
,
161 this, &DolphinView::slotVisibleRolesChangedByHeader
);
162 connect(m_view
, &DolphinItemListView::roleEditingCanceled
,
163 this, &DolphinView::slotRoleEditingCanceled
);
164 connect(m_view
->header(), &KItemListHeader::columnWidthChangeFinished
,
165 this, &DolphinView::slotHeaderColumnWidthChangeFinished
);
167 KItemListSelectionManager
* selectionManager
= controller
->selectionManager();
168 connect(selectionManager
, &KItemListSelectionManager::selectionChanged
,
169 this, &DolphinView::slotSelectionChanged
);
172 m_toolTipManager
= new ToolTipManager(this);
173 connect(m_toolTipManager
, &ToolTipManager::urlActivated
, this, &DolphinView::urlActivated
);
176 m_versionControlObserver
= new VersionControlObserver(this);
177 m_versionControlObserver
->setView(this);
178 m_versionControlObserver
->setModel(m_model
);
179 connect(m_versionControlObserver
, &VersionControlObserver::infoMessage
, this, &DolphinView::infoMessage
);
180 connect(m_versionControlObserver
, &VersionControlObserver::errorMessage
, this, &DolphinView::errorMessage
);
181 connect(m_versionControlObserver
, &VersionControlObserver::operationCompletedMessage
, this, &DolphinView::operationCompletedMessage
);
183 m_twoClicksRenamingTimer
= new QTimer(this);
184 m_twoClicksRenamingTimer
->setSingleShot(true);
185 connect(m_twoClicksRenamingTimer
, &QTimer::timeout
, this, &DolphinView::slotTwoClicksRenamingTimerTimeout
);
187 applyViewProperties();
188 m_topLayout
->addWidget(m_container
);
193 DolphinView::~DolphinView()
197 QUrl
DolphinView::url() const
202 void DolphinView::setActive(bool active
)
204 if (active
== m_active
) {
213 m_container
->setFocus();
215 Q_EMIT
writeStateChanged(m_isFolderWritable
);
219 bool DolphinView::isActive() const
224 void DolphinView::setMode(Mode mode
)
226 if (mode
!= m_mode
) {
227 ViewProperties
props(viewPropertiesUrl());
228 props
.setViewMode(mode
);
230 // We pass the new ViewProperties to applyViewProperties, rather than
231 // storing them on disk and letting applyViewProperties() read them
232 // from there, to prevent that changing the view mode fails if the
233 // .directory file is not writable (see bug 318534).
234 applyViewProperties(props
);
238 DolphinView::Mode
DolphinView::mode() const
243 void DolphinView::setPreviewsShown(bool show
)
245 if (previewsShown() == show
) {
249 ViewProperties
props(viewPropertiesUrl());
250 props
.setPreviewsShown(show
);
252 const int oldZoomLevel
= m_view
->zoomLevel();
253 m_view
->setPreviewsShown(show
);
254 Q_EMIT
previewsShownChanged(show
);
256 const int newZoomLevel
= m_view
->zoomLevel();
257 if (newZoomLevel
!= oldZoomLevel
) {
258 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
262 bool DolphinView::previewsShown() const
264 return m_view
->previewsShown();
267 void DolphinView::setHiddenFilesShown(bool show
)
269 if (m_model
->showHiddenFiles() == show
) {
273 const KFileItemList itemList
= selectedItems();
274 m_selectedUrls
.clear();
275 m_selectedUrls
= itemList
.urlList();
277 ViewProperties
props(viewPropertiesUrl());
278 props
.setHiddenFilesShown(show
);
280 m_model
->setShowHiddenFiles(show
);
281 Q_EMIT
hiddenFilesShownChanged(show
);
284 bool DolphinView::hiddenFilesShown() const
286 return m_model
->showHiddenFiles();
289 void DolphinView::setGroupedSorting(bool grouped
)
291 if (grouped
== groupedSorting()) {
295 ViewProperties
props(viewPropertiesUrl());
296 props
.setGroupedSorting(grouped
);
299 m_container
->controller()->model()->setGroupedSorting(grouped
);
301 Q_EMIT
groupedSortingChanged(grouped
);
304 bool DolphinView::groupedSorting() const
306 return m_model
->groupedSorting();
309 KFileItemList
DolphinView::items() const
312 const int itemCount
= m_model
->count();
313 list
.reserve(itemCount
);
315 for (int i
= 0; i
< itemCount
; ++i
) {
316 list
.append(m_model
->fileItem(i
));
322 int DolphinView::itemsCount() const
324 return m_model
->count();
327 KFileItemList
DolphinView::selectedItems() const
329 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
331 KFileItemList selectedItems
;
332 const auto items
= selectionManager
->selectedItems();
333 selectedItems
.reserve(items
.count());
334 for (int index
: items
) {
335 selectedItems
.append(m_model
->fileItem(index
));
337 return selectedItems
;
340 int DolphinView::selectedItemsCount() const
342 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
343 return selectionManager
->selectedItems().count();
346 void DolphinView::markUrlsAsSelected(const QList
<QUrl
>& urls
)
348 m_selectedUrls
= urls
;
351 void DolphinView::markUrlAsCurrent(const QUrl
&url
)
353 m_currentItemUrl
= url
;
354 m_scrollToCurrentItem
= true;
357 void DolphinView::selectItems(const QRegularExpression
®exp
, bool enabled
)
359 const KItemListSelectionManager::SelectionMode mode
= enabled
360 ? KItemListSelectionManager::Select
361 : KItemListSelectionManager::Deselect
;
362 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
364 for (int index
= 0; index
< m_model
->count(); index
++) {
365 const KFileItem item
= m_model
->fileItem(index
);
366 if (regexp
.match(item
.text()).hasMatch()) {
367 // An alternative approach would be to store the matching items in a KItemSet and
368 // select them in one go after the loop, but we'd need a new function
369 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
371 selectionManager
->setSelected(index
, 1, mode
);
376 void DolphinView::setZoomLevel(int level
)
378 const int oldZoomLevel
= zoomLevel();
379 m_view
->setZoomLevel(level
);
380 if (zoomLevel() != oldZoomLevel
) {
382 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
386 int DolphinView::zoomLevel() const
388 return m_view
->zoomLevel();
391 void DolphinView::setSortRole(const QByteArray
& role
)
393 if (role
!= sortRole()) {
394 updateSortRole(role
);
398 QByteArray
DolphinView::sortRole() const
400 const KItemModelBase
* model
= m_container
->controller()->model();
401 return model
->sortRole();
404 void DolphinView::setSortOrder(Qt::SortOrder order
)
406 if (sortOrder() != order
) {
407 updateSortOrder(order
);
411 Qt::SortOrder
DolphinView::sortOrder() const
413 return m_model
->sortOrder();
416 void DolphinView::setSortFoldersFirst(bool foldersFirst
)
418 if (sortFoldersFirst() != foldersFirst
) {
419 updateSortFoldersFirst(foldersFirst
);
423 bool DolphinView::sortFoldersFirst() const
425 return m_model
->sortDirectoriesFirst();
428 void DolphinView::setVisibleRoles(const QList
<QByteArray
>& roles
)
430 const QList
<QByteArray
> previousRoles
= roles
;
432 ViewProperties
props(viewPropertiesUrl());
433 props
.setVisibleRoles(roles
);
435 m_visibleRoles
= roles
;
436 m_view
->setVisibleRoles(roles
);
438 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousRoles
);
441 QList
<QByteArray
> DolphinView::visibleRoles() const
443 return m_visibleRoles
;
446 void DolphinView::reload()
448 QByteArray viewState
;
449 QDataStream
saveStream(&viewState
, QIODevice::WriteOnly
);
450 saveState(saveStream
);
453 loadDirectory(url(), true);
455 QDataStream
restoreStream(viewState
);
456 restoreState(restoreStream
);
459 void DolphinView::readSettings()
461 const int oldZoomLevel
= m_view
->zoomLevel();
463 GeneralSettings::self()->load();
464 m_view
->readSettings();
465 applyViewProperties();
467 const int delay
= GeneralSettings::autoExpandFolders() ? 750 : -1;
468 m_container
->controller()->setAutoActivationDelay(delay
);
470 const int newZoomLevel
= m_view
->zoomLevel();
471 if (newZoomLevel
!= oldZoomLevel
) {
472 Q_EMIT
zoomLevelChanged(newZoomLevel
, oldZoomLevel
);
476 void DolphinView::writeSettings()
478 GeneralSettings::self()->save();
479 m_view
->writeSettings();
482 void DolphinView::setNameFilter(const QString
& nameFilter
)
484 m_model
->setNameFilter(nameFilter
);
487 QString
DolphinView::nameFilter() const
489 return m_model
->nameFilter();
492 void DolphinView::setMimeTypeFilters(const QStringList
& filters
)
494 return m_model
->setMimeTypeFilters(filters
);
497 QStringList
DolphinView::mimeTypeFilters() const
499 return m_model
->mimeTypeFilters();
502 QString
DolphinView::statusBarText() const
510 KIO::filesize_t totalFileSize
= 0;
512 if (m_container
->controller()->selectionManager()->hasSelection()) {
513 // Give a summary of the status of the selected files
514 const KFileItemList list
= selectedItems();
515 for (const KFileItem
& item
: list
) {
520 totalFileSize
+= item
.size();
524 if (folderCount
+ fileCount
== 1) {
525 // If only one item is selected, show info about it
526 return list
.first().getStatusBarInfo();
528 // At least 2 items are selected
529 foldersText
= i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount
);
530 filesText
= i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount
);
533 calculateItemCount(fileCount
, folderCount
, totalFileSize
);
534 foldersText
= i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount
);
535 filesText
= i18ncp("@info:status", "1 File", "%1 Files", fileCount
);
538 if (fileCount
> 0 && folderCount
> 0) {
539 summary
= i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
540 foldersText
, filesText
,
541 KFormat().formatByteSize(totalFileSize
));
542 } else if (fileCount
> 0) {
543 summary
= i18nc("@info:status files (size)", "%1 (%2)",
545 KFormat().formatByteSize(totalFileSize
));
546 } else if (folderCount
> 0) {
547 summary
= foldersText
;
549 summary
= i18nc("@info:status", "0 Folders, 0 Files");
555 QList
<QAction
*> DolphinView::versionControlActions(const KFileItemList
& items
) const
557 QList
<QAction
*> actions
;
559 if (items
.isEmpty()) {
560 const KFileItem item
= m_model
->rootItem();
561 if (!item
.isNull()) {
562 actions
= m_versionControlObserver
->actions(KFileItemList() << item
);
565 actions
= m_versionControlObserver
->actions(items
);
571 void DolphinView::setUrl(const QUrl
& url
)
583 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
584 this, &DolphinView::slotRoleEditingFinished
);
586 // It is important to clear the items from the model before
587 // applying the view properties, otherwise expensive operations
588 // might be done on the existing items although they get cleared
589 // anyhow afterwards by loadDirectory().
591 applyViewProperties();
594 Q_EMIT
urlChanged(url
);
597 void DolphinView::selectAll()
599 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
600 selectionManager
->setSelected(0, m_model
->count());
603 void DolphinView::invertSelection()
605 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
606 selectionManager
->setSelected(0, m_model
->count(), KItemListSelectionManager::Toggle
);
609 void DolphinView::clearSelection()
611 m_selectedUrls
.clear();
612 m_container
->controller()->selectionManager()->clearSelection();
615 void DolphinView::renameSelectedItems()
617 const KFileItemList items
= selectedItems();
618 if (items
.isEmpty()) {
622 if (items
.count() == 1 && GeneralSettings::renameInline()) {
623 const int index
= m_model
->index(items
.first());
624 m_view
->editRole(index
, "text");
628 connect(m_view
, &DolphinItemListView::roleEditingFinished
,
629 this, &DolphinView::slotRoleEditingFinished
);
631 KIO::RenameFileDialog
* dialog
= new KIO::RenameFileDialog(items
, this);
632 connect(dialog
, &KIO::RenameFileDialog::renamingFinished
,
633 this, &DolphinView::slotRenameDialogRenamingFinished
);
638 // Assure that the current index remains visible when KFileItemModel
639 // will notify the view about changed items (which might result in
640 // a changed sorting).
641 m_assureVisibleCurrentIndex
= true;
644 void DolphinView::trashSelectedItems()
646 const QList
<QUrl
> list
= simplifiedSelectedUrls();
647 KIO::JobUiDelegate uiDelegate
;
648 uiDelegate
.setWindow(window());
649 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Trash
, KIO::JobUiDelegate::DefaultConfirmation
)) {
650 KIO::Job
* job
= KIO::trash(list
);
651 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash
, list
, QUrl(QStringLiteral("trash:/")), job
);
652 KJobWidgets::setWindow(job
, this);
653 connect(job
, &KIO::Job::result
,
654 this, &DolphinView::slotTrashFileFinished
);
658 void DolphinView::deleteSelectedItems()
660 const QList
<QUrl
> list
= simplifiedSelectedUrls();
662 KIO::JobUiDelegate uiDelegate
;
663 uiDelegate
.setWindow(window());
664 if (uiDelegate
.askDeleteConfirmation(list
, KIO::JobUiDelegate::Delete
, KIO::JobUiDelegate::DefaultConfirmation
)) {
665 KIO::Job
* job
= KIO::del(list
);
666 KJobWidgets::setWindow(job
, this);
667 connect(job
, &KIO::Job::result
,
668 this, &DolphinView::slotDeleteFileFinished
);
672 void DolphinView::cutSelectedItemsToClipboard()
674 QMimeData
* mimeData
= selectionMimeData();
675 KIO::setClipboardDataCut(mimeData
, true);
676 QApplication::clipboard()->setMimeData(mimeData
);
679 void DolphinView::copySelectedItemsToClipboard()
681 QMimeData
* mimeData
= selectionMimeData();
682 QApplication::clipboard()->setMimeData(mimeData
);
685 void DolphinView::copySelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
687 KIO::CopyJob
* job
= KIO::copy(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
688 KJobWidgets::setWindow(job
, this);
690 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
691 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
692 KIO::FileUndoManager::self()->recordCopyJob(job
);
695 void DolphinView::moveSelectedItems(const KFileItemList
&selection
, const QUrl
&destinationUrl
)
697 KIO::CopyJob
* job
= KIO::move(selection
.urlList(), destinationUrl
, KIO::DefaultFlags
);
698 KJobWidgets::setWindow(job
, this);
700 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
701 connect(job
, &KIO::CopyJob::copyingDone
, this, &DolphinView::slotCopyingDone
);
702 KIO::FileUndoManager::self()->recordCopyJob(job
);
706 void DolphinView::paste()
711 void DolphinView::pasteIntoFolder()
713 const KFileItemList items
= selectedItems();
714 if ((items
.count() == 1) && items
.first().isDir()) {
715 pasteToUrl(items
.first().url());
719 void DolphinView::duplicateSelectedItems()
721 const KFileItemList itemList
= selectedItems();
722 if (itemList
.isEmpty()) {
726 const QMimeDatabase db
;
728 // Duplicate all selected items and append "copy" to the end of the file name
729 // but before the filename extension, if present
730 QList
<QUrl
> newSelection
;
731 for (const auto &item
: itemList
) {
732 const QUrl originalURL
= item
.url();
733 const QString originalDirectoryPath
= originalURL
.adjusted(QUrl::RemoveFilename
).path();
734 const QString originalFileName
= item
.name();
736 QString extension
= db
.suffixForFileName(originalFileName
);
738 QUrl duplicateURL
= originalURL
;
740 // No extension; new filename is "<oldfilename> copy"
741 if (extension
.isEmpty()) {
742 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFileName
));
743 // There's an extension; new filename is "<oldfilename> copy.<extension>"
745 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
746 extension
= QLatin1String(".") + extension
;
747 const QString originalFilenameWithoutExtension
= originalFileName
.chopped(extension
.size());
748 // Preserve file's original filename extension in case the casing differs
749 // from what QMimeDatabase::suffixForFileName() returned
750 const QString originalExtension
= originalFileName
.right(extension
.size());
751 duplicateURL
.setPath(originalDirectoryPath
+ i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension
) + originalExtension
);
754 KIO::CopyJob
* job
= KIO::copyAs(originalURL
, duplicateURL
);
755 KJobWidgets::setWindow(job
, this);
758 newSelection
<< duplicateURL
;
759 KIO::FileUndoManager::self()->recordCopyJob(job
);
763 forceUrlsSelection(newSelection
.first(), newSelection
);
766 void DolphinView::stopLoading()
768 m_model
->cancelDirectoryLoading();
771 void DolphinView::updatePalette()
773 QColor color
= KColorScheme(isActiveWindow() ? QPalette::Active
: QPalette::Inactive
, KColorScheme::View
).background().color();
778 QWidget
* viewport
= m_container
->viewport();
781 palette
.setColor(viewport
->backgroundRole(), color
);
782 viewport
->setPalette(palette
);
788 void DolphinView::abortTwoClicksRenaming()
790 m_twoClicksRenamingItemUrl
.clear();
791 m_twoClicksRenamingTimer
->stop();
794 bool DolphinView::eventFilter(QObject
* watched
, QEvent
* event
)
796 switch (event
->type()) {
797 case QEvent::PaletteChange
:
799 QPixmapCache::clear();
802 case QEvent::WindowActivate
:
803 case QEvent::WindowDeactivate
:
807 case QEvent::KeyPress
:
808 hideToolTip(ToolTipManager::HideBehavior::Instantly
);
809 if (GeneralSettings::useTabForSwitchingSplitView()) {
810 QKeyEvent
* keyEvent
= static_cast<QKeyEvent
*>(event
);
811 if (keyEvent
->key() == Qt::Key_Tab
&& keyEvent
->modifiers() == Qt::NoModifier
) {
812 Q_EMIT
toggleActiveViewRequested();
817 case QEvent::FocusIn
:
818 if (watched
== m_container
) {
823 case QEvent::GraphicsSceneDragEnter
:
824 if (watched
== m_view
) {
826 abortTwoClicksRenaming();
830 case QEvent::GraphicsSceneDragLeave
:
831 if (watched
== m_view
) {
836 case QEvent::GraphicsSceneDrop
:
837 if (watched
== m_view
) {
844 return QWidget::eventFilter(watched
, event
);
847 void DolphinView::wheelEvent(QWheelEvent
* event
)
849 if (event
->modifiers().testFlag(Qt::ControlModifier
)) {
850 const int numDegrees
= event
->delta() / 8;
851 const int numSteps
= numDegrees
/ 15;
853 setZoomLevel(zoomLevel() + numSteps
);
860 void DolphinView::hideEvent(QHideEvent
* event
)
863 QWidget::hideEvent(event
);
866 bool DolphinView::event(QEvent
* event
)
868 if (event
->type() == QEvent::WindowDeactivate
) {
870 * Dolphin leaves file preview tooltips open even when is not visible.
872 * Hide tool-tip when Dolphin loses focus.
875 abortTwoClicksRenaming();
878 return QWidget::event(event
);
881 void DolphinView::activate()
886 void DolphinView::slotItemActivated(int index
)
888 abortTwoClicksRenaming();
890 const KFileItem item
= m_model
->fileItem(index
);
891 if (!item
.isNull()) {
892 Q_EMIT
itemActivated(item
);
896 void DolphinView::slotItemsActivated(const KItemSet
& indexes
)
898 Q_ASSERT(indexes
.count() >= 2);
900 abortTwoClicksRenaming();
902 if (indexes
.count() > 5) {
903 QString question
= i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes
.count());
904 const int answer
= KMessageBox::warningYesNo(this, question
);
905 if (answer
!= KMessageBox::Yes
) {
911 items
.reserve(indexes
.count());
913 for (int index
: indexes
) {
914 KFileItem item
= m_model
->fileItem(index
);
915 const QUrl
& url
= openItemAsFolderUrl(item
);
917 if (!url
.isEmpty()) { // Open folders in new tabs
918 Q_EMIT
tabRequested(url
, DolphinTabWidget::AfterLastTab
);
924 if (items
.count() == 1) {
925 Q_EMIT
itemActivated(items
.first());
926 } else if (items
.count() > 1) {
927 Q_EMIT
itemsActivated(items
);
931 void DolphinView::slotItemMiddleClicked(int index
)
933 const KFileItem
& item
= m_model
->fileItem(index
);
934 const QUrl
& url
= openItemAsFolderUrl(item
);
935 if (!url
.isEmpty()) {
936 Q_EMIT
tabRequested(url
, DolphinTabWidget::AfterCurrentTab
);
937 } else if (isTabsForFilesEnabled()) {
938 Q_EMIT
tabRequested(item
.url(), DolphinTabWidget::AfterCurrentTab
);
942 void DolphinView::slotItemContextMenuRequested(int index
, const QPointF
& pos
)
944 // Force emit of a selection changed signal before we request the
945 // context menu, to update the edit-actions first. (See Bug 294013)
946 if (m_selectionChangedTimer
->isActive()) {
947 emitSelectionChangedSignal();
950 const KFileItem item
= m_model
->fileItem(index
);
951 Q_EMIT
requestContextMenu(pos
.toPoint(), item
, url(), QList
<QAction
*>());
954 void DolphinView::slotViewContextMenuRequested(const QPointF
& pos
)
956 Q_EMIT
requestContextMenu(pos
.toPoint(), KFileItem(), url(), QList
<QAction
*>());
959 void DolphinView::slotHeaderContextMenuRequested(const QPointF
& pos
)
961 ViewProperties
props(viewPropertiesUrl());
963 QPointer
<QMenu
> menu
= new QMenu(QApplication::activeWindow());
965 KItemListView
* view
= m_container
->controller()->view();
966 const QList
<QByteArray
> visibleRolesSet
= view
->visibleRoles();
968 bool indexingEnabled
= false;
970 Baloo::IndexerConfig config
;
971 indexingEnabled
= config
.fileIndexingEnabled();
975 QMenu
* groupMenu
= nullptr;
977 // Add all roles to the menu that can be shown or hidden by the user
978 const QList
<KFileItemModel::RoleInfo
> rolesInfo
= KFileItemModel::rolesInformation();
979 for (const KFileItemModel::RoleInfo
& info
: rolesInfo
) {
980 if (info
.role
== "text") {
981 // It should not be possible to hide the "text" role
985 const QString text
= m_model
->roleDescription(info
.role
);
986 QAction
* action
= nullptr;
987 if (info
.group
.isEmpty()) {
988 action
= menu
->addAction(text
);
990 if (!groupMenu
|| info
.group
!= groupName
) {
991 groupName
= info
.group
;
992 groupMenu
= menu
->addMenu(groupName
);
995 action
= groupMenu
->addAction(text
);
998 action
->setCheckable(true);
999 action
->setChecked(visibleRolesSet
.contains(info
.role
));
1000 action
->setData(info
.role
);
1002 const bool enable
= (!info
.requiresBaloo
&& !info
.requiresIndexer
) ||
1003 (info
.requiresBaloo
) ||
1004 (info
.requiresIndexer
&& indexingEnabled
);
1005 action
->setEnabled(enable
);
1008 menu
->addSeparator();
1010 QActionGroup
* widthsGroup
= new QActionGroup(menu
);
1011 const bool autoColumnWidths
= props
.headerColumnWidths().isEmpty();
1013 QAction
* autoAdjustWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1014 autoAdjustWidthsAction
->setCheckable(true);
1015 autoAdjustWidthsAction
->setChecked(autoColumnWidths
);
1016 autoAdjustWidthsAction
->setActionGroup(widthsGroup
);
1018 QAction
* customWidthsAction
= menu
->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1019 customWidthsAction
->setCheckable(true);
1020 customWidthsAction
->setChecked(!autoColumnWidths
);
1021 customWidthsAction
->setActionGroup(widthsGroup
);
1023 QAction
* action
= menu
->exec(pos
.toPoint());
1024 if (menu
&& action
) {
1025 KItemListHeader
* header
= view
->header();
1027 if (action
== autoAdjustWidthsAction
) {
1028 // Clear the column-widths from the viewproperties and turn on
1029 // the automatic resizing of the columns
1030 props
.setHeaderColumnWidths(QList
<int>());
1031 header
->setAutomaticColumnResizing(true);
1032 } else if (action
== customWidthsAction
) {
1033 // Apply the current column-widths as custom column-widths and turn
1034 // off the automatic resizing of the columns
1035 QList
<int> columnWidths
;
1036 const auto visibleRoles
= view
->visibleRoles();
1037 columnWidths
.reserve(visibleRoles
.count());
1038 for (const QByteArray
& role
: visibleRoles
) {
1039 columnWidths
.append(header
->columnWidth(role
));
1041 props
.setHeaderColumnWidths(columnWidths
);
1042 header
->setAutomaticColumnResizing(false);
1044 // Show or hide the selected role
1045 const QByteArray selectedRole
= action
->data().toByteArray();
1047 QList
<QByteArray
> visibleRoles
= view
->visibleRoles();
1048 if (action
->isChecked()) {
1049 visibleRoles
.append(selectedRole
);
1051 visibleRoles
.removeOne(selectedRole
);
1054 view
->setVisibleRoles(visibleRoles
);
1055 props
.setVisibleRoles(visibleRoles
);
1057 QList
<int> columnWidths
;
1058 if (!header
->automaticColumnResizing()) {
1059 const auto visibleRoles
= view
->visibleRoles();
1060 columnWidths
.reserve(visibleRoles
.count());
1061 for (const QByteArray
& role
: visibleRoles
) {
1062 columnWidths
.append(header
->columnWidth(role
));
1065 props
.setHeaderColumnWidths(columnWidths
);
1072 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray
& role
, qreal current
)
1074 const QList
<QByteArray
> visibleRoles
= m_view
->visibleRoles();
1076 ViewProperties
props(viewPropertiesUrl());
1077 QList
<int> columnWidths
= props
.headerColumnWidths();
1078 if (columnWidths
.count() != visibleRoles
.count()) {
1079 columnWidths
.clear();
1080 columnWidths
.reserve(visibleRoles
.count());
1081 const KItemListHeader
* header
= m_view
->header();
1082 for (const QByteArray
& role
: visibleRoles
) {
1083 const int width
= header
->columnWidth(role
);
1084 columnWidths
.append(width
);
1088 const int roleIndex
= visibleRoles
.indexOf(role
);
1089 Q_ASSERT(roleIndex
>= 0 && roleIndex
< columnWidths
.count());
1090 columnWidths
[roleIndex
] = current
;
1092 props
.setHeaderColumnWidths(columnWidths
);
1095 void DolphinView::slotItemHovered(int index
)
1097 const KFileItem item
= m_model
->fileItem(index
);
1099 if (GeneralSettings::showToolTips() && !m_dragging
) {
1100 QRectF itemRect
= m_container
->controller()->view()->itemContextRect(index
);
1101 const QPoint pos
= m_container
->mapToGlobal(itemRect
.topLeft().toPoint());
1102 itemRect
.moveTo(pos
);
1105 m_toolTipManager
->showToolTip(item
, itemRect
, nativeParentWidget()->windowHandle());
1109 Q_EMIT
requestItemInfo(item
);
1112 void DolphinView::slotItemUnhovered(int index
)
1116 Q_EMIT
requestItemInfo(KFileItem());
1119 void DolphinView::slotItemDropEvent(int index
, QGraphicsSceneDragDropEvent
* event
)
1122 KFileItem destItem
= m_model
->fileItem(index
);
1123 if (destItem
.isNull() || (!destItem
.isDir() && !destItem
.isDesktopFile())) {
1124 // Use the URL of the view as drop target if the item is no directory
1126 destItem
= m_model
->rootItem();
1129 // The item represents a directory or desktop-file
1130 destUrl
= destItem
.mostLocalUrl();
1133 QDropEvent
dropEvent(event
->pos().toPoint(),
1134 event
->possibleActions(),
1137 event
->modifiers());
1138 dropUrls(destUrl
, &dropEvent
, this);
1143 void DolphinView::dropUrls(const QUrl
&destUrl
, QDropEvent
*dropEvent
, QWidget
*dropWidget
)
1145 KIO::DropJob
* job
= DragAndDropHelper::dropUrls(destUrl
, dropEvent
, dropWidget
);
1148 connect(job
, &KIO::DropJob::result
, this, &DolphinView::slotJobResult
);
1150 if (destUrl
== url()) {
1151 // Mark the dropped urls as selected.
1152 m_clearSelectionBeforeSelectingNewItems
= true;
1153 m_markFirstNewlySelectedItemAsCurrent
= true;
1154 connect(job
, &KIO::DropJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1159 void DolphinView::slotModelChanged(KItemModelBase
* current
, KItemModelBase
* previous
)
1161 if (previous
!= nullptr) {
1162 Q_ASSERT(qobject_cast
<KFileItemModel
*>(previous
));
1163 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(previous
);
1164 disconnect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1165 m_versionControlObserver
->setModel(nullptr);
1169 Q_ASSERT(qobject_cast
<KFileItemModel
*>(current
));
1170 KFileItemModel
* fileItemModel
= static_cast<KFileItemModel
*>(current
);
1171 connect(fileItemModel
, &KFileItemModel::directoryLoadingCompleted
, this, &DolphinView::slotDirectoryLoadingCompleted
);
1172 m_versionControlObserver
->setModel(fileItemModel
);
1176 void DolphinView::slotMouseButtonPressed(int itemIndex
, Qt::MouseButtons buttons
)
1182 if (buttons
& Qt::BackButton
) {
1183 Q_EMIT
goBackRequested();
1184 } else if (buttons
& Qt::ForwardButton
) {
1185 Q_EMIT
goForwardRequested();
1189 void DolphinView::slotSelectedItemTextPressed(int index
)
1191 if (GeneralSettings::renameInline() && !m_view
->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick
)) {
1192 const KFileItem item
= m_model
->fileItem(index
);
1193 const KFileItemListProperties
capabilities(KFileItemList() << item
);
1194 if (capabilities
.supportsMoving()) {
1195 m_twoClicksRenamingItemUrl
= item
.url();
1196 m_twoClicksRenamingTimer
->start(QApplication::doubleClickInterval());
1201 void DolphinView::slotCopyingDone(KIO::Job
*, const QUrl
&, const QUrl
&to
)
1203 slotItemCreated(to
);
1206 void DolphinView::slotItemCreated(const QUrl
& url
)
1208 if (m_markFirstNewlySelectedItemAsCurrent
) {
1209 markUrlAsCurrent(url
);
1210 m_markFirstNewlySelectedItemAsCurrent
= false;
1212 m_selectedUrls
<< url
;
1215 void DolphinView::slotJobResult(KJob
*job
)
1218 Q_EMIT
errorMessage(job
->errorString());
1220 if (!m_selectedUrls
.isEmpty()) {
1221 m_selectedUrls
= KDirModel::simplifiedUrlList(m_selectedUrls
);
1225 void DolphinView::slotSelectionChanged(const KItemSet
& current
, const KItemSet
& previous
)
1227 const int currentCount
= current
.count();
1228 const int previousCount
= previous
.count();
1229 const bool selectionStateChanged
= (currentCount
== 0 && previousCount
> 0) ||
1230 (currentCount
> 0 && previousCount
== 0);
1232 // If nothing has been selected before and something got selected (or if something
1233 // was selected before and now nothing is selected) the selectionChangedSignal must
1234 // be emitted asynchronously as fast as possible to update the edit-actions.
1235 m_selectionChangedTimer
->setInterval(selectionStateChanged
? 0 : 300);
1236 m_selectionChangedTimer
->start();
1239 void DolphinView::emitSelectionChangedSignal()
1241 m_selectionChangedTimer
->stop();
1242 Q_EMIT
selectionChanged(selectedItems());
1245 void DolphinView::updateSortRole(const QByteArray
& role
)
1247 ViewProperties
props(viewPropertiesUrl());
1248 props
.setSortRole(role
);
1250 KItemModelBase
* model
= m_container
->controller()->model();
1251 model
->setSortRole(role
);
1253 Q_EMIT
sortRoleChanged(role
);
1256 void DolphinView::updateSortOrder(Qt::SortOrder order
)
1258 ViewProperties
props(viewPropertiesUrl());
1259 props
.setSortOrder(order
);
1261 m_model
->setSortOrder(order
);
1263 Q_EMIT
sortOrderChanged(order
);
1266 void DolphinView::updateSortFoldersFirst(bool foldersFirst
)
1268 ViewProperties
props(viewPropertiesUrl());
1269 props
.setSortFoldersFirst(foldersFirst
);
1271 m_model
->setSortDirectoriesFirst(foldersFirst
);
1273 Q_EMIT
sortFoldersFirstChanged(foldersFirst
);
1276 QPair
<bool, QString
> DolphinView::pasteInfo() const
1278 const QMimeData
*mimeData
= QApplication::clipboard()->mimeData();
1279 QPair
<bool, QString
> info
;
1280 info
.second
= KIO::pasteActionText(mimeData
, &info
.first
, rootItem());
1284 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles
)
1286 m_tabsForFiles
= tabsForFiles
;
1289 bool DolphinView::isTabsForFilesEnabled() const
1291 return m_tabsForFiles
;
1294 bool DolphinView::itemsExpandable() const
1296 return m_mode
== DetailsView
;
1299 void DolphinView::restoreState(QDataStream
& stream
)
1301 // Read the version number of the view state and check if the version is supported.
1302 quint32 version
= 0;
1305 // The version of the view state isn't supported, we can't restore it.
1309 // Restore the current item that had the keyboard focus
1310 stream
>> m_currentItemUrl
;
1312 // Restore the previously selected items
1313 stream
>> m_selectedUrls
;
1315 // Restore the view position
1316 stream
>> m_restoredContentsPosition
;
1318 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1321 m_model
->restoreExpandedDirectories(urls
);
1324 void DolphinView::saveState(QDataStream
& stream
)
1326 stream
<< quint32(1); // View state version
1328 // Save the current item that has the keyboard focus
1329 const int currentIndex
= m_container
->controller()->selectionManager()->currentItem();
1330 if (currentIndex
!= -1) {
1331 KFileItem item
= m_model
->fileItem(currentIndex
);
1332 Q_ASSERT(!item
.isNull()); // If the current index is valid a item must exist
1333 QUrl currentItemUrl
= item
.url();
1334 stream
<< currentItemUrl
;
1339 // Save the selected urls
1340 stream
<< selectedItems().urlList();
1342 // Save view position
1343 const qreal x
= m_container
->horizontalScrollBar()->value();
1344 const qreal y
= m_container
->verticalScrollBar()->value();
1345 stream
<< QPoint(x
, y
);
1347 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1348 stream
<< m_model
->expandedDirectories();
1351 KFileItem
DolphinView::rootItem() const
1353 return m_model
->rootItem();
1356 void DolphinView::setViewPropertiesContext(const QString
& context
)
1358 m_viewPropertiesContext
= context
;
1361 QString
DolphinView::viewPropertiesContext() const
1363 return m_viewPropertiesContext
;
1366 QUrl
DolphinView::openItemAsFolderUrl(const KFileItem
& item
, const bool browseThroughArchives
)
1368 if (item
.isNull()) {
1372 QUrl url
= item
.targetUrl();
1378 if (item
.isMimeTypeKnown()) {
1379 const QString
& mimetype
= item
.mimetype();
1381 if (browseThroughArchives
&& item
.isFile() && url
.isLocalFile()) {
1382 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1383 // zip:/<path>/ when clicking on a zip file, etc.
1384 // The .protocol file specifies the mimetype that the kioslave handles.
1385 // Note that we don't use mimetype inheritance since we don't want to
1386 // open OpenDocument files as zip folders...
1387 const QString
& protocol
= KProtocolManager::protocolForArchiveMimetype(mimetype
);
1388 if (!protocol
.isEmpty()) {
1389 url
.setScheme(protocol
);
1394 if (mimetype
== QLatin1String("application/x-desktop")) {
1395 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1396 KDesktopFile
desktopFile(url
.toLocalFile());
1397 if (desktopFile
.hasLinkType()) {
1398 const QString linkUrl
= desktopFile
.readUrl();
1399 if (!linkUrl
.startsWith(QLatin1String("http"))) {
1400 return QUrl::fromUserInput(linkUrl
);
1409 void DolphinView::resetZoomLevel()
1411 ViewModeSettings::ViewMode mode
;
1414 case IconsView
: mode
= ViewModeSettings::IconsMode
; break;
1415 case CompactView
: mode
= ViewModeSettings::CompactMode
; break;
1416 case DetailsView
: mode
= ViewModeSettings::DetailsMode
; break;
1418 const ViewModeSettings
settings(mode
);
1419 const QSize iconSize
= QSize(settings
.iconSize(), settings
.iconSize());
1420 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize
));
1423 void DolphinView::observeCreatedItem(const QUrl
& url
)
1426 forceUrlsSelection(url
, {url
});
1430 void DolphinView::slotDirectoryRedirection(const QUrl
& oldUrl
, const QUrl
& newUrl
)
1432 if (oldUrl
.matches(url(), QUrl::StripTrailingSlash
)) {
1433 Q_EMIT
redirection(oldUrl
, newUrl
);
1434 m_url
= newUrl
; // #186947
1438 void DolphinView::updateViewState()
1440 if (m_currentItemUrl
!= QUrl()) {
1441 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1443 // if there is a selection already, leave it that way
1444 if (!selectionManager
->hasSelection()) {
1445 const int currentIndex
= m_model
->index(m_currentItemUrl
);
1446 if (currentIndex
!= -1) {
1447 selectionManager
->setCurrentItem(currentIndex
);
1449 // scroll to current item and reset the state
1450 if (m_scrollToCurrentItem
) {
1451 m_view
->scrollToItem(currentIndex
);
1452 m_scrollToCurrentItem
= false;
1455 selectionManager
->setCurrentItem(0);
1459 m_currentItemUrl
= QUrl();
1462 if (!m_restoredContentsPosition
.isNull()) {
1463 const int x
= m_restoredContentsPosition
.x();
1464 const int y
= m_restoredContentsPosition
.y();
1465 m_restoredContentsPosition
= QPoint();
1467 m_container
->horizontalScrollBar()->setValue(x
);
1468 m_container
->verticalScrollBar()->setValue(y
);
1471 if (!m_selectedUrls
.isEmpty()) {
1472 KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1474 // if there is a selection already, leave it that way
1475 if (!selectionManager
->hasSelection()) {
1476 if (m_clearSelectionBeforeSelectingNewItems
) {
1477 selectionManager
->clearSelection();
1478 m_clearSelectionBeforeSelectingNewItems
= false;
1481 KItemSet selectedItems
= selectionManager
->selectedItems();
1483 QList
<QUrl
>::iterator it
= m_selectedUrls
.begin();
1484 while (it
!= m_selectedUrls
.end()) {
1485 const int index
= m_model
->index(*it
);
1487 selectedItems
.insert(index
);
1488 it
= m_selectedUrls
.erase(it
);
1494 selectionManager
->beginAnchoredSelection(selectionManager
->currentItem());
1495 selectionManager
->setSelectedItems(selectedItems
);
1500 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior
)
1503 if (GeneralSettings::showToolTips()) {
1504 m_toolTipManager
->hideToolTip(behavior
);
1511 void DolphinView::calculateItemCount(int& fileCount
,
1513 KIO::filesize_t
& totalFileSize
) const
1515 const int itemCount
= m_model
->count();
1517 bool countFileSize
= true;
1519 if (!m_model
->rootItem().url().isValid()) {
1523 // In case we have a precomputed value
1524 const auto job
= KIO::statDetails(m_model
->rootItem().url(), KIO::StatJob::SourceSide
, KIO::StatRecursiveSize
, KIO::HideProgressInfo
);
1526 const auto entry
= job
->statResult();
1527 if (entry
.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE
)) {
1528 totalFileSize
= static_cast<KIO::filesize_t
>(entry
.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE
));
1529 countFileSize
= false;
1532 for (int i
= 0; i
< itemCount
; ++i
) {
1533 const KFileItem item
= m_model
->fileItem(i
);
1538 if (countFileSize
) {
1539 totalFileSize
+= item
.size();
1545 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1547 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1549 // verify that only one item is selected
1550 if (selectionManager
->selectedItems().count() == 1) {
1551 const int index
= selectionManager
->currentItem();
1552 const QUrl fileItemUrl
= m_model
->fileItem(index
).url();
1554 // check if the selected item was the same item that started the twoClicksRenaming
1555 if (fileItemUrl
.isValid() && m_twoClicksRenamingItemUrl
== fileItemUrl
) {
1556 renameSelectedItems();
1561 void DolphinView::slotTrashFileFinished(KJob
* job
)
1563 if (job
->error() == 0) {
1564 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1565 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1566 Q_EMIT
errorMessage(job
->errorString());
1570 void DolphinView::slotDeleteFileFinished(KJob
* job
)
1572 if (job
->error() == 0) {
1573 Q_EMIT
operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1574 } else if (job
->error() != KIO::ERR_USER_CANCELED
) {
1575 Q_EMIT
errorMessage(job
->errorString());
1579 void DolphinView::slotRenamingResult(KJob
* job
)
1582 KIO::CopyJob
*copyJob
= qobject_cast
<KIO::CopyJob
*>(job
);
1584 const QUrl newUrl
= copyJob
->destUrl();
1585 const int index
= m_model
->index(newUrl
);
1587 QHash
<QByteArray
, QVariant
> data
;
1588 const QUrl oldUrl
= copyJob
->srcUrls().at(0);
1589 data
.insert("text", oldUrl
.fileName());
1590 m_model
->setData(index
, data
);
1595 void DolphinView::slotDirectoryLoadingStarted()
1597 // Disable the writestate temporary until it can be determined in a fast way
1598 // in DolphinView::slotDirectoryLoadingCompleted()
1599 if (m_isFolderWritable
) {
1600 m_isFolderWritable
= false;
1601 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1604 Q_EMIT
directoryLoadingStarted();
1607 void DolphinView::slotDirectoryLoadingCompleted()
1609 // Update the view-state. This has to be done asynchronously
1610 // because the view might not be in its final state yet.
1611 QTimer::singleShot(0, this, &DolphinView::updateViewState
);
1613 Q_EMIT
directoryLoadingCompleted();
1615 updateWritableState();
1618 void DolphinView::slotItemsChanged()
1620 m_assureVisibleCurrentIndex
= false;
1623 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current
, Qt::SortOrder previous
)
1626 Q_ASSERT(m_model
->sortOrder() == current
);
1628 ViewProperties
props(viewPropertiesUrl());
1629 props
.setSortOrder(current
);
1631 Q_EMIT
sortOrderChanged(current
);
1634 void DolphinView::slotSortRoleChangedByHeader(const QByteArray
& current
, const QByteArray
& previous
)
1637 Q_ASSERT(m_model
->sortRole() == current
);
1639 ViewProperties
props(viewPropertiesUrl());
1640 props
.setSortRole(current
);
1642 Q_EMIT
sortRoleChanged(current
);
1645 void DolphinView::slotVisibleRolesChangedByHeader(const QList
<QByteArray
>& current
,
1646 const QList
<QByteArray
>& previous
)
1649 Q_ASSERT(m_container
->controller()->view()->visibleRoles() == current
);
1651 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1653 m_visibleRoles
= current
;
1655 ViewProperties
props(viewPropertiesUrl());
1656 props
.setVisibleRoles(m_visibleRoles
);
1658 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1661 void DolphinView::slotRoleEditingCanceled()
1663 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1664 this, &DolphinView::slotRoleEditingFinished
);
1667 void DolphinView::slotRoleEditingFinished(int index
, const QByteArray
& role
, const QVariant
& value
)
1669 disconnect(m_view
, &DolphinItemListView::roleEditingFinished
,
1670 this, &DolphinView::slotRoleEditingFinished
);
1672 if (index
< 0 || index
>= m_model
->count()) {
1676 if (role
== "text") {
1677 const KFileItem oldItem
= m_model
->fileItem(index
);
1678 const QString newName
= value
.toString();
1679 if (!newName
.isEmpty() && newName
!= oldItem
.text() && newName
!= QLatin1Char('.') && newName
!= QLatin1String("..")) {
1680 const QUrl oldUrl
= oldItem
.url();
1682 QUrl newUrl
= oldUrl
.adjusted(QUrl::RemoveFilename
);
1683 newUrl
.setPath(newUrl
.path() + KIO::encodeFileName(newName
));
1686 //Confirm hiding file/directory by renaming inline
1687 if (!hiddenFilesShown() && newName
.startsWith(QLatin1Char('.')) && !oldItem
.name().startsWith(QLatin1Char('.'))) {
1688 KGuiItem
yesGuiItem(KStandardGuiItem::yes());
1689 yesGuiItem
.setText(i18nc("@action:button", "Rename and Hide"));
1691 const auto code
= KMessageBox::questionYesNo(this,
1692 oldItem
.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1693 "Do you still want to rename it?")
1694 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1695 "Do you still want to rename it?"),
1696 oldItem
.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1698 KStandardGuiItem::cancel(),
1699 QStringLiteral("ConfirmHide")
1702 if (code
== KMessageBox::No
) {
1708 const bool newNameExistsAlready
= (m_model
->index(newUrl
) >= 0);
1709 if (!newNameExistsAlready
) {
1710 // Only change the data in the model if no item with the new name
1711 // is in the model yet. If there is an item with the new name
1712 // already, calling KIO::CopyJob will open a dialog
1713 // asking for a new name, and KFileItemModel will update the
1714 // data when the dir lister signals that the file name has changed.
1715 QHash
<QByteArray
, QVariant
> data
;
1716 data
.insert(role
, value
);
1717 m_model
->setData(index
, data
);
1720 KIO::Job
* job
= KIO::moveAs(oldUrl
, newUrl
);
1721 KJobWidgets::setWindow(job
, this);
1722 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename
, {oldUrl
}, newUrl
, job
);
1723 job
->uiDelegate()->setAutoErrorHandlingEnabled(true);
1725 forceUrlsSelection(newUrl
, {newUrl
});
1727 if (!newNameExistsAlready
) {
1728 // Only connect the result signal if there is no item with the new name
1729 // in the model yet, see bug 328262.
1730 connect(job
, &KJob::result
, this, &DolphinView::slotRenamingResult
);
1736 void DolphinView::loadDirectory(const QUrl
& url
, bool reload
)
1738 if (!url
.isValid()) {
1739 const QString
location(url
.toDisplayString(QUrl::PreferLocalFile
));
1740 if (location
.isEmpty()) {
1741 Q_EMIT
errorMessage(i18nc("@info:status", "The location is empty."));
1743 Q_EMIT
errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location
));
1749 m_model
->refreshDirectory(url
);
1751 m_model
->loadDirectory(url
);
1755 void DolphinView::applyViewProperties()
1757 const ViewProperties
props(viewPropertiesUrl());
1758 applyViewProperties(props
);
1761 void DolphinView::applyViewProperties(const ViewProperties
& props
)
1763 m_view
->beginTransaction();
1765 const Mode mode
= props
.viewMode();
1766 if (m_mode
!= mode
) {
1767 const Mode previousMode
= m_mode
;
1770 // Changing the mode might result in changing
1771 // the zoom level. Remember the old zoom level so
1772 // that zoomLevelChanged() can get emitted.
1773 const int oldZoomLevel
= m_view
->zoomLevel();
1776 Q_EMIT
modeChanged(m_mode
, previousMode
);
1778 if (m_view
->zoomLevel() != oldZoomLevel
) {
1779 Q_EMIT
zoomLevelChanged(m_view
->zoomLevel(), oldZoomLevel
);
1783 const bool hiddenFilesShown
= props
.hiddenFilesShown();
1784 if (hiddenFilesShown
!= m_model
->showHiddenFiles()) {
1785 m_model
->setShowHiddenFiles(hiddenFilesShown
);
1786 Q_EMIT
hiddenFilesShownChanged(hiddenFilesShown
);
1789 const bool groupedSorting
= props
.groupedSorting();
1790 if (groupedSorting
!= m_model
->groupedSorting()) {
1791 m_model
->setGroupedSorting(groupedSorting
);
1792 Q_EMIT
groupedSortingChanged(groupedSorting
);
1795 const QByteArray sortRole
= props
.sortRole();
1796 if (sortRole
!= m_model
->sortRole()) {
1797 m_model
->setSortRole(sortRole
);
1798 Q_EMIT
sortRoleChanged(sortRole
);
1801 const Qt::SortOrder sortOrder
= props
.sortOrder();
1802 if (sortOrder
!= m_model
->sortOrder()) {
1803 m_model
->setSortOrder(sortOrder
);
1804 Q_EMIT
sortOrderChanged(sortOrder
);
1807 const bool sortFoldersFirst
= props
.sortFoldersFirst();
1808 if (sortFoldersFirst
!= m_model
->sortDirectoriesFirst()) {
1809 m_model
->setSortDirectoriesFirst(sortFoldersFirst
);
1810 Q_EMIT
sortFoldersFirstChanged(sortFoldersFirst
);
1813 const QList
<QByteArray
> visibleRoles
= props
.visibleRoles();
1814 if (visibleRoles
!= m_visibleRoles
) {
1815 const QList
<QByteArray
> previousVisibleRoles
= m_visibleRoles
;
1816 m_visibleRoles
= visibleRoles
;
1817 m_view
->setVisibleRoles(visibleRoles
);
1818 Q_EMIT
visibleRolesChanged(m_visibleRoles
, previousVisibleRoles
);
1821 const bool previewsShown
= props
.previewsShown();
1822 if (previewsShown
!= m_view
->previewsShown()) {
1823 const int oldZoomLevel
= zoomLevel();
1825 m_view
->setPreviewsShown(previewsShown
);
1826 Q_EMIT
previewsShownChanged(previewsShown
);
1828 // Changing the preview-state might result in a changed zoom-level
1829 if (oldZoomLevel
!= zoomLevel()) {
1830 Q_EMIT
zoomLevelChanged(zoomLevel(), oldZoomLevel
);
1834 KItemListView
* itemListView
= m_container
->controller()->view();
1835 if (itemListView
->isHeaderVisible()) {
1836 KItemListHeader
* header
= itemListView
->header();
1837 const QList
<int> headerColumnWidths
= props
.headerColumnWidths();
1838 const int rolesCount
= m_visibleRoles
.count();
1839 if (headerColumnWidths
.count() == rolesCount
) {
1840 header
->setAutomaticColumnResizing(false);
1842 QHash
<QByteArray
, qreal
> columnWidths
;
1843 for (int i
= 0; i
< rolesCount
; ++i
) {
1844 columnWidths
.insert(m_visibleRoles
[i
], headerColumnWidths
[i
]);
1846 header
->setColumnWidths(columnWidths
);
1848 header
->setAutomaticColumnResizing(true);
1852 m_view
->endTransaction();
1855 void DolphinView::applyModeToView()
1858 case IconsView
: m_view
->setItemLayout(KFileItemListView::IconsLayout
); break;
1859 case CompactView
: m_view
->setItemLayout(KFileItemListView::CompactLayout
); break;
1860 case DetailsView
: m_view
->setItemLayout(KFileItemListView::DetailsLayout
); break;
1861 default: Q_ASSERT(false); break;
1865 void DolphinView::pasteToUrl(const QUrl
& url
)
1867 KIO::PasteJob
*job
= KIO::paste(QApplication::clipboard()->mimeData(), url
);
1868 KJobWidgets::setWindow(job
, this);
1869 m_clearSelectionBeforeSelectingNewItems
= true;
1870 m_markFirstNewlySelectedItemAsCurrent
= true;
1871 connect(job
, &KIO::PasteJob::itemCreated
, this, &DolphinView::slotItemCreated
);
1872 connect(job
, &KIO::PasteJob::result
, this, &DolphinView::slotJobResult
);
1875 QList
<QUrl
> DolphinView::simplifiedSelectedUrls() const
1879 const KFileItemList items
= selectedItems();
1880 urls
.reserve(items
.count());
1881 for (const KFileItem
& item
: items
) {
1882 urls
.append(item
.url());
1885 if (itemsExpandable()) {
1886 // TODO: Check if we still need KDirModel for this in KDE 5.0
1887 urls
= KDirModel::simplifiedUrlList(urls
);
1893 QMimeData
* DolphinView::selectionMimeData() const
1895 const KItemListSelectionManager
* selectionManager
= m_container
->controller()->selectionManager();
1896 const KItemSet selectedIndexes
= selectionManager
->selectedItems();
1898 return m_model
->createMimeData(selectedIndexes
);
1901 void DolphinView::updateWritableState()
1903 const bool wasFolderWritable
= m_isFolderWritable
;
1904 m_isFolderWritable
= false;
1906 KFileItem item
= m_model
->rootItem();
1907 if (item
.isNull()) {
1908 // Try to find out if the URL is writable even if the "root item" is
1909 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1910 item
= KFileItem(url());
1911 item
.setDelayedMimeTypes(true);
1914 KFileItemListProperties
capabilities(KFileItemList() << item
);
1915 m_isFolderWritable
= capabilities
.supportsWriting();
1917 if (m_isFolderWritable
!= wasFolderWritable
) {
1918 Q_EMIT
writeStateChanged(m_isFolderWritable
);
1922 QUrl
DolphinView::viewPropertiesUrl() const
1924 if (m_viewPropertiesContext
.isEmpty()) {
1929 url
.setScheme(m_url
.scheme());
1930 url
.setPath(m_viewPropertiesContext
);
1934 void DolphinView::slotRenameDialogRenamingFinished(const QList
<QUrl
>& urls
)
1936 forceUrlsSelection(urls
.first(), urls
);
1939 void DolphinView::forceUrlsSelection(const QUrl
& current
, const QList
<QUrl
>& selected
)
1942 m_clearSelectionBeforeSelectingNewItems
= true;
1943 markUrlAsCurrent(current
);
1944 markUrlsAsSelected(selected
);
1947 void DolphinView::copyPathToClipboard()
1949 const KFileItemList list
= selectedItems();
1950 if (list
.isEmpty()) {
1953 const KFileItem
& item
= list
.at(0);
1954 QString path
= item
.localPath();
1955 if (path
.isEmpty()) {
1956 path
= item
.url().toDisplayString();
1958 QClipboard
* clipboard
= QApplication::clipboard();
1959 if (clipboard
== nullptr) {
1962 clipboard
->setText(path
);
1965 void DolphinView::slotIncreaseZoom()
1967 setZoomLevel(zoomLevel() + 1);
1970 void DolphinView::slotDecreaseZoom()
1972 setZoomLevel(zoomLevel() - 1);
1975 void DolphinView::slotSwipeUp()
1977 Q_EMIT
goUpRequested();