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