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