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