]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
DolphinViewContainer: Delay changing the url
[dolphin.git] / src / views / dolphinview.cpp
1 /*
2 * SPDX-FileCopyrightText: 2006-2009 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2006 Gregor Kališnik <gregor@podnapisi.net>
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include "dolphinview.h"
9
10 #include "dolphin_detailsmodesettings.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphinitemlistview.h"
13 #include "dolphinnewfilemenuobserver.h"
14 #include "draganddrophelper.h"
15 #include "kitemviews/kfileitemlistview.h"
16 #include "kitemviews/kfileitemmodel.h"
17 #include "kitemviews/kitemlistcontainer.h"
18 #include "kitemviews/kitemlistcontroller.h"
19 #include "kitemviews/kitemlistheader.h"
20 #include "kitemviews/kitemlistselectionmanager.h"
21 #include "kitemviews/private/kitemlistroleeditor.h"
22 #include "selectionmode/singleclickselectionproxystyle.h"
23 #include "settings/viewmodes/viewmodesettings.h"
24 #include "versioncontrol/versioncontrolobserver.h"
25 #include "viewproperties.h"
26 #include "views/tooltips/tooltipmanager.h"
27 #include "zoomlevelinfo.h"
28
29 #if HAVE_BALOO
30 #include <Baloo/IndexerConfig>
31 #endif
32 #include <KColorScheme>
33 #include <KDesktopFile>
34 #include <KDirModel>
35 #include <KFileItemListProperties>
36 #include <KFormat>
37 #include <KIO/CopyJob>
38 #include <KIO/DeleteOrTrashJob>
39 #include <KIO/DropJob>
40 #include <KIO/JobUiDelegate>
41 #include <KIO/Paste>
42 #include <KIO/PasteJob>
43 #include <KIO/RenameFileDialog>
44 #include <KJobWidgets>
45 #include <KLocalizedString>
46 #include <KMessageBox>
47 #include <KProtocolManager>
48 #include <KUrlMimeData>
49
50 #include <kwidgetsaddons_version.h>
51
52 #include <QAbstractItemView>
53 #include <QActionGroup>
54 #include <QApplication>
55 #include <QClipboard>
56 #include <QDropEvent>
57 #include <QGraphicsOpacityEffect>
58 #include <QGraphicsSceneDragDropEvent>
59 #include <QLabel>
60 #include <QMenu>
61 #include <QMimeDatabase>
62 #include <QPixmapCache>
63 #include <QScrollBar>
64 #include <QSize>
65 #include <QTimer>
66 #include <QToolTip>
67 #include <QVBoxLayout>
68
69 DolphinView::DolphinView(const QUrl &url, QWidget *parent)
70 : QWidget(parent)
71 , m_active(true)
72 , m_tabsForFiles(false)
73 , m_assureVisibleCurrentIndex(false)
74 , m_isFolderWritable(true)
75 , m_dragging(false)
76 , m_selectNextItem(false)
77 , m_url(url)
78 , m_viewPropertiesContext()
79 , m_mode(DolphinView::IconsView)
80 , m_visibleRoles()
81 , m_topLayout(nullptr)
82 , m_model(nullptr)
83 , m_view(nullptr)
84 , m_container(nullptr)
85 , m_toolTipManager(nullptr)
86 , m_selectionChangedTimer(nullptr)
87 , m_currentItemUrl()
88 , m_scrollToCurrentItem(false)
89 , m_restoredContentsPosition()
90 , m_controlWheelAccumulatedDelta(0)
91 , m_selectedUrls()
92 , m_clearSelectionBeforeSelectingNewItems(false)
93 , m_markFirstNewlySelectedItemAsCurrent(false)
94 , m_versionControlObserver(nullptr)
95 , m_twoClicksRenamingTimer(nullptr)
96 , m_placeholderLabel(nullptr)
97 , m_showLoadingPlaceholderTimer(nullptr)
98 {
99 m_topLayout = new QVBoxLayout(this);
100 m_topLayout->setSpacing(0);
101 m_topLayout->setContentsMargins(0, 0, 0, 0);
102
103 // When a new item has been created by the "Create New..." menu, the item should
104 // get selected and it must be assured that the item will get visible. As the
105 // creation is done asynchronously, several signals must be checked:
106 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated, this, &DolphinView::observeCreatedItem);
107
108 m_selectionChangedTimer = new QTimer(this);
109 m_selectionChangedTimer->setSingleShot(true);
110 m_selectionChangedTimer->setInterval(300);
111 connect(m_selectionChangedTimer, &QTimer::timeout, this, &DolphinView::emitSelectionChangedSignal);
112
113 m_model = new KFileItemModel(this);
114 m_view = new DolphinItemListView();
115 m_view->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::FollowSetting);
116 m_view->setVisibleRoles({"text"});
117 applyModeToView();
118
119 KItemListController *controller = new KItemListController(m_model, m_view, this);
120 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
121 controller->setAutoActivationDelay(delay);
122 connect(controller, &KItemListController::doubleClickViewBackground, this, &DolphinView::doubleClickViewBackground);
123
124 // The EnlargeSmallPreviews setting can only be changed after the model
125 // has been set in the view by KItemListController.
126 m_view->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
127
128 m_container = new KItemListContainer(controller, this);
129 m_container->installEventFilter(this);
130 #ifndef QT_NO_ACCESSIBILITY
131 m_view->setAccessibleParentsObject(m_container);
132 #endif
133 setFocusProxy(m_container);
134 connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, [=] {
135 hideToolTip();
136 });
137 connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] {
138 hideToolTip();
139 });
140
141 m_showLoadingPlaceholderTimer = new QTimer(this);
142 m_showLoadingPlaceholderTimer->setInterval(500);
143 m_showLoadingPlaceholderTimer->setSingleShot(true);
144 connect(m_showLoadingPlaceholderTimer, &QTimer::timeout, this, &DolphinView::showLoadingPlaceholder);
145
146 // Show some placeholder text for empty folders
147 // This is made using a heavily-modified QLabel rather than a KTitleWidget
148 // because KTitleWidget can't be told to turn off mouse-selectable text
149 m_placeholderLabel = new QLabel(this);
150 // Don't consume mouse events
151 m_placeholderLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
152
153 QFont placeholderLabelFont;
154 // To match the size of a level 2 Heading/KTitleWidget
155 placeholderLabelFont.setPointSize(qRound(placeholderLabelFont.pointSize() * 1.3));
156 m_placeholderLabel->setFont(placeholderLabelFont);
157 m_placeholderLabel->setWordWrap(true);
158 m_placeholderLabel->setAlignment(Qt::AlignCenter);
159 // Match opacity of QML placeholder label component
160 auto *effect = new QGraphicsOpacityEffect(m_placeholderLabel);
161 effect->setOpacity(0.5);
162 m_placeholderLabel->setGraphicsEffect(effect);
163 // Set initial text and visibility
164 updatePlaceholderLabel();
165
166 auto *centeringLayout = new QVBoxLayout(m_container);
167 centeringLayout->addWidget(m_placeholderLabel);
168 centeringLayout->setAlignment(m_placeholderLabel, Qt::AlignCenter);
169
170 controller->setSelectionBehavior(KItemListController::MultiSelection);
171 connect(controller, &KItemListController::itemActivated, this, &DolphinView::slotItemActivated);
172 connect(controller, &KItemListController::itemsActivated, this, &DolphinView::slotItemsActivated);
173 connect(controller, &KItemListController::itemMiddleClicked, this, &DolphinView::slotItemMiddleClicked);
174 connect(controller, &KItemListController::itemContextMenuRequested, this, &DolphinView::slotItemContextMenuRequested);
175 connect(controller, &KItemListController::viewContextMenuRequested, this, &DolphinView::slotViewContextMenuRequested);
176 connect(controller, &KItemListController::headerContextMenuRequested, this, &DolphinView::slotHeaderContextMenuRequested);
177 connect(controller, &KItemListController::mouseButtonPressed, this, &DolphinView::slotMouseButtonPressed);
178 connect(controller, &KItemListController::itemHovered, this, &DolphinView::slotItemHovered);
179 connect(controller, &KItemListController::itemUnhovered, this, &DolphinView::slotItemUnhovered);
180 connect(controller, &KItemListController::itemDropEvent, this, &DolphinView::slotItemDropEvent);
181 connect(controller, &KItemListController::escapePressed, this, &DolphinView::stopLoading);
182 connect(controller, &KItemListController::modelChanged, this, &DolphinView::slotModelChanged);
183 connect(controller, &KItemListController::selectedItemTextPressed, this, &DolphinView::slotSelectedItemTextPressed);
184 connect(controller, &KItemListController::increaseZoom, this, &DolphinView::slotIncreaseZoom);
185 connect(controller, &KItemListController::decreaseZoom, this, &DolphinView::slotDecreaseZoom);
186 connect(controller, &KItemListController::swipeUp, this, &DolphinView::slotSwipeUp);
187 connect(controller, &KItemListController::selectionModeChangeRequested, this, &DolphinView::selectionModeChangeRequested);
188
189 connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted);
190 connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
191 connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::slotDirectoryLoadingCanceled);
192 connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress);
193 connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress);
194 connect(m_model, &KFileItemModel::itemsChanged, this, &DolphinView::slotItemsChanged);
195 connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged);
196 connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged);
197 connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage);
198 connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage);
199 connect(m_model, &KFileItemModel::directoryRedirection, this, &DolphinView::slotDirectoryRedirection);
200 connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError);
201 connect(m_model, &KFileItemModel::fileItemsChanged, this, &DolphinView::fileItemsChanged);
202 connect(m_model, &KFileItemModel::currentDirectoryRemoved, this, &DolphinView::currentDirectoryRemoved);
203
204 connect(this, &DolphinView::itemCountChanged, this, &DolphinView::updatePlaceholderLabel);
205
206 m_view->installEventFilter(this);
207 connect(m_view, &DolphinItemListView::sortOrderChanged, this, &DolphinView::slotSortOrderChangedByHeader);
208 connect(m_view, &DolphinItemListView::sortRoleChanged, this, &DolphinView::slotSortRoleChangedByHeader);
209 connect(m_view, &DolphinItemListView::visibleRolesChanged, this, &DolphinView::slotVisibleRolesChangedByHeader);
210 connect(m_view, &DolphinItemListView::roleEditingCanceled, this, &DolphinView::slotRoleEditingCanceled);
211
212 connect(m_view, &DolphinItemListView::columnHovered, this, [this](int columnIndex) {
213 m_hoveredColumnHeaderIndex = columnIndex;
214 });
215 connect(m_view, &DolphinItemListView::columnUnHovered, this, [this](int /* columnIndex */) {
216 m_hoveredColumnHeaderIndex = std::nullopt;
217 });
218 connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished, this, &DolphinView::slotHeaderColumnWidthChangeFinished);
219 connect(m_view->header(), &KItemListHeader::sidePaddingChanged, this, &DolphinView::slotSidePaddingWidthChanged);
220
221 KItemListSelectionManager *selectionManager = controller->selectionManager();
222 connect(selectionManager, &KItemListSelectionManager::selectionChanged, this, &DolphinView::slotSelectionChanged);
223
224 #if HAVE_BALOO
225 m_toolTipManager = new ToolTipManager(this);
226 connect(m_toolTipManager, &ToolTipManager::urlActivated, this, &DolphinView::urlActivated);
227 #endif
228
229 m_versionControlObserver = new VersionControlObserver(this);
230 m_versionControlObserver->setView(this);
231 m_versionControlObserver->setModel(m_model);
232 connect(m_versionControlObserver, &VersionControlObserver::infoMessage, this, &DolphinView::infoMessage);
233 connect(m_versionControlObserver, &VersionControlObserver::errorMessage, this, [this](const QString &message) {
234 Q_EMIT errorMessage(message, KIO::ERR_UNKNOWN);
235 });
236 connect(m_versionControlObserver, &VersionControlObserver::operationCompletedMessage, this, &DolphinView::operationCompletedMessage);
237
238 m_twoClicksRenamingTimer = new QTimer(this);
239 m_twoClicksRenamingTimer->setSingleShot(true);
240 connect(m_twoClicksRenamingTimer, &QTimer::timeout, this, &DolphinView::slotTwoClicksRenamingTimerTimeout);
241
242 applyViewProperties();
243 m_topLayout->addWidget(m_container);
244
245 loadDirectory(url);
246 }
247
248 DolphinView::~DolphinView()
249 {
250 disconnect(m_container->controller(), &KItemListController::modelChanged, this, &DolphinView::slotModelChanged);
251 }
252
253 QUrl DolphinView::url() const
254 {
255 return m_url;
256 }
257
258 void DolphinView::setActive(bool active)
259 {
260 if (active == m_active) {
261 return;
262 }
263
264 m_active = active;
265
266 updatePalette();
267
268 if (active) {
269 m_container->setFocus();
270 Q_EMIT activated();
271 }
272 }
273
274 bool DolphinView::isActive() const
275 {
276 return m_active;
277 }
278
279 void DolphinView::setViewMode(Mode mode)
280 {
281 if (mode != m_mode) {
282 // Reset scrollbars before changing the view mode.
283 m_container->horizontalScrollBar()->setValue(0);
284 m_container->verticalScrollBar()->setValue(0);
285
286 ViewProperties props(viewPropertiesUrl());
287 props.setViewMode(mode);
288
289 // We pass the new ViewProperties to applyViewProperties, rather than
290 // storing them on disk and letting applyViewProperties() read them
291 // from there, to prevent that changing the view mode fails if the
292 // .directory file is not writable (see bug 318534).
293 applyViewProperties(props);
294 }
295 }
296
297 DolphinView::Mode DolphinView::viewMode() const
298 {
299 return m_mode;
300 }
301
302 void DolphinView::setSelectionModeEnabled(const bool enabled)
303 {
304 if (enabled) {
305 if (!m_proxyStyle) {
306 m_proxyStyle = std::make_unique<SelectionMode::SingleClickSelectionProxyStyle>();
307 }
308 setStyle(m_proxyStyle.get());
309 m_view->setStyle(m_proxyStyle.get());
310 m_view->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::False);
311 } else {
312 setStyle(nullptr);
313 m_view->setStyle(nullptr);
314 m_view->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::FollowSetting);
315 }
316 m_container->controller()->setSelectionModeEnabled(enabled);
317 }
318
319 bool DolphinView::selectionMode() const
320 {
321 return m_container->controller()->selectionMode();
322 }
323
324 void DolphinView::setPreviewsShown(bool show)
325 {
326 if (previewsShown() == show) {
327 return;
328 }
329
330 ViewProperties props(viewPropertiesUrl());
331 props.setPreviewsShown(show);
332
333 const int oldZoomLevel = m_view->zoomLevel();
334 m_view->setPreviewsShown(show);
335 Q_EMIT previewsShownChanged(show);
336
337 const int newZoomLevel = m_view->zoomLevel();
338 if (newZoomLevel != oldZoomLevel) {
339 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
340 }
341 }
342
343 bool DolphinView::previewsShown() const
344 {
345 return m_view->previewsShown();
346 }
347
348 void DolphinView::setHiddenFilesShown(bool show)
349 {
350 if (m_model->showHiddenFiles() == show) {
351 return;
352 }
353
354 const KFileItemList itemList = selectedItems();
355 m_selectedUrls.clear();
356 m_selectedUrls = itemList.urlList();
357
358 ViewProperties props(viewPropertiesUrl());
359 props.setHiddenFilesShown(show);
360
361 m_model->setShowHiddenFiles(show);
362 Q_EMIT hiddenFilesShownChanged(show);
363 }
364
365 bool DolphinView::hiddenFilesShown() const
366 {
367 return m_model->showHiddenFiles();
368 }
369
370 void DolphinView::setGroupedSorting(bool grouped)
371 {
372 if (grouped == groupedSorting()) {
373 return;
374 }
375
376 ViewProperties props(viewPropertiesUrl());
377 props.setGroupedSorting(grouped);
378 props.save();
379
380 m_container->controller()->model()->setGroupedSorting(grouped);
381
382 Q_EMIT groupedSortingChanged(grouped);
383 }
384
385 bool DolphinView::groupedSorting() const
386 {
387 return m_model->groupedSorting();
388 }
389
390 KFileItemList DolphinView::items() const
391 {
392 KFileItemList list;
393 const int itemCount = m_model->count();
394 list.reserve(itemCount);
395
396 for (int i = 0; i < itemCount; ++i) {
397 list.append(m_model->fileItem(i));
398 }
399
400 return list;
401 }
402
403 int DolphinView::itemsCount() const
404 {
405 return m_model->count();
406 }
407
408 KFileItemList DolphinView::selectedItems() const
409 {
410 const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
411
412 KFileItemList selectedItems;
413 const auto items = selectionManager->selectedItems();
414 selectedItems.reserve(items.count());
415 for (int index : items) {
416 selectedItems.append(m_model->fileItem(index));
417 }
418 return selectedItems;
419 }
420
421 int DolphinView::selectedItemsCount() const
422 {
423 const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
424 return selectionManager->selectedItems().count();
425 }
426
427 void DolphinView::markUrlsAsSelected(const QList<QUrl> &urls)
428 {
429 m_selectedUrls = urls;
430 m_selectJobCreatedItems = false;
431 }
432
433 void DolphinView::markUrlAsCurrent(const QUrl &url)
434 {
435 m_currentItemUrl = url;
436 m_scrollToCurrentItem = true;
437 }
438
439 void DolphinView::selectItems(const QRegularExpression &regexp, bool enabled)
440 {
441 const KItemListSelectionManager::SelectionMode mode = enabled ? KItemListSelectionManager::Select : KItemListSelectionManager::Deselect;
442 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
443
444 for (int index = 0; index < m_model->count(); index++) {
445 const KFileItem item = m_model->fileItem(index);
446 if (regexp.match(item.text()).hasMatch()) {
447 // An alternative approach would be to store the matching items in a KItemSet and
448 // select them in one go after the loop, but we'd need a new function
449 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
450 // for that.
451 selectionManager->setSelected(index, 1, mode);
452 }
453 }
454 }
455
456 void DolphinView::setZoomLevel(int level)
457 {
458 const int oldZoomLevel = zoomLevel();
459 m_view->setZoomLevel(level);
460 if (zoomLevel() != oldZoomLevel) {
461 hideToolTip();
462 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
463 }
464 }
465
466 int DolphinView::zoomLevel() const
467 {
468 return m_view->zoomLevel();
469 }
470
471 void DolphinView::setSortRole(const QByteArray &role)
472 {
473 if (role != sortRole()) {
474 ViewProperties props(viewPropertiesUrl());
475 props.setSortRole(role);
476
477 KItemModelBase *model = m_container->controller()->model();
478 model->setSortRole(role);
479
480 Q_EMIT sortRoleChanged(role);
481 }
482 }
483
484 QByteArray DolphinView::sortRole() const
485 {
486 const KItemModelBase *model = m_container->controller()->model();
487 return model->sortRole();
488 }
489
490 void DolphinView::setSortOrder(Qt::SortOrder order)
491 {
492 if (sortOrder() != order) {
493 ViewProperties props(viewPropertiesUrl());
494 props.setSortOrder(order);
495
496 m_model->setSortOrder(order);
497
498 Q_EMIT sortOrderChanged(order);
499 }
500 }
501
502 Qt::SortOrder DolphinView::sortOrder() const
503 {
504 return m_model->sortOrder();
505 }
506
507 void DolphinView::setSortFoldersFirst(bool foldersFirst)
508 {
509 if (sortFoldersFirst() != foldersFirst) {
510 updateSortFoldersFirst(foldersFirst);
511 }
512 }
513
514 bool DolphinView::sortFoldersFirst() const
515 {
516 return m_model->sortDirectoriesFirst();
517 }
518
519 void DolphinView::setSortHiddenLast(bool hiddenLast)
520 {
521 if (sortHiddenLast() != hiddenLast) {
522 updateSortHiddenLast(hiddenLast);
523 }
524 }
525
526 bool DolphinView::sortHiddenLast() const
527 {
528 return m_model->sortHiddenLast();
529 }
530
531 void DolphinView::setVisibleRoles(const QList<QByteArray> &roles)
532 {
533 const QList<QByteArray> previousRoles = roles;
534
535 ViewProperties props(viewPropertiesUrl());
536 props.setVisibleRoles(roles);
537
538 m_visibleRoles = roles;
539 m_view->setVisibleRoles(roles);
540
541 Q_EMIT visibleRolesChanged(m_visibleRoles, previousRoles);
542 }
543
544 QList<QByteArray> DolphinView::visibleRoles() const
545 {
546 return m_visibleRoles;
547 }
548
549 void DolphinView::reload()
550 {
551 QByteArray viewState;
552 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
553 saveState(saveStream);
554
555 setUrl(url());
556 loadDirectory(url(), true);
557
558 QDataStream restoreStream(viewState);
559 restoreState(restoreStream);
560 }
561
562 void DolphinView::readSettings()
563 {
564 const int oldZoomLevel = m_view->zoomLevel();
565
566 GeneralSettings::self()->load();
567 m_view->readSettings();
568 applyViewProperties();
569
570 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
571 m_container->controller()->setAutoActivationDelay(delay);
572
573 const int newZoomLevel = m_view->zoomLevel();
574 if (newZoomLevel != oldZoomLevel) {
575 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
576 }
577 }
578
579 void DolphinView::writeSettings()
580 {
581 GeneralSettings::self()->save();
582 m_view->writeSettings();
583 }
584
585 void DolphinView::setNameFilter(const QString &nameFilter)
586 {
587 m_model->setNameFilter(nameFilter);
588 }
589
590 QString DolphinView::nameFilter() const
591 {
592 return m_model->nameFilter();
593 }
594
595 void DolphinView::setMimeTypeFilters(const QStringList &filters)
596 {
597 return m_model->setMimeTypeFilters(filters);
598 }
599
600 QStringList DolphinView::mimeTypeFilters() const
601 {
602 return m_model->mimeTypeFilters();
603 }
604
605 void DolphinView::requestStatusBarText()
606 {
607 if (m_statJobForStatusBarText) {
608 // Kill the pending request.
609 m_statJobForStatusBarText->kill();
610 }
611
612 if (m_container->controller()->selectionManager()->hasSelection()) {
613 int folderCount = 0;
614 int fileCount = 0;
615 KIO::filesize_t totalFileSize = 0;
616
617 // Give a summary of the status of the selected files
618 const KFileItemList list = selectedItems();
619 for (const KFileItem &item : list) {
620 if (item.isDir()) {
621 ++folderCount;
622 } else {
623 ++fileCount;
624 totalFileSize += item.size();
625 }
626 }
627
628 if (folderCount + fileCount == 1) {
629 // If only one item is selected, show info about it
630 Q_EMIT statusBarTextChanged(list.first().getStatusBarInfo());
631 } else {
632 // At least 2 items are selected
633 emitStatusBarText(folderCount, fileCount, totalFileSize, HasSelection);
634 }
635 } else { // has no selection
636 if (!m_model->rootItem().url().isValid()) {
637 return;
638 }
639
640 m_statJobForStatusBarText = KIO::stat(m_model->rootItem().url(), KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
641 connect(m_statJobForStatusBarText, &KJob::result, this, &DolphinView::slotStatJobResult);
642 m_statJobForStatusBarText->start();
643 }
644 }
645
646 void DolphinView::emitStatusBarText(const int folderCount, const int fileCount, KIO::filesize_t totalFileSize, const Selection selection)
647 {
648 QString foldersText;
649 QString filesText;
650 QString summary;
651
652 if (selection == HasSelection) {
653 // At least 2 items are selected because the case of 1 selected item is handled in
654 // DolphinView::requestStatusBarText().
655 foldersText = i18ncp("@info:status", "1 folder selected", "%1 folders selected", folderCount);
656 filesText = i18ncp("@info:status", "1 file selected", "%1 files selected", fileCount);
657 } else {
658 foldersText = i18ncp("@info:status", "1 folder", "%1 folders", folderCount);
659 filesText = i18ncp("@info:status", "1 file", "%1 files", fileCount);
660 }
661
662 if (fileCount > 0 && folderCount > 0) {
663 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)", foldersText, filesText, KFormat().formatByteSize(totalFileSize));
664 } else if (fileCount > 0) {
665 summary = i18nc("@info:status files (size)", "%1 (%2)", filesText, KFormat().formatByteSize(totalFileSize));
666 } else if (folderCount > 0) {
667 summary = foldersText;
668 } else {
669 summary = i18nc("@info:status", "0 folders, 0 files");
670 }
671 Q_EMIT statusBarTextChanged(summary);
672 }
673
674 QList<QAction *> DolphinView::versionControlActions(const KFileItemList &items) const
675 {
676 QList<QAction *> actions;
677
678 if (items.isEmpty()) {
679 const KFileItem item = m_model->rootItem();
680 if (!item.isNull()) {
681 actions = m_versionControlObserver->actions(KFileItemList() << item);
682 }
683 } else {
684 actions = m_versionControlObserver->actions(items);
685 }
686
687 return actions;
688 }
689
690 void DolphinView::setUrl(const QUrl &url)
691 {
692 if (url == m_url) {
693 return;
694 }
695
696 clearSelection();
697
698 m_url = url;
699
700 hideToolTip();
701
702 disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
703
704 // It is important to clear the items from the model before
705 // applying the view properties, otherwise expensive operations
706 // might be done on the existing items although they get cleared
707 // anyhow afterwards by loadDirectory().
708 m_model->clear();
709 applyViewProperties();
710 loadDirectory(url);
711
712 Q_EMIT urlChanged(url);
713 }
714
715 void DolphinView::selectAll()
716 {
717 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
718 selectionManager->setSelected(0, m_model->count());
719 }
720
721 void DolphinView::invertSelection()
722 {
723 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
724 selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
725 }
726
727 void DolphinView::clearSelection()
728 {
729 m_selectJobCreatedItems = false;
730 m_selectedUrls.clear();
731 m_container->controller()->selectionManager()->clearSelection();
732 }
733
734 void DolphinView::renameSelectedItems()
735 {
736 const KFileItemList items = selectedItems();
737 if (items.isEmpty()) {
738 return;
739 }
740
741 if (items.count() == 1 && GeneralSettings::renameInline()) {
742 const int index = m_model->index(items.first());
743
744 connect(
745 m_view,
746 &KItemListView::scrollingStopped,
747 this,
748 [this, index]() {
749 m_view->editRole(index, "text");
750
751 hideToolTip();
752
753 connect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
754 },
755 Qt::SingleShotConnection);
756 m_view->scrollToItem(index);
757
758 } else {
759 KIO::RenameFileDialog *dialog = new KIO::RenameFileDialog(items, this);
760 connect(dialog, &KIO::RenameFileDialog::renamingFinished, this, &DolphinView::slotRenameDialogRenamingFinished);
761
762 dialog->open();
763 }
764
765 // Assure that the current index remains visible when KFileItemModel
766 // will notify the view about changed items (which might result in
767 // a changed sorting).
768 m_assureVisibleCurrentIndex = true;
769 }
770
771 void DolphinView::trashSelectedItems()
772 {
773 const QList<QUrl> list = simplifiedSelectedUrls();
774
775 using Iface = KIO::AskUserActionInterface;
776 auto *trashJob = new KIO::DeleteOrTrashJob(list, Iface::Trash, Iface::DefaultConfirmation, this);
777 connect(trashJob, &KJob::result, this, &DolphinView::slotTrashFileFinished);
778 m_selectNextItem = true;
779 trashJob->start();
780 }
781
782 void DolphinView::deleteSelectedItems()
783 {
784 const QList<QUrl> list = simplifiedSelectedUrls();
785
786 using Iface = KIO::AskUserActionInterface;
787 auto *trashJob = new KIO::DeleteOrTrashJob(list, Iface::Delete, Iface::DefaultConfirmation, this);
788 connect(trashJob, &KJob::result, this, &DolphinView::slotTrashFileFinished);
789 m_selectNextItem = true;
790 trashJob->start();
791 }
792
793 void DolphinView::cutSelectedItemsToClipboard()
794 {
795 QMimeData *mimeData = selectionMimeData();
796 KIO::setClipboardDataCut(mimeData, true);
797 KUrlMimeData::exportUrlsToPortal(mimeData);
798 QApplication::clipboard()->setMimeData(mimeData);
799 }
800
801 void DolphinView::copySelectedItemsToClipboard()
802 {
803 QMimeData *mimeData = selectionMimeData();
804 KUrlMimeData::exportUrlsToPortal(mimeData);
805 QApplication::clipboard()->setMimeData(mimeData);
806 }
807
808 void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
809 {
810 if (selection.isEmpty() || !destinationUrl.isValid()) {
811 return;
812 }
813
814 m_clearSelectionBeforeSelectingNewItems = true;
815 m_markFirstNewlySelectedItemAsCurrent = true;
816 m_selectJobCreatedItems = true;
817
818 KIO::CopyJob *job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
819 KJobWidgets::setWindow(job, this);
820
821 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
822 connect(job, &KIO::CopyJob::copying, this, &DolphinView::slotItemCreatedFromJob);
823 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotItemCreatedFromJob);
824 KIO::FileUndoManager::self()->recordCopyJob(job);
825 }
826
827 void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
828 {
829 if (selection.isEmpty() || !destinationUrl.isValid()) {
830 return;
831 }
832
833 m_clearSelectionBeforeSelectingNewItems = true;
834 m_markFirstNewlySelectedItemAsCurrent = true;
835 m_selectJobCreatedItems = true;
836
837 KIO::CopyJob *job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
838 KJobWidgets::setWindow(job, this);
839
840 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
841 connect(job, &KIO::CopyJob::moving, this, &DolphinView::slotItemCreatedFromJob);
842 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotItemCreatedFromJob);
843 KIO::FileUndoManager::self()->recordCopyJob(job);
844 }
845
846 void DolphinView::paste()
847 {
848 pasteToUrl(url());
849 }
850
851 void DolphinView::pasteIntoFolder()
852 {
853 const KFileItemList items = selectedItems();
854 if ((items.count() == 1) && items.first().isDir()) {
855 pasteToUrl(items.first().url());
856 }
857 }
858
859 void DolphinView::duplicateSelectedItems()
860 {
861 const KFileItemList itemList = selectedItems();
862 if (itemList.isEmpty()) {
863 return;
864 }
865
866 const QMimeDatabase db;
867
868 m_clearSelectionBeforeSelectingNewItems = true;
869 m_markFirstNewlySelectedItemAsCurrent = true;
870 m_selectJobCreatedItems = true;
871
872 // Duplicate all selected items and append "copy" to the end of the file name
873 // but before the filename extension, if present
874 for (const auto &item : itemList) {
875 const QUrl originalURL = item.url();
876 const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
877 const QString originalFileName = item.name();
878
879 QString extension = db.suffixForFileName(originalFileName);
880
881 QUrl duplicateURL = originalURL;
882
883 // No extension; new filename is "<oldfilename> copy"
884 if (extension.isEmpty()) {
885 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFileName));
886 // There's an extension; new filename is "<oldfilename> copy.<extension>"
887 } else {
888 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
889 extension = QLatin1String(".") + extension;
890 const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size());
891 // Preserve file's original filename extension in case the casing differs
892 // from what QMimeDatabase::suffixForFileName() returned
893 const QString originalExtension = originalFileName.right(extension.size());
894 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension);
895 }
896
897 KIO::CopyJob *job = KIO::copyAs(originalURL, duplicateURL);
898 job->setAutoRename(true);
899 KJobWidgets::setWindow(job, this);
900
901 connect(job, &KIO::CopyJob::result, this, &DolphinView::slotJobResult);
902 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotItemCreatedFromJob);
903 connect(job, &KIO::CopyJob::copyingLinkDone, this, &DolphinView::slotItemLinkCreatedFromJob);
904 KIO::FileUndoManager::self()->recordCopyJob(job);
905 }
906 }
907
908 void DolphinView::stopLoading()
909 {
910 m_model->cancelDirectoryLoading();
911 }
912
913 void DolphinView::updatePalette()
914 {
915 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
916 if (!m_active) {
917 color.setAlpha(150);
918 }
919
920 QWidget *viewport = m_container->viewport();
921 if (viewport) {
922 QPalette palette;
923 palette.setColor(viewport->backgroundRole(), color);
924 viewport->setPalette(palette);
925 }
926
927 update();
928 }
929
930 void DolphinView::abortTwoClicksRenaming()
931 {
932 m_twoClicksRenamingItemUrl.clear();
933 m_twoClicksRenamingTimer->stop();
934 }
935
936 bool DolphinView::eventFilter(QObject *watched, QEvent *event)
937 {
938 switch (event->type()) {
939 case QEvent::PaletteChange:
940 updatePalette();
941 QPixmapCache::clear();
942 break;
943
944 case QEvent::WindowActivate:
945 case QEvent::WindowDeactivate:
946 updatePalette();
947 break;
948
949 case QEvent::KeyPress:
950 hideToolTip(ToolTipManager::HideBehavior::Instantly);
951 if (GeneralSettings::useTabForSwitchingSplitView()) {
952 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
953 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
954 Q_EMIT toggleActiveViewRequested();
955 return true;
956 }
957 }
958 break;
959 case QEvent::KeyRelease:
960 if (static_cast<QKeyEvent *>(event)->key() == Qt::Key_Control) {
961 m_controlWheelAccumulatedDelta = 0;
962 }
963 break;
964 case QEvent::FocusIn:
965 if (watched == m_container) {
966 setActive(true);
967 }
968 break;
969
970 case QEvent::GraphicsSceneDragEnter:
971 if (watched == m_view) {
972 m_dragging = true;
973 abortTwoClicksRenaming();
974 }
975 break;
976
977 case QEvent::GraphicsSceneDragLeave:
978 if (watched == m_view) {
979 m_dragging = false;
980 }
981 break;
982
983 case QEvent::GraphicsSceneDrop:
984 if (watched == m_view) {
985 m_dragging = false;
986 }
987 break;
988
989 case QEvent::ToolTip: {
990 const auto helpEvent = static_cast<QHelpEvent *>(event);
991 if (tryShowNameToolTip(helpEvent)) {
992 return true;
993
994 } else if (m_hoveredColumnHeaderIndex) {
995 const auto rolesInfo = KFileItemModel::rolesInformation();
996 const auto visibleRole = m_visibleRoles.value(*m_hoveredColumnHeaderIndex);
997
998 for (const KFileItemModel::RoleInfo &info : rolesInfo) {
999 if (visibleRole == info.role) {
1000 QToolTip::showText(helpEvent->globalPos(), info.tooltip, this);
1001 return true;
1002 }
1003 }
1004 }
1005 break;
1006 }
1007 default:
1008 break;
1009 }
1010
1011 return QWidget::eventFilter(watched, event);
1012 }
1013
1014 void DolphinView::wheelEvent(QWheelEvent *event)
1015 {
1016 if (event->modifiers().testFlag(Qt::ControlModifier)) {
1017 m_controlWheelAccumulatedDelta += event->angleDelta().y();
1018
1019 if (m_controlWheelAccumulatedDelta <= -QWheelEvent::DefaultDeltasPerStep) {
1020 slotDecreaseZoom();
1021 m_controlWheelAccumulatedDelta += QWheelEvent::DefaultDeltasPerStep;
1022 } else if (m_controlWheelAccumulatedDelta >= QWheelEvent::DefaultDeltasPerStep) {
1023 slotIncreaseZoom();
1024 m_controlWheelAccumulatedDelta -= QWheelEvent::DefaultDeltasPerStep;
1025 }
1026
1027 event->accept();
1028 } else {
1029 event->ignore();
1030 }
1031 }
1032
1033 void DolphinView::hideEvent(QHideEvent *event)
1034 {
1035 hideToolTip();
1036 QWidget::hideEvent(event);
1037 }
1038
1039 bool DolphinView::event(QEvent *event)
1040 {
1041 if (event->type() == QEvent::WindowDeactivate) {
1042 /* See Bug 297355
1043 * Dolphin leaves file preview tooltips open even when is not visible.
1044 *
1045 * Hide tool-tip when Dolphin loses focus.
1046 */
1047 hideToolTip();
1048 abortTwoClicksRenaming();
1049 }
1050
1051 return QWidget::event(event);
1052 }
1053
1054 void DolphinView::activate()
1055 {
1056 setActive(true);
1057 }
1058
1059 void DolphinView::slotItemActivated(int index)
1060 {
1061 abortTwoClicksRenaming();
1062
1063 const KFileItem item = m_model->fileItem(index);
1064 if (!item.isNull()) {
1065 Q_EMIT itemActivated(item);
1066 }
1067 }
1068
1069 void DolphinView::slotItemsActivated(const KItemSet &indexes)
1070 {
1071 Q_ASSERT(indexes.count() >= 2);
1072
1073 abortTwoClicksRenaming();
1074
1075 const auto modifiers = QGuiApplication::keyboardModifiers();
1076
1077 if (indexes.count() > 5) {
1078 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
1079 const int answer = KMessageBox::warningContinueCancel(
1080 this,
1081 question,
1082 {},
1083 KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes.count()), QStringLiteral("document-open")),
1084 KStandardGuiItem::cancel(),
1085 QStringLiteral("ConfirmOpenManyFolders"));
1086 if (answer != KMessageBox::PrimaryAction && answer != KMessageBox::Continue) {
1087 return;
1088 }
1089 }
1090
1091 KFileItemList items;
1092 items.reserve(indexes.count());
1093
1094 for (int index : indexes) {
1095 KFileItem item = m_model->fileItem(index);
1096 const QUrl &url = openItemAsFolderUrl(item);
1097
1098 if (!url.isEmpty()) {
1099 // Open folders in new tabs or in new windows depending on the modifier
1100 // The ctrl+shift behavior is ignored because we are handling multiple items
1101 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1102 if (modifiers & Qt::ShiftModifier && !(modifiers & Qt::ControlModifier)) {
1103 Q_EMIT windowRequested(url);
1104 } else {
1105 Q_EMIT tabRequested(url);
1106 }
1107 } else {
1108 items.append(item);
1109 }
1110 }
1111
1112 if (items.count() == 1) {
1113 Q_EMIT itemActivated(items.first());
1114 } else if (items.count() > 1) {
1115 Q_EMIT itemsActivated(items);
1116 }
1117 }
1118
1119 void DolphinView::slotItemMiddleClicked(int index)
1120 {
1121 const KFileItem &item = m_model->fileItem(index);
1122 const QUrl &url = openItemAsFolderUrl(item, GeneralSettings::browseThroughArchives());
1123 const auto modifiers = QGuiApplication::keyboardModifiers();
1124 if (!url.isEmpty()) {
1125 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1126 if (modifiers & Qt::ShiftModifier) {
1127 Q_EMIT activeTabRequested(url);
1128 } else {
1129 Q_EMIT tabRequested(url);
1130 }
1131 } else if (isTabsForFilesEnabled()) {
1132 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1133 if (modifiers & Qt::ShiftModifier) {
1134 Q_EMIT activeTabRequested(item.url());
1135 } else {
1136 Q_EMIT tabRequested(item.url());
1137 }
1138 } else {
1139 Q_EMIT fileMiddleClickActivated(item);
1140 }
1141 }
1142
1143 void DolphinView::slotItemContextMenuRequested(int index, const QPointF &pos)
1144 {
1145 // Force emit of a selection changed signal before we request the
1146 // context menu, to update the edit-actions first. (See Bug 294013)
1147 if (m_selectionChangedTimer->isActive()) {
1148 emitSelectionChangedSignal();
1149 }
1150
1151 const KFileItem item = m_model->fileItem(index);
1152 Q_EMIT requestContextMenu(pos.toPoint(), item, selectedItems(), url());
1153 }
1154
1155 void DolphinView::slotViewContextMenuRequested(const QPointF &pos)
1156 {
1157 Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), selectedItems(), url());
1158 }
1159
1160 void DolphinView::slotHeaderContextMenuRequested(const QPointF &pos)
1161 {
1162 ViewProperties props(viewPropertiesUrl());
1163
1164 QPointer<QMenu> menu = new QMenu(this);
1165
1166 KItemListView *view = m_container->controller()->view();
1167 const QList<QByteArray> visibleRolesSet = view->visibleRoles();
1168
1169 bool indexingEnabled = false;
1170 #if HAVE_BALOO
1171 Baloo::IndexerConfig config;
1172 indexingEnabled = config.fileIndexingEnabled();
1173 #endif
1174
1175 QString groupName;
1176 QMenu *groupMenu = nullptr;
1177
1178 // Add all roles to the menu that can be shown or hidden by the user
1179 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
1180 for (const KFileItemModel::RoleInfo &info : rolesInfo) {
1181 if (info.role == "text") {
1182 // It should not be possible to hide the "text" role
1183 continue;
1184 }
1185
1186 const QString text = m_model->roleDescription(info.role);
1187 QAction *action = nullptr;
1188 if (info.group.isEmpty()) {
1189 action = menu->addAction(text);
1190 } else {
1191 if (!groupMenu || info.group != groupName) {
1192 groupName = info.group;
1193 groupMenu = menu->addMenu(groupName);
1194 }
1195
1196 action = groupMenu->addAction(text);
1197 }
1198
1199 action->setCheckable(true);
1200 action->setChecked(visibleRolesSet.contains(info.role));
1201 action->setData(info.role);
1202 action->setToolTip(info.tooltip);
1203
1204 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled);
1205 action->setEnabled(enable);
1206 }
1207
1208 menu->addSeparator();
1209
1210 QActionGroup *widthsGroup = new QActionGroup(menu);
1211 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
1212
1213 QAction *toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding"));
1214 toggleSidePaddingAction->setCheckable(true);
1215 toggleSidePaddingAction->setChecked(view->header()->sidePadding() > 0);
1216
1217 QAction *autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1218 autoAdjustWidthsAction->setCheckable(true);
1219 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1220 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1221
1222 QAction *customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1223 customWidthsAction->setCheckable(true);
1224 customWidthsAction->setChecked(!autoColumnWidths);
1225 customWidthsAction->setActionGroup(widthsGroup);
1226
1227 QAction *action = menu->exec(pos.toPoint());
1228 if (menu && action) {
1229 KItemListHeader *header = view->header();
1230
1231 if (action == autoAdjustWidthsAction) {
1232 // Clear the column-widths from the viewproperties and turn on
1233 // the automatic resizing of the columns
1234 props.setHeaderColumnWidths(QList<int>());
1235 header->setAutomaticColumnResizing(true);
1236 } else if (action == customWidthsAction) {
1237 // Apply the current column-widths as custom column-widths and turn
1238 // off the automatic resizing of the columns
1239 QList<int> columnWidths;
1240 const auto visibleRoles = view->visibleRoles();
1241 columnWidths.reserve(visibleRoles.count());
1242 for (const QByteArray &role : visibleRoles) {
1243 columnWidths.append(header->columnWidth(role));
1244 }
1245 props.setHeaderColumnWidths(columnWidths);
1246 header->setAutomaticColumnResizing(false);
1247 } else if (action == toggleSidePaddingAction) {
1248 header->setSidePadding(toggleSidePaddingAction->isChecked() ? 20 : 0);
1249 } else {
1250 // Show or hide the selected role
1251 const QByteArray selectedRole = action->data().toByteArray();
1252
1253 QList<QByteArray> visibleRoles = view->visibleRoles();
1254 if (action->isChecked()) {
1255 visibleRoles.append(selectedRole);
1256 } else {
1257 visibleRoles.removeOne(selectedRole);
1258 }
1259
1260 view->setVisibleRoles(visibleRoles);
1261 props.setVisibleRoles(visibleRoles);
1262
1263 QList<int> columnWidths;
1264 if (!header->automaticColumnResizing()) {
1265 const auto visibleRoles = view->visibleRoles();
1266 columnWidths.reserve(visibleRoles.count());
1267 for (const QByteArray &role : visibleRoles) {
1268 columnWidths.append(header->columnWidth(role));
1269 }
1270 }
1271 props.setHeaderColumnWidths(columnWidths);
1272 }
1273 }
1274
1275 delete menu;
1276 }
1277
1278 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray &role, qreal current)
1279 {
1280 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1281
1282 ViewProperties props(viewPropertiesUrl());
1283 QList<int> columnWidths = props.headerColumnWidths();
1284 if (columnWidths.count() != visibleRoles.count()) {
1285 columnWidths.clear();
1286 columnWidths.reserve(visibleRoles.count());
1287 const KItemListHeader *header = m_view->header();
1288 for (const QByteArray &role : visibleRoles) {
1289 const int width = header->columnWidth(role);
1290 columnWidths.append(width);
1291 }
1292 }
1293
1294 const int roleIndex = visibleRoles.indexOf(role);
1295 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1296 columnWidths[roleIndex] = current;
1297
1298 props.setHeaderColumnWidths(columnWidths);
1299 }
1300
1301 void DolphinView::slotSidePaddingWidthChanged(qreal width)
1302 {
1303 ViewProperties props(viewPropertiesUrl());
1304 DetailsModeSettings::setSidePadding(int(width));
1305 m_view->writeSettings();
1306 }
1307
1308 void DolphinView::slotItemHovered(int index)
1309 {
1310 const KFileItem item = m_model->fileItem(index);
1311
1312 if (GeneralSettings::showToolTips() && !m_dragging) {
1313 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1314 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1315 itemRect.moveTo(pos);
1316
1317 #if HAVE_BALOO
1318 auto nativeParent = nativeParentWidget();
1319 if (nativeParent) {
1320 m_toolTipManager->showToolTip(item, itemRect, nativeParent->windowHandle());
1321 }
1322 #endif
1323 }
1324
1325 Q_EMIT requestItemInfo(item);
1326 }
1327
1328 void DolphinView::slotItemUnhovered(int index)
1329 {
1330 Q_UNUSED(index)
1331 hideToolTip();
1332 Q_EMIT requestItemInfo(KFileItem());
1333 }
1334
1335 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent *event)
1336 {
1337 QUrl destUrl;
1338 KFileItem destItem = m_model->fileItem(index);
1339 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1340 // Use the URL of the view as drop target if the item is no directory
1341 // or desktop-file
1342 destItem = m_model->rootItem();
1343 destUrl = url();
1344 } else {
1345 // The item represents a directory or desktop-file
1346 destUrl = destItem.mostLocalUrl();
1347 }
1348
1349 QDropEvent dropEvent(event->pos().toPoint(), event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
1350 dropUrls(destUrl, &dropEvent, this);
1351
1352 setActive(true);
1353 }
1354
1355 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1356 {
1357 KIO::DropJob *job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1358
1359 if (job) {
1360 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1361
1362 if (destUrl == url()) {
1363 // Mark the dropped urls as selected.
1364 m_clearSelectionBeforeSelectingNewItems = true;
1365 m_markFirstNewlySelectedItemAsCurrent = true;
1366 m_selectJobCreatedItems = true;
1367 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1368 connect(job, &KIO::DropJob::copyJobStarted, this, [this](const KIO::CopyJob *copyJob) {
1369 connect(copyJob, &KIO::CopyJob::copying, this, &DolphinView::slotItemCreatedFromJob);
1370 connect(copyJob, &KIO::CopyJob::moving, this, &DolphinView::slotItemCreatedFromJob);
1371 connect(copyJob, &KIO::CopyJob::linking, this, [this](KIO::Job *job, const QString &src, const QUrl &dest) {
1372 Q_UNUSED(job)
1373 Q_UNUSED(src)
1374 slotItemCreated(dest);
1375 });
1376 });
1377 }
1378 }
1379 }
1380
1381 void DolphinView::slotModelChanged(KItemModelBase *current, KItemModelBase *previous)
1382 {
1383 if (previous != nullptr) {
1384 Q_ASSERT(qobject_cast<KFileItemModel *>(previous));
1385 KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(previous);
1386 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1387 m_versionControlObserver->setModel(nullptr);
1388 }
1389
1390 if (current) {
1391 Q_ASSERT(qobject_cast<KFileItemModel *>(current));
1392 KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(current);
1393 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1394 m_versionControlObserver->setModel(fileItemModel);
1395 }
1396 }
1397
1398 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1399 {
1400 Q_UNUSED(itemIndex)
1401
1402 hideToolTip();
1403
1404 if (buttons & Qt::BackButton) {
1405 Q_EMIT goBackRequested();
1406 } else if (buttons & Qt::ForwardButton) {
1407 Q_EMIT goForwardRequested();
1408 }
1409 }
1410
1411 void DolphinView::slotSelectedItemTextPressed(int index)
1412 {
1413 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1414 const KFileItem item = m_model->fileItem(index);
1415 const KFileItemListProperties capabilities(KFileItemList() << item);
1416 if (capabilities.supportsMoving()) {
1417 m_twoClicksRenamingItemUrl = item.url();
1418 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1419 }
1420 }
1421 }
1422
1423 void DolphinView::slotItemCreatedFromJob(KIO::Job *, const QUrl &, const QUrl &to)
1424 {
1425 slotItemCreated(to);
1426 }
1427
1428 void DolphinView::slotItemLinkCreatedFromJob(KIO::Job *, const QUrl &, const QString &, const QUrl &to)
1429 {
1430 slotItemCreated(to);
1431 }
1432
1433 void DolphinView::slotItemCreated(const QUrl &url)
1434 {
1435 if (m_markFirstNewlySelectedItemAsCurrent) {
1436 markUrlAsCurrent(url);
1437 m_markFirstNewlySelectedItemAsCurrent = false;
1438 }
1439 if (m_selectJobCreatedItems && !m_selectedUrls.contains(url)) {
1440 m_selectedUrls << url;
1441 }
1442 }
1443
1444 void DolphinView::onDirectoryLoadingCompletedAfterJob()
1445 {
1446 // the model should now contain all the items created by the job
1447 m_selectJobCreatedItems = true; // to make sure we overwrite selection
1448 // update the view: scroll into View and selection
1449 updateViewState();
1450 m_selectJobCreatedItems = false;
1451 m_selectedUrls.clear();
1452 }
1453
1454 void DolphinView::slotJobResult(KJob *job)
1455 {
1456 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
1457 Q_EMIT errorMessage(job->errorString(), job->error());
1458 }
1459 if (!m_selectJobCreatedItems) {
1460 m_selectedUrls.clear();
1461 return;
1462 }
1463 if (!m_selectedUrls.isEmpty()) {
1464 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1465
1466 updateSelectionState();
1467 if (!m_selectedUrls.isEmpty()) {
1468 // not all urls were found, the model may not be up to date
1469 connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::onDirectoryLoadingCompletedAfterJob, Qt::SingleShotConnection);
1470 } else {
1471 m_selectJobCreatedItems = false;
1472 m_selectedUrls.clear();
1473 }
1474 }
1475 }
1476
1477 void DolphinView::slotSelectionChanged(const KItemSet &current, const KItemSet &previous)
1478 {
1479 m_selectNextItem = false;
1480 const int currentCount = current.count();
1481 const int previousCount = previous.count();
1482 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || (currentCount > 0 && previousCount == 0);
1483
1484 // If nothing has been selected before and something got selected (or if something
1485 // was selected before and now nothing is selected) the selectionChangedSignal must
1486 // be emitted asynchronously as fast as possible to update the edit-actions.
1487 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1488 m_selectionChangedTimer->start();
1489 }
1490
1491 void DolphinView::emitSelectionChangedSignal()
1492 {
1493 m_selectionChangedTimer->stop();
1494 Q_EMIT selectionChanged(selectedItems());
1495 }
1496
1497 void DolphinView::slotStatJobResult(KJob *job)
1498 {
1499 int folderCount = 0;
1500 int fileCount = 0;
1501 KIO::filesize_t totalFileSize = 0;
1502 bool countFileSize = true;
1503
1504 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1505 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1506 // We have a precomputed value.
1507 totalFileSize = static_cast<KIO::filesize_t>(entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1508 countFileSize = false;
1509 }
1510
1511 const int itemCount = m_model->count();
1512 for (int i = 0; i < itemCount; ++i) {
1513 const KFileItem item = m_model->fileItem(i);
1514 if (item.isDir()) {
1515 ++folderCount;
1516 } else {
1517 ++fileCount;
1518 if (countFileSize) {
1519 totalFileSize += item.size();
1520 }
1521 }
1522 }
1523 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1524 }
1525
1526 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1527 {
1528 ViewProperties props(viewPropertiesUrl());
1529 props.setSortFoldersFirst(foldersFirst);
1530
1531 m_model->setSortDirectoriesFirst(foldersFirst);
1532
1533 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1534 }
1535
1536 void DolphinView::updateSortHiddenLast(bool hiddenLast)
1537 {
1538 ViewProperties props(viewPropertiesUrl());
1539 props.setSortHiddenLast(hiddenLast);
1540
1541 m_model->setSortHiddenLast(hiddenLast);
1542
1543 Q_EMIT sortHiddenLastChanged(hiddenLast);
1544 }
1545
1546 QPair<bool, QString> DolphinView::pasteInfo() const
1547 {
1548 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1549 QPair<bool, QString> info;
1550 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1551 return info;
1552 }
1553
1554 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1555 {
1556 m_tabsForFiles = tabsForFiles;
1557 }
1558
1559 bool DolphinView::isTabsForFilesEnabled() const
1560 {
1561 return m_tabsForFiles;
1562 }
1563
1564 bool DolphinView::itemsExpandable() const
1565 {
1566 return m_mode == DetailsView;
1567 }
1568
1569 bool DolphinView::isExpanded(const KFileItem &item) const
1570 {
1571 Q_ASSERT(item.isDir());
1572 Q_ASSERT(items().contains(item));
1573 if (!itemsExpandable()) {
1574 return false;
1575 }
1576 return m_model->isExpanded(m_model->index(item));
1577 }
1578
1579 void DolphinView::restoreState(QDataStream &stream)
1580 {
1581 // Read the version number of the view state and check if the version is supported.
1582 quint32 version = 0;
1583 stream >> version;
1584 if (version != 1) {
1585 // The version of the view state isn't supported, we can't restore it.
1586 return;
1587 }
1588
1589 // Restore the current item that had the keyboard focus
1590 stream >> m_currentItemUrl;
1591
1592 // Restore the previously selected items
1593 stream >> m_selectedUrls;
1594
1595 // Restore the view position
1596 stream >> m_restoredContentsPosition;
1597
1598 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1599 QSet<QUrl> urls;
1600 stream >> urls;
1601 m_model->restoreExpandedDirectories(urls);
1602 }
1603
1604 void DolphinView::saveState(QDataStream &stream)
1605 {
1606 stream << quint32(1); // View state version
1607
1608 // Save the current item that has the keyboard focus
1609 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1610 if (currentIndex != -1) {
1611 KFileItem item = m_model->fileItem(currentIndex);
1612 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1613 QUrl currentItemUrl = item.url();
1614 stream << currentItemUrl;
1615 } else {
1616 stream << QUrl();
1617 }
1618
1619 // Save the selected urls
1620 stream << selectedItems().urlList();
1621
1622 // Save view position
1623 const qreal x = m_container->horizontalScrollBar()->value();
1624 const qreal y = m_container->verticalScrollBar()->value();
1625 stream << QPoint(x, y);
1626
1627 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1628 stream << m_model->expandedDirectories();
1629 }
1630
1631 KFileItem DolphinView::rootItem() const
1632 {
1633 return m_model->rootItem();
1634 }
1635
1636 void DolphinView::setViewPropertiesContext(const QString &context)
1637 {
1638 m_viewPropertiesContext = context;
1639 }
1640
1641 QString DolphinView::viewPropertiesContext() const
1642 {
1643 return m_viewPropertiesContext;
1644 }
1645
1646 QUrl DolphinView::openItemAsFolderUrl(const KFileItem &item, const bool browseThroughArchives)
1647 {
1648 if (item.isNull()) {
1649 return QUrl();
1650 }
1651
1652 QUrl url = item.targetUrl();
1653
1654 if (item.isDir()) {
1655 return url;
1656 }
1657
1658 if (item.isMimeTypeKnown()) {
1659 const QString &mimetype = item.mimetype();
1660
1661 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1662 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1663 // zip:/<path>/ when clicking on a zip file, etc.
1664 // The .protocol file specifies the mimetype that the kioslave handles.
1665 // Note that we don't use mimetype inheritance since we don't want to
1666 // open OpenDocument files as zip folders...
1667 const QString &protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1668 if (!protocol.isEmpty()) {
1669 url.setScheme(protocol);
1670 return url;
1671 }
1672 }
1673
1674 if (mimetype == QLatin1String("application/x-desktop")) {
1675 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1676 KDesktopFile desktopFile(url.toLocalFile());
1677 if (desktopFile.hasLinkType()) {
1678 const QString linkUrl = desktopFile.readUrl();
1679 if (!linkUrl.startsWith(QLatin1String("http"))) {
1680 return QUrl::fromUserInput(linkUrl);
1681 }
1682 }
1683 }
1684 }
1685
1686 return QUrl();
1687 }
1688
1689 void DolphinView::resetZoomLevel()
1690 {
1691 ViewModeSettings settings{m_mode};
1692 settings.useDefaults(true);
1693 const int defaultIconSize = settings.iconSize();
1694 settings.useDefaults(false);
1695
1696 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize)));
1697 }
1698
1699 void DolphinView::observeCreatedItem(const QUrl &url)
1700 {
1701 if (m_active) {
1702 forceUrlsSelection(url, {url});
1703 }
1704 }
1705
1706 void DolphinView::slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl)
1707 {
1708 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1709 Q_EMIT redirection(oldUrl, newUrl);
1710 m_url = newUrl; // #186947
1711 }
1712 }
1713
1714 void DolphinView::updateSelectionState()
1715 {
1716 if (!m_selectedUrls.isEmpty()) {
1717 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1718
1719 const bool shouldScrollToCurrentItem = m_clearSelectionBeforeSelectingNewItems;
1720 // if there is a selection already, leave it that way
1721 // unless some drop/paste job are in the process of creating items
1722 if (!selectionManager->hasSelection() || m_selectJobCreatedItems) {
1723 if (m_clearSelectionBeforeSelectingNewItems) {
1724 selectionManager->clearSelection();
1725 m_clearSelectionBeforeSelectingNewItems = false;
1726 }
1727
1728 KItemSet selectedItems = selectionManager->selectedItems();
1729
1730 QList<QUrl>::iterator it = m_selectedUrls.begin();
1731 while (it != m_selectedUrls.end()) {
1732 const int index = m_model->index(*it);
1733 if (index >= 0) {
1734 selectedItems.insert(index);
1735 it = m_selectedUrls.erase(it);
1736 } else {
1737 ++it;
1738 }
1739 }
1740
1741 if (!selectedItems.isEmpty()) {
1742 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1743 selectionManager->setSelectedItems(selectedItems);
1744 selectionManager->endAnchoredSelection();
1745 if (shouldScrollToCurrentItem) {
1746 m_view->scrollToItem(selectedItems.first());
1747 }
1748 }
1749 }
1750 }
1751 }
1752
1753 void DolphinView::updateViewState()
1754 {
1755 if (m_currentItemUrl != QUrl()) {
1756 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1757
1758 // if there is a selection already, leave it that way
1759 if (!selectionManager->hasSelection()) {
1760 const int currentIndex = m_model->index(m_currentItemUrl);
1761 if (currentIndex != -1) {
1762 selectionManager->setCurrentItem(currentIndex);
1763
1764 // scroll to current item and reset the state
1765 if (m_scrollToCurrentItem) {
1766 m_view->scrollToItem(currentIndex, KItemListView::ViewItemPosition::Middle);
1767 m_scrollToCurrentItem = false;
1768 }
1769 m_currentItemUrl = QUrl();
1770 } else {
1771 selectionManager->setCurrentItem(0);
1772 }
1773 } else {
1774 m_currentItemUrl = QUrl();
1775 }
1776 }
1777
1778 if (!m_restoredContentsPosition.isNull()) {
1779 const int x = m_restoredContentsPosition.x();
1780 const int y = m_restoredContentsPosition.y();
1781 m_restoredContentsPosition = QPoint();
1782
1783 m_container->horizontalScrollBar()->setValue(x);
1784 m_container->verticalScrollBar()->setValue(y);
1785 }
1786
1787 updateSelectionState();
1788 }
1789
1790 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1791 {
1792 if (GeneralSettings::showToolTips()) {
1793 #if HAVE_BALOO
1794 m_toolTipManager->hideToolTip(behavior);
1795 #else
1796 Q_UNUSED(behavior)
1797 #endif
1798 } else if (m_mode == DolphinView::IconsView) {
1799 QToolTip::hideText();
1800 }
1801 }
1802
1803 bool DolphinView::handleSpaceAsNormalKey() const
1804 {
1805 return !m_container->hasFocus() || m_container->controller()->isSearchAsYouTypeActive();
1806 }
1807
1808 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1809 {
1810 const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1811
1812 // verify that only one item is selected
1813 if (selectionManager->selectedItems().count() == 1) {
1814 const int index = selectionManager->currentItem();
1815 const QUrl fileItemUrl = m_model->fileItem(index).url();
1816
1817 // check if the selected item was the same item that started the twoClicksRenaming
1818 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1819 renameSelectedItems();
1820 }
1821 }
1822 }
1823
1824 void DolphinView::slotTrashFileFinished(KJob *job)
1825 {
1826 if (job->error() == 0) {
1827 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1828 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1829 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1830 Q_EMIT errorMessage(job->errorString(), job->error());
1831 }
1832 }
1833
1834 void DolphinView::slotDeleteFileFinished(KJob *job)
1835 {
1836 if (job->error() == 0) {
1837 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1838 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1839 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1840 Q_EMIT errorMessage(job->errorString(), job->error());
1841 }
1842 }
1843
1844 void DolphinView::selectNextItem()
1845 {
1846 if (m_active && m_selectNextItem) {
1847 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1848 if (selectedItems().isEmpty()) {
1849 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1850 return;
1851 }
1852 const auto lastSelectedIndex = m_model->index(selectedItems().last());
1853 if (lastSelectedIndex < 0) {
1854 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1855 return;
1856 }
1857 auto nextItem = lastSelectedIndex + 1;
1858 if (nextItem >= itemsCount()) {
1859 nextItem = lastSelectedIndex - selectedItemsCount();
1860 }
1861 if (nextItem >= 0) {
1862 selectionManager->setSelected(nextItem, 1);
1863 }
1864 m_selectNextItem = false;
1865 }
1866 }
1867
1868 void DolphinView::slotRenamingResult(KJob *job)
1869 {
1870 if (job->error()) {
1871 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1872 Q_ASSERT(copyJob);
1873 const QUrl newUrl = copyJob->destUrl();
1874 const int index = m_model->index(newUrl);
1875 if (index >= 0) {
1876 QHash<QByteArray, QVariant> data;
1877 const QUrl oldUrl = copyJob->srcUrls().at(0);
1878 data.insert("text", oldUrl.fileName());
1879 m_model->setData(index, data);
1880 }
1881 }
1882 }
1883
1884 void DolphinView::slotDirectoryLoadingStarted()
1885 {
1886 m_loadingState = LoadingState::Loading;
1887 updatePlaceholderLabel();
1888
1889 // Disable the writestate temporary until it can be determined in a fast way
1890 // in DolphinView::slotDirectoryLoadingCompleted()
1891 if (m_isFolderWritable) {
1892 m_isFolderWritable = false;
1893 Q_EMIT writeStateChanged(m_isFolderWritable);
1894 }
1895
1896 Q_EMIT directoryLoadingStarted();
1897 }
1898
1899 void DolphinView::slotDirectoryLoadingCompleted()
1900 {
1901 m_loadingState = LoadingState::Completed;
1902
1903 // Update the view-state. This has to be done asynchronously
1904 // because the view might not be in its final state yet.
1905 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1906
1907 // Update the placeholder label in case we found that the folder was empty
1908 // after loading it
1909
1910 Q_EMIT directoryLoadingCompleted();
1911
1912 updatePlaceholderLabel();
1913 updateWritableState();
1914 }
1915
1916 void DolphinView::slotDirectoryLoadingCanceled()
1917 {
1918 m_loadingState = LoadingState::Canceled;
1919
1920 updatePlaceholderLabel();
1921
1922 Q_EMIT directoryLoadingCanceled();
1923 }
1924
1925 void DolphinView::slotItemsChanged()
1926 {
1927 m_assureVisibleCurrentIndex = false;
1928 }
1929
1930 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1931 {
1932 Q_UNUSED(previous)
1933 Q_ASSERT(m_model->sortOrder() == current);
1934
1935 ViewProperties props(viewPropertiesUrl());
1936 props.setSortOrder(current);
1937
1938 Q_EMIT sortOrderChanged(current);
1939 }
1940
1941 void DolphinView::slotSortRoleChangedByHeader(const QByteArray &current, const QByteArray &previous)
1942 {
1943 Q_UNUSED(previous)
1944 Q_ASSERT(m_model->sortRole() == current);
1945
1946 ViewProperties props(viewPropertiesUrl());
1947 props.setSortRole(current);
1948
1949 Q_EMIT sortRoleChanged(current);
1950 }
1951
1952 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray> &current, const QList<QByteArray> &previous)
1953 {
1954 Q_UNUSED(previous)
1955 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1956
1957 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1958
1959 m_visibleRoles = current;
1960
1961 ViewProperties props(viewPropertiesUrl());
1962 props.setVisibleRoles(m_visibleRoles);
1963
1964 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1965 }
1966
1967 void DolphinView::slotRoleEditingCanceled()
1968 {
1969 disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
1970 }
1971
1972 void DolphinView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value)
1973 {
1974 disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
1975
1976 const KFileItemList items = selectedItems();
1977 if (items.count() != 1) {
1978 return;
1979 }
1980
1981 if (role == "text") {
1982 const KFileItem oldItem = items.first();
1983 const EditResult retVal = value.value<EditResult>();
1984 const QString newName = retVal.newName;
1985 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1986 const QUrl oldUrl = oldItem.url();
1987
1988 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1989 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1990
1991 #ifndef Q_OS_WIN
1992 // Confirm hiding file/directory by renaming inline
1993 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1994 KGuiItem yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden"));
1995
1996 const auto code =
1997 KMessageBox::questionTwoActions(this,
1998 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1999 "Do you still want to rename it?")
2000 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
2001 "Do you still want to rename it?"),
2002 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
2003 yesGuiItem,
2004 KStandardGuiItem::cancel(),
2005 QStringLiteral("ConfirmHide"));
2006
2007 if (code == KMessageBox::SecondaryAction) {
2008 return;
2009 }
2010 }
2011 #endif
2012
2013 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
2014 if (!newNameExistsAlready && m_model->index(oldUrl) == index) {
2015 // Only change the data in the model if no item with the new name
2016 // is in the model yet. If there is an item with the new name
2017 // already, calling KIO::CopyJob will open a dialog
2018 // asking for a new name, and KFileItemModel will update the
2019 // data when the dir lister signals that the file name has changed.
2020 QHash<QByteArray, QVariant> data;
2021 data.insert(role, retVal.newName);
2022 m_model->setData(index, data);
2023 }
2024
2025 KIO::Job *job = KIO::moveAs(oldUrl, newUrl);
2026 KJobWidgets::setWindow(job, this);
2027 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
2028 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
2029
2030 if (!newNameExistsAlready) {
2031 forceUrlsSelection(newUrl, {newUrl});
2032
2033 // Only connect the result signal if there is no item with the new name
2034 // in the model yet, see bug 328262.
2035 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
2036 }
2037 }
2038 if (retVal.direction != EditDone) {
2039 const short indexShift = retVal.direction == EditNext ? 1 : -1;
2040 m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect);
2041 m_container->controller()->selectionManager()->setSelected(index + indexShift, 1, KItemListSelectionManager::Select);
2042 renameSelectedItems();
2043 }
2044 }
2045 }
2046
2047 void DolphinView::loadDirectory(const QUrl &url, bool reload)
2048 {
2049 if (!url.isValid()) {
2050 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
2051 if (location.isEmpty()) {
2052 Q_EMIT errorMessage(i18nc("@info:status", "The location is empty."), KIO::ERR_UNKNOWN);
2053 } else {
2054 Q_EMIT errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location), KIO::ERR_UNKNOWN);
2055 }
2056 return;
2057 }
2058
2059 if (reload) {
2060 m_model->refreshDirectory(url);
2061 } else {
2062 m_model->loadDirectory(url);
2063 }
2064 }
2065
2066 void DolphinView::applyViewProperties()
2067 {
2068 const ViewProperties props(viewPropertiesUrl());
2069 applyViewProperties(props);
2070 }
2071
2072 void DolphinView::applyViewProperties(const ViewProperties &props)
2073 {
2074 m_view->beginTransaction();
2075
2076 const Mode mode = props.viewMode();
2077 if (m_mode != mode) {
2078 const Mode previousMode = m_mode;
2079 m_mode = mode;
2080
2081 // Changing the mode might result in changing
2082 // the zoom level. Remember the old zoom level so
2083 // that zoomLevelChanged() can get emitted.
2084 const int oldZoomLevel = m_view->zoomLevel();
2085 applyModeToView();
2086
2087 Q_EMIT modeChanged(m_mode, previousMode);
2088
2089 if (m_view->zoomLevel() != oldZoomLevel) {
2090 Q_EMIT zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
2091 }
2092 }
2093
2094 const bool hiddenFilesShown = props.hiddenFilesShown();
2095 if (hiddenFilesShown != m_model->showHiddenFiles()) {
2096 m_model->setShowHiddenFiles(hiddenFilesShown);
2097 Q_EMIT hiddenFilesShownChanged(hiddenFilesShown);
2098 }
2099
2100 const bool groupedSorting = props.groupedSorting();
2101 if (groupedSorting != m_model->groupedSorting()) {
2102 m_model->setGroupedSorting(groupedSorting);
2103 Q_EMIT groupedSortingChanged(groupedSorting);
2104 }
2105
2106 const QByteArray sortRole = props.sortRole();
2107 if (sortRole != m_model->sortRole()) {
2108 m_model->setSortRole(sortRole);
2109 Q_EMIT sortRoleChanged(sortRole);
2110 }
2111
2112 const Qt::SortOrder sortOrder = props.sortOrder();
2113 if (sortOrder != m_model->sortOrder()) {
2114 m_model->setSortOrder(sortOrder);
2115 Q_EMIT sortOrderChanged(sortOrder);
2116 }
2117
2118 const bool sortFoldersFirst = props.sortFoldersFirst();
2119 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
2120 m_model->setSortDirectoriesFirst(sortFoldersFirst);
2121 Q_EMIT sortFoldersFirstChanged(sortFoldersFirst);
2122 }
2123
2124 const bool sortHiddenLast = props.sortHiddenLast();
2125 if (sortHiddenLast != m_model->sortHiddenLast()) {
2126 m_model->setSortHiddenLast(sortHiddenLast);
2127 Q_EMIT sortHiddenLastChanged(sortHiddenLast);
2128 }
2129
2130 const QList<QByteArray> visibleRoles = props.visibleRoles();
2131 if (visibleRoles != m_visibleRoles) {
2132 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
2133 m_visibleRoles = visibleRoles;
2134 m_view->setVisibleRoles(visibleRoles);
2135 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
2136 }
2137
2138 const bool previewsShown = props.previewsShown();
2139 if (previewsShown != m_view->previewsShown()) {
2140 const int oldZoomLevel = zoomLevel();
2141
2142 m_view->setPreviewsShown(previewsShown);
2143 Q_EMIT previewsShownChanged(previewsShown);
2144
2145 // Changing the preview-state might result in a changed zoom-level
2146 if (oldZoomLevel != zoomLevel()) {
2147 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
2148 }
2149 }
2150
2151 KItemListView *itemListView = m_container->controller()->view();
2152 if (itemListView->isHeaderVisible()) {
2153 KItemListHeader *header = itemListView->header();
2154 const QList<int> headerColumnWidths = props.headerColumnWidths();
2155 const int rolesCount = m_visibleRoles.count();
2156 if (headerColumnWidths.count() == rolesCount) {
2157 header->setAutomaticColumnResizing(false);
2158
2159 QHash<QByteArray, qreal> columnWidths;
2160 for (int i = 0; i < rolesCount; ++i) {
2161 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
2162 }
2163 header->setColumnWidths(columnWidths);
2164 } else {
2165 header->setAutomaticColumnResizing(true);
2166 }
2167 header->setSidePadding(DetailsModeSettings::sidePadding());
2168 }
2169
2170 m_view->endTransaction();
2171 }
2172
2173 void DolphinView::applyModeToView()
2174 {
2175 switch (m_mode) {
2176 case IconsView:
2177 m_view->setItemLayout(KFileItemListView::IconsLayout);
2178 break;
2179 case CompactView:
2180 m_view->setItemLayout(KFileItemListView::CompactLayout);
2181 break;
2182 case DetailsView:
2183 m_view->setItemLayout(KFileItemListView::DetailsLayout);
2184 break;
2185 default:
2186 Q_ASSERT(false);
2187 break;
2188 }
2189 }
2190
2191 void DolphinView::pasteToUrl(const QUrl &url)
2192 {
2193 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
2194 KJobWidgets::setWindow(job, this);
2195 m_clearSelectionBeforeSelectingNewItems = true;
2196 m_markFirstNewlySelectedItemAsCurrent = true;
2197 m_selectJobCreatedItems = true;
2198 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
2199 connect(job, &KIO::PasteJob::copyJobStarted, this, [this](const KIO::CopyJob *copyJob) {
2200 connect(copyJob, &KIO::CopyJob::copying, this, &DolphinView::slotItemCreatedFromJob);
2201 connect(copyJob, &KIO::CopyJob::moving, this, &DolphinView::slotItemCreatedFromJob);
2202 connect(copyJob, &KIO::CopyJob::linking, this, [this](KIO::Job *job, const QString &src, const QUrl &dest) {
2203 Q_UNUSED(job)
2204 Q_UNUSED(src)
2205 slotItemCreated(dest);
2206 });
2207 });
2208 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotJobResult);
2209 }
2210
2211 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
2212 {
2213 QList<QUrl> urls;
2214
2215 const KFileItemList items = selectedItems();
2216 urls.reserve(items.count());
2217 for (const KFileItem &item : items) {
2218 urls.append(item.url());
2219 }
2220
2221 if (itemsExpandable()) {
2222 // TODO: Check if we still need KDirModel for this in KDE 5.0
2223 urls = KDirModel::simplifiedUrlList(urls);
2224 }
2225
2226 return urls;
2227 }
2228
2229 QMimeData *DolphinView::selectionMimeData() const
2230 {
2231 const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
2232 const KItemSet selectedIndexes = selectionManager->selectedItems();
2233
2234 return m_model->createMimeData(selectedIndexes);
2235 }
2236
2237 void DolphinView::updateWritableState()
2238 {
2239 const bool wasFolderWritable = m_isFolderWritable;
2240 m_isFolderWritable = false;
2241
2242 KFileItem item = m_model->rootItem();
2243 if (item.isNull()) {
2244 // Try to find out if the URL is writable even if the "root item" is
2245 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2246 item = KFileItem(url());
2247 item.setDelayedMimeTypes(true);
2248 }
2249
2250 KFileItemListProperties capabilities(KFileItemList() << item);
2251 m_isFolderWritable = capabilities.supportsWriting();
2252
2253 if (m_isFolderWritable != wasFolderWritable) {
2254 Q_EMIT writeStateChanged(m_isFolderWritable);
2255 }
2256 }
2257
2258 bool DolphinView::isFolderWritable() const
2259 {
2260 return m_isFolderWritable;
2261 }
2262
2263 QUrl DolphinView::viewPropertiesUrl() const
2264 {
2265 if (m_viewPropertiesContext.isEmpty()) {
2266 return m_url;
2267 }
2268
2269 QUrl url;
2270 url.setScheme(m_url.scheme());
2271 url.setPath(m_viewPropertiesContext);
2272 return url;
2273 }
2274
2275 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl> &urls)
2276 {
2277 forceUrlsSelection(urls.first(), urls);
2278 }
2279
2280 void DolphinView::forceUrlsSelection(const QUrl &current, const QList<QUrl> &selected)
2281 {
2282 clearSelection();
2283 m_clearSelectionBeforeSelectingNewItems = true;
2284 markUrlAsCurrent(current);
2285 markUrlsAsSelected(selected);
2286 }
2287
2288 void DolphinView::copyPathToClipboard()
2289 {
2290 const KFileItemList list = selectedItems();
2291 if (list.isEmpty()) {
2292 return;
2293 }
2294 const KFileItem &item = list.at(0);
2295 QString path = item.localPath();
2296 if (path.isEmpty()) {
2297 path = item.url().toDisplayString();
2298 }
2299 QClipboard *clipboard = QApplication::clipboard();
2300 if (clipboard == nullptr) {
2301 return;
2302 }
2303 clipboard->setText(QDir::toNativeSeparators(path));
2304 }
2305
2306 void DolphinView::slotIncreaseZoom()
2307 {
2308 setZoomLevel(zoomLevel() + 1);
2309 }
2310
2311 void DolphinView::slotDecreaseZoom()
2312 {
2313 setZoomLevel(zoomLevel() - 1);
2314 }
2315
2316 void DolphinView::slotSwipeUp()
2317 {
2318 Q_EMIT goUpRequested();
2319 }
2320
2321 void DolphinView::showLoadingPlaceholder()
2322 {
2323 m_placeholderLabel->setText(i18n("Loading…"));
2324 m_placeholderLabel->setVisible(true);
2325 }
2326
2327 void DolphinView::updatePlaceholderLabel()
2328 {
2329 m_showLoadingPlaceholderTimer->stop();
2330 if (itemsCount() > 0) {
2331 m_placeholderLabel->setVisible(false);
2332 return;
2333 }
2334
2335 if (m_loadingState == LoadingState::Loading) {
2336 m_placeholderLabel->setVisible(false);
2337 m_showLoadingPlaceholderTimer->start();
2338 return;
2339 }
2340
2341 if (m_loadingState == LoadingState::Canceled) {
2342 m_placeholderLabel->setText(i18n("Loading canceled"));
2343 } else if (!nameFilter().isEmpty()) {
2344 m_placeholderLabel->setText(i18n("No items matching the filter"));
2345 } else if (m_url.scheme() == QLatin1String("baloosearch") || m_url.scheme() == QLatin1String("filenamesearch")) {
2346 m_placeholderLabel->setText(i18n("No items matching the search"));
2347 } else if (m_url.scheme() == QLatin1String("trash") && m_url.path() == QLatin1String("/")) {
2348 m_placeholderLabel->setText(i18n("Trash is empty"));
2349 } else if (m_url.scheme() == QLatin1String("tags")) {
2350 if (m_url.path() == QLatin1Char('/')) {
2351 m_placeholderLabel->setText(i18n("No tags"));
2352 } else {
2353 const QString tagName = m_url.path().mid(1); // Remove leading /
2354 m_placeholderLabel->setText(i18n("No files tagged with \"%1\"", tagName));
2355 }
2356
2357 } else if (m_url.scheme() == QLatin1String("recentlyused")) {
2358 m_placeholderLabel->setText(i18n("No recently used items"));
2359 } else if (m_url.scheme() == QLatin1String("smb")) {
2360 m_placeholderLabel->setText(i18n("No shared folders found"));
2361 } else if (m_url.scheme() == QLatin1String("network")) {
2362 m_placeholderLabel->setText(i18n("No relevant network resources found"));
2363 } else if (m_url.scheme() == QLatin1String("mtp") && m_url.path() == QLatin1String("/")) {
2364 m_placeholderLabel->setText(i18n("No MTP-compatible devices found"));
2365 } else if (m_url.scheme() == QLatin1String("afc") && m_url.path() == QLatin1String("/")) {
2366 m_placeholderLabel->setText(i18n("No Apple devices found"));
2367 } else if (m_url.scheme() == QLatin1String("bluetooth")) {
2368 m_placeholderLabel->setText(i18n("No Bluetooth devices found"));
2369 } else {
2370 m_placeholderLabel->setText(i18n("Folder is empty"));
2371 }
2372
2373 m_placeholderLabel->setVisible(true);
2374 }
2375
2376 bool DolphinView::tryShowNameToolTip(QHelpEvent *event)
2377 {
2378 if (!GeneralSettings::showToolTips() && m_mode == DolphinView::IconsView) {
2379 const std::optional<int> index = m_view->itemAt(event->pos());
2380
2381 if (!index.has_value()) {
2382 return false;
2383 }
2384
2385 // Check whether the filename has been elided
2386 const bool isElided = m_view->isElided(index.value());
2387
2388 if (isElided) {
2389 const KFileItem item = m_model->fileItem(index.value());
2390 const QString text = item.text();
2391 const QPoint pos = mapToGlobal(event->pos());
2392 QToolTip::showText(pos, text);
2393 return true;
2394 }
2395 }
2396 return false;
2397 }
2398
2399 #include "moc_dolphinview.cpp"