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