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