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