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