]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Exit the deleted directory when it is removed
[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 connect(m_model, &KFileItemModel::currentDirectoryRemoved, this, &DolphinView::currentDirectoryRemoved);
199
200 connect(this, &DolphinView::itemCountChanged,
201 this, &DolphinView::updatePlaceholderLabel);
202
203 m_view->installEventFilter(this);
204 connect(m_view, &DolphinItemListView::sortOrderChanged,
205 this, &DolphinView::slotSortOrderChangedByHeader);
206 connect(m_view, &DolphinItemListView::sortRoleChanged,
207 this, &DolphinView::slotSortRoleChangedByHeader);
208 connect(m_view, &DolphinItemListView::visibleRolesChanged,
209 this, &DolphinView::slotVisibleRolesChangedByHeader);
210 connect(m_view, &DolphinItemListView::roleEditingCanceled,
211 this, &DolphinView::slotRoleEditingCanceled);
212 connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished,
213 this, &DolphinView::slotHeaderColumnWidthChangeFinished);
214 connect(m_view->header(), &KItemListHeader::sidePaddingChanged,
215 this, &DolphinView::slotSidePaddingWidthChanged);
216
217 KItemListSelectionManager* selectionManager = controller->selectionManager();
218 connect(selectionManager, &KItemListSelectionManager::selectionChanged,
219 this, &DolphinView::slotSelectionChanged);
220
221 #if HAVE_BALOO
222 m_toolTipManager = new ToolTipManager(this);
223 connect(m_toolTipManager, &ToolTipManager::urlActivated, this, &DolphinView::urlActivated);
224 #endif
225
226 m_versionControlObserver = new VersionControlObserver(this);
227 m_versionControlObserver->setView(this);
228 m_versionControlObserver->setModel(m_model);
229 connect(m_versionControlObserver, &VersionControlObserver::infoMessage, this, &DolphinView::infoMessage);
230 connect(m_versionControlObserver, &VersionControlObserver::errorMessage, this, &DolphinView::errorMessage);
231 connect(m_versionControlObserver, &VersionControlObserver::operationCompletedMessage, this, &DolphinView::operationCompletedMessage);
232
233 m_twoClicksRenamingTimer = new QTimer(this);
234 m_twoClicksRenamingTimer->setSingleShot(true);
235 connect(m_twoClicksRenamingTimer, &QTimer::timeout, this, &DolphinView::slotTwoClicksRenamingTimerTimeout);
236
237 applyViewProperties();
238 m_topLayout->addWidget(m_container);
239
240 loadDirectory(url);
241 }
242
243 DolphinView::~DolphinView()
244 {
245 disconnect(m_container->controller(), &KItemListController::modelChanged, this, &DolphinView::slotModelChanged);
246 }
247
248 QUrl DolphinView::url() const
249 {
250 return m_url;
251 }
252
253 void DolphinView::setActive(bool active)
254 {
255 if (active == m_active) {
256 return;
257 }
258
259 m_active = active;
260
261 updatePalette();
262
263 if (active) {
264 m_container->setFocus();
265 Q_EMIT activated();
266 Q_EMIT writeStateChanged(m_isFolderWritable);
267 }
268 }
269
270 bool DolphinView::isActive() const
271 {
272 return m_active;
273 }
274
275 void DolphinView::setViewMode(Mode mode)
276 {
277 if (mode != m_mode) {
278 ViewProperties props(viewPropertiesUrl());
279 props.setViewMode(mode);
280
281 // We pass the new ViewProperties to applyViewProperties, rather than
282 // storing them on disk and letting applyViewProperties() read them
283 // from there, to prevent that changing the view mode fails if the
284 // .directory file is not writable (see bug 318534).
285 applyViewProperties(props);
286 }
287 }
288
289 DolphinView::Mode DolphinView::viewMode() const
290 {
291 return m_mode;
292 }
293
294 void DolphinView::setSelectionModeEnabled(const bool enabled)
295 {
296 if (enabled) {
297 m_proxyStyle = std::make_unique<SelectionMode::SingleClickSelectionProxyStyle>();
298 setStyle(m_proxyStyle.get());
299 m_view->setStyle(m_proxyStyle.get());
300 m_view->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::False);
301 } else {
302 setStyle(QApplication::style());
303 m_view->setStyle(QApplication::style());
304 m_view->setEnabledSelectionToggles(DolphinItemListView::SelectionTogglesEnabled::FollowSetting);
305 }
306 m_container->controller()->setSelectionModeEnabled(enabled);
307 }
308
309 bool DolphinView::selectionMode() const
310 {
311 return m_container->controller()->selectionMode();
312 }
313
314 void DolphinView::setPreviewsShown(bool show)
315 {
316 if (previewsShown() == show) {
317 return;
318 }
319
320 ViewProperties props(viewPropertiesUrl());
321 props.setPreviewsShown(show);
322
323 const int oldZoomLevel = m_view->zoomLevel();
324 m_view->setPreviewsShown(show);
325 Q_EMIT previewsShownChanged(show);
326
327 const int newZoomLevel = m_view->zoomLevel();
328 if (newZoomLevel != oldZoomLevel) {
329 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
330 }
331 }
332
333 bool DolphinView::previewsShown() const
334 {
335 return m_view->previewsShown();
336 }
337
338 void DolphinView::setHiddenFilesShown(bool show)
339 {
340 if (m_model->showHiddenFiles() == show) {
341 return;
342 }
343
344 const KFileItemList itemList = selectedItems();
345 m_selectedUrls.clear();
346 m_selectedUrls = itemList.urlList();
347
348 ViewProperties props(viewPropertiesUrl());
349 props.setHiddenFilesShown(show);
350
351 m_model->setShowHiddenFiles(show);
352 Q_EMIT hiddenFilesShownChanged(show);
353 }
354
355 bool DolphinView::hiddenFilesShown() const
356 {
357 return m_model->showHiddenFiles();
358 }
359
360 void DolphinView::setGroupedSorting(bool grouped)
361 {
362 if (grouped == groupedSorting()) {
363 return;
364 }
365
366 ViewProperties props(viewPropertiesUrl());
367 props.setGroupedSorting(grouped);
368 props.save();
369
370 m_container->controller()->model()->setGroupedSorting(grouped);
371
372 Q_EMIT groupedSortingChanged(grouped);
373 }
374
375 bool DolphinView::groupedSorting() const
376 {
377 return m_model->groupedSorting();
378 }
379
380 KFileItemList DolphinView::items() const
381 {
382 KFileItemList list;
383 const int itemCount = m_model->count();
384 list.reserve(itemCount);
385
386 for (int i = 0; i < itemCount; ++i) {
387 list.append(m_model->fileItem(i));
388 }
389
390 return list;
391 }
392
393 int DolphinView::itemsCount() const
394 {
395 return m_model->count();
396 }
397
398 KFileItemList DolphinView::selectedItems() const
399 {
400 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
401
402 KFileItemList selectedItems;
403 const auto items = selectionManager->selectedItems();
404 selectedItems.reserve(items.count());
405 for (int index : items) {
406 selectedItems.append(m_model->fileItem(index));
407 }
408 return selectedItems;
409 }
410
411 int DolphinView::selectedItemsCount() const
412 {
413 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
414 return selectionManager->selectedItems().count();
415 }
416
417 void DolphinView::markUrlsAsSelected(const QList<QUrl>& urls)
418 {
419 m_selectedUrls = urls;
420 }
421
422 void DolphinView::markUrlAsCurrent(const QUrl &url)
423 {
424 m_currentItemUrl = url;
425 m_scrollToCurrentItem = true;
426 }
427
428 void DolphinView::selectItems(const QRegularExpression &regexp, bool enabled)
429 {
430 const KItemListSelectionManager::SelectionMode mode = enabled
431 ? KItemListSelectionManager::Select
432 : KItemListSelectionManager::Deselect;
433 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
434
435 for (int index = 0; index < m_model->count(); index++) {
436 const KFileItem item = m_model->fileItem(index);
437 if (regexp.match(item.text()).hasMatch()) {
438 // An alternative approach would be to store the matching items in a KItemSet and
439 // select them in one go after the loop, but we'd need a new function
440 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
441 // for that.
442 selectionManager->setSelected(index, 1, mode);
443 }
444 }
445 }
446
447 void DolphinView::setZoomLevel(int level)
448 {
449 const int oldZoomLevel = zoomLevel();
450 m_view->setZoomLevel(level);
451 if (zoomLevel() != oldZoomLevel) {
452 hideToolTip();
453 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
454 }
455 }
456
457 int DolphinView::zoomLevel() const
458 {
459 return m_view->zoomLevel();
460 }
461
462 void DolphinView::setSortRole(const QByteArray& role)
463 {
464 if (role != sortRole()) {
465 updateSortRole(role);
466 }
467 }
468
469 QByteArray DolphinView::sortRole() const
470 {
471 const KItemModelBase* model = m_container->controller()->model();
472 return model->sortRole();
473 }
474
475 void DolphinView::setSortOrder(Qt::SortOrder order)
476 {
477 if (sortOrder() != order) {
478 updateSortOrder(order);
479 }
480 }
481
482 Qt::SortOrder DolphinView::sortOrder() const
483 {
484 return m_model->sortOrder();
485 }
486
487 void DolphinView::setSortFoldersFirst(bool foldersFirst)
488 {
489 if (sortFoldersFirst() != foldersFirst) {
490 updateSortFoldersFirst(foldersFirst);
491 }
492 }
493
494 bool DolphinView::sortFoldersFirst() const
495 {
496 return m_model->sortDirectoriesFirst();
497 }
498
499 void DolphinView::setSortHiddenLast(bool hiddenLast)
500 {
501 if (sortHiddenLast() != hiddenLast) {
502 updateSortHiddenLast(hiddenLast);
503 }
504 }
505
506 bool DolphinView::sortHiddenLast() const
507 {
508 return m_model->sortHiddenLast();
509 }
510
511 void DolphinView::setVisibleRoles(const QList<QByteArray>& roles)
512 {
513 const QList<QByteArray> previousRoles = roles;
514
515 ViewProperties props(viewPropertiesUrl());
516 props.setVisibleRoles(roles);
517
518 m_visibleRoles = roles;
519 m_view->setVisibleRoles(roles);
520
521 Q_EMIT visibleRolesChanged(m_visibleRoles, previousRoles);
522 }
523
524 QList<QByteArray> DolphinView::visibleRoles() const
525 {
526 return m_visibleRoles;
527 }
528
529 void DolphinView::reload()
530 {
531 QByteArray viewState;
532 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
533 saveState(saveStream);
534
535 setUrl(url());
536 loadDirectory(url(), true);
537
538 QDataStream restoreStream(viewState);
539 restoreState(restoreStream);
540 }
541
542 void DolphinView::readSettings()
543 {
544 const int oldZoomLevel = m_view->zoomLevel();
545
546 GeneralSettings::self()->load();
547 m_view->readSettings();
548 applyViewProperties();
549
550 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
551 m_container->controller()->setAutoActivationDelay(delay);
552
553 const int newZoomLevel = m_view->zoomLevel();
554 if (newZoomLevel != oldZoomLevel) {
555 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
556 }
557 }
558
559 void DolphinView::writeSettings()
560 {
561 GeneralSettings::self()->save();
562 m_view->writeSettings();
563 }
564
565 void DolphinView::setNameFilter(const QString& nameFilter)
566 {
567 m_model->setNameFilter(nameFilter);
568 }
569
570 QString DolphinView::nameFilter() const
571 {
572 return m_model->nameFilter();
573 }
574
575 void DolphinView::setMimeTypeFilters(const QStringList& filters)
576 {
577 return m_model->setMimeTypeFilters(filters);
578 }
579
580 QStringList DolphinView::mimeTypeFilters() const
581 {
582 return m_model->mimeTypeFilters();
583 }
584
585 void DolphinView::requestStatusBarText()
586 {
587 if (m_statJobForStatusBarText) {
588 // Kill the pending request.
589 m_statJobForStatusBarText->kill();
590 }
591
592 if (m_container->controller()->selectionManager()->hasSelection()) {
593 int folderCount = 0;
594 int fileCount = 0;
595 KIO::filesize_t totalFileSize = 0;
596
597 // Give a summary of the status of the selected files
598 const KFileItemList list = selectedItems();
599 for (const KFileItem& item : list) {
600 if (item.isDir()) {
601 ++folderCount;
602 } else {
603 ++fileCount;
604 totalFileSize += item.size();
605 }
606 }
607
608 if (folderCount + fileCount == 1) {
609 // If only one item is selected, show info about it
610 Q_EMIT statusBarTextChanged(list.first().getStatusBarInfo());
611 } else {
612 // At least 2 items are selected
613 emitStatusBarText(folderCount, fileCount, totalFileSize, HasSelection);
614 }
615 } else { // has no selection
616 if (!m_model->rootItem().url().isValid()) {
617 return;
618 }
619
620 m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(),
621 KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
622 connect(m_statJobForStatusBarText, &KJob::result,
623 this, &DolphinView::slotStatJobResult);
624 m_statJobForStatusBarText->start();
625 }
626 }
627
628 void DolphinView::emitStatusBarText(const int folderCount, const int fileCount,
629 KIO::filesize_t totalFileSize, const Selection selection)
630 {
631 QString foldersText;
632 QString filesText;
633 QString summary;
634
635 if (selection == HasSelection) {
636 // At least 2 items are selected because the case of 1 selected item is handled in
637 // DolphinView::requestStatusBarText().
638 foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
639 filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
640 } else {
641 foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount);
642 filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount);
643 }
644
645 if (fileCount > 0 && folderCount > 0) {
646 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
647 foldersText, filesText,
648 KFormat().formatByteSize(totalFileSize));
649 } else if (fileCount > 0) {
650 summary = i18nc("@info:status files (size)", "%1 (%2)",
651 filesText,
652 KFormat().formatByteSize(totalFileSize));
653 } else if (folderCount > 0) {
654 summary = foldersText;
655 } else {
656 summary = i18nc("@info:status", "0 Folders, 0 Files");
657 }
658 Q_EMIT statusBarTextChanged(summary);
659 }
660
661 QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
662 {
663 QList<QAction*> actions;
664
665 if (items.isEmpty()) {
666 const KFileItem item = m_model->rootItem();
667 if (!item.isNull()) {
668 actions = m_versionControlObserver->actions(KFileItemList() << item);
669 }
670 } else {
671 actions = m_versionControlObserver->actions(items);
672 }
673
674 return actions;
675 }
676
677 void DolphinView::setUrl(const QUrl& url)
678 {
679 if (url == m_url) {
680 return;
681 }
682
683 clearSelection();
684
685 m_url = url;
686
687 hideToolTip();
688
689 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
690 this, &DolphinView::slotRoleEditingFinished);
691
692 // It is important to clear the items from the model before
693 // applying the view properties, otherwise expensive operations
694 // might be done on the existing items although they get cleared
695 // anyhow afterwards by loadDirectory().
696 m_model->clear();
697 applyViewProperties();
698 loadDirectory(url);
699
700 Q_EMIT urlChanged(url);
701 }
702
703 void DolphinView::selectAll()
704 {
705 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
706 selectionManager->setSelected(0, m_model->count());
707 }
708
709 void DolphinView::invertSelection()
710 {
711 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
712 selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
713 }
714
715 void DolphinView::clearSelection()
716 {
717 m_selectedUrls.clear();
718 m_container->controller()->selectionManager()->clearSelection();
719 }
720
721 void DolphinView::renameSelectedItems()
722 {
723 const KFileItemList items = selectedItems();
724 if (items.isEmpty()) {
725 return;
726 }
727
728 if (items.count() == 1 && GeneralSettings::renameInline()) {
729 const int index = m_model->index(items.first());
730
731 QMetaObject::Connection * const connection = new QMetaObject::Connection;
732 *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=](){
733 QObject::disconnect(*connection);
734 delete connection;
735
736 m_view->editRole(index, "text");
737
738 hideToolTip();
739
740 connect(m_view, &DolphinItemListView::roleEditingFinished,
741 this, &DolphinView::slotRoleEditingFinished);
742 });
743 m_view->scrollToItem(index);
744
745 } else {
746 KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(items, this);
747 connect(dialog, &KIO::RenameFileDialog::renamingFinished,
748 this, &DolphinView::slotRenameDialogRenamingFinished);
749
750 dialog->open();
751 }
752
753 // Assure that the current index remains visible when KFileItemModel
754 // will notify the view about changed items (which might result in
755 // a changed sorting).
756 m_assureVisibleCurrentIndex = true;
757 }
758
759 void DolphinView::trashSelectedItems()
760 {
761 const QList<QUrl> list = simplifiedSelectedUrls();
762
763 #if KIO_VERSION >= QT_VERSION_CHECK(5, 100, 0)
764 using Iface = KIO::AskUserActionInterface;
765 auto *trashJob = new KIO::DeleteOrTrashJob(list, Iface::Trash, Iface::DefaultConfirmation, this);
766 connect(trashJob, &KJob::result, this, &DolphinView::slotTrashFileFinished);
767 trashJob->start();
768 #else
769 KIO::JobUiDelegate uiDelegate;
770 uiDelegate.setWindow(window());
771 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) {
772 KIO::Job* job = KIO::trash(list);
773 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job);
774 KJobWidgets::setWindow(job, this);
775 connect(job, &KIO::Job::result,
776 this, &DolphinView::slotTrashFileFinished);
777 }
778 #endif
779 }
780
781 void DolphinView::deleteSelectedItems()
782 {
783 const QList<QUrl> list = simplifiedSelectedUrls();
784
785 #if KIO_VERSION >= QT_VERSION_CHECK(5, 100, 0)
786 using Iface = KIO::AskUserActionInterface;
787 auto *trashJob = new KIO::DeleteOrTrashJob(list, Iface::Delete, Iface::DefaultConfirmation, this);
788 connect(trashJob, &KJob::result, this, &DolphinView::slotTrashFileFinished);
789 trashJob->start();
790 #else
791 KIO::JobUiDelegate uiDelegate;
792 uiDelegate.setWindow(window());
793 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) {
794 KIO::Job* job = KIO::del(list);
795 KJobWidgets::setWindow(job, this);
796 connect(job, &KIO::Job::result,
797 this, &DolphinView::slotDeleteFileFinished);
798 }
799 #endif
800 }
801
802 void DolphinView::cutSelectedItemsToClipboard()
803 {
804 QMimeData* mimeData = selectionMimeData();
805 KIO::setClipboardDataCut(mimeData, true);
806 KUrlMimeData::exportUrlsToPortal(mimeData);
807 QApplication::clipboard()->setMimeData(mimeData);
808 }
809
810 void DolphinView::copySelectedItemsToClipboard()
811 {
812 QMimeData *mimeData = selectionMimeData();
813 KUrlMimeData::exportUrlsToPortal(mimeData);
814 QApplication::clipboard()->setMimeData(mimeData);
815 }
816
817 void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
818 {
819 KIO::CopyJob* job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
820 KJobWidgets::setWindow(job, this);
821
822 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
823 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
824 KIO::FileUndoManager::self()->recordCopyJob(job);
825 }
826
827 void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
828 {
829 KIO::CopyJob* job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
830 KJobWidgets::setWindow(job, this);
831
832 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
833 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
834 KIO::FileUndoManager::self()->recordCopyJob(job);
835
836 }
837
838 void DolphinView::paste()
839 {
840 pasteToUrl(url());
841 }
842
843 void DolphinView::pasteIntoFolder()
844 {
845 const KFileItemList items = selectedItems();
846 if ((items.count() == 1) && items.first().isDir()) {
847 pasteToUrl(items.first().url());
848 }
849 }
850
851 void DolphinView::duplicateSelectedItems()
852 {
853 const KFileItemList itemList = selectedItems();
854 if (itemList.isEmpty()) {
855 return;
856 }
857
858 const QMimeDatabase db;
859
860 // Duplicate all selected items and append "copy" to the end of the file name
861 // but before the filename extension, if present
862 QList<QUrl> newSelection;
863 for (const auto &item : itemList) {
864 const QUrl originalURL = item.url();
865 const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
866 const QString originalFileName = item.name();
867
868 QString extension = db.suffixForFileName(originalFileName);
869
870 QUrl duplicateURL = originalURL;
871
872 // No extension; new filename is "<oldfilename> copy"
873 if (extension.isEmpty()) {
874 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFileName));
875 // There's an extension; new filename is "<oldfilename> copy.<extension>"
876 } else {
877 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
878 extension = QLatin1String(".") + extension;
879 const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size());
880 // Preserve file's original filename extension in case the casing differs
881 // from what QMimeDatabase::suffixForFileName() returned
882 const QString originalExtension = originalFileName.right(extension.size());
883 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension);
884 }
885
886 KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL);
887 KJobWidgets::setWindow(job, this);
888
889 if (job) {
890 newSelection << duplicateURL;
891 KIO::FileUndoManager::self()->recordCopyJob(job);
892 }
893 }
894
895 forceUrlsSelection(newSelection.first(), newSelection);
896 }
897
898 void DolphinView::stopLoading()
899 {
900 m_model->cancelDirectoryLoading();
901 }
902
903 void DolphinView::updatePalette()
904 {
905 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
906 if (!m_active) {
907 color.setAlpha(150);
908 }
909
910 QWidget* viewport = m_container->viewport();
911 if (viewport) {
912 QPalette palette;
913 palette.setColor(viewport->backgroundRole(), color);
914 viewport->setPalette(palette);
915 }
916
917 update();
918 }
919
920 void DolphinView::abortTwoClicksRenaming()
921 {
922 m_twoClicksRenamingItemUrl.clear();
923 m_twoClicksRenamingTimer->stop();
924 }
925
926 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
927 {
928 switch (event->type()) {
929 case QEvent::PaletteChange:
930 updatePalette();
931 QPixmapCache::clear();
932 break;
933
934 case QEvent::WindowActivate:
935 case QEvent::WindowDeactivate:
936 updatePalette();
937 break;
938
939 case QEvent::KeyPress:
940 hideToolTip(ToolTipManager::HideBehavior::Instantly);
941 if (GeneralSettings::useTabForSwitchingSplitView()) {
942 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
943 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
944 Q_EMIT toggleActiveViewRequested();
945 return true;
946 }
947 }
948 break;
949 case QEvent::FocusIn:
950 if (watched == m_container) {
951 setActive(true);
952 }
953 break;
954
955 case QEvent::GraphicsSceneDragEnter:
956 if (watched == m_view) {
957 m_dragging = true;
958 abortTwoClicksRenaming();
959 }
960 break;
961
962 case QEvent::GraphicsSceneDragLeave:
963 if (watched == m_view) {
964 m_dragging = false;
965 }
966 break;
967
968 case QEvent::GraphicsSceneDrop:
969 if (watched == m_view) {
970 m_dragging = false;
971 }
972 break;
973
974 case QEvent::ToolTip:
975 tryShowNameToolTip(static_cast<QHelpEvent*>(event));
976
977 default:
978 break;
979 }
980
981 return QWidget::eventFilter(watched, event);
982 }
983
984 void DolphinView::wheelEvent(QWheelEvent* event)
985 {
986 if (event->modifiers().testFlag(Qt::ControlModifier)) {
987 const QPoint numDegrees = event->angleDelta() / 8;
988 const QPoint numSteps = numDegrees / 15;
989
990 setZoomLevel(zoomLevel() + numSteps.y());
991 event->accept();
992 } else {
993 event->ignore();
994 }
995 }
996
997 void DolphinView::hideEvent(QHideEvent* event)
998 {
999 hideToolTip();
1000 QWidget::hideEvent(event);
1001 }
1002
1003 bool DolphinView::event(QEvent* event)
1004 {
1005 if (event->type() == QEvent::WindowDeactivate) {
1006 /* See Bug 297355
1007 * Dolphin leaves file preview tooltips open even when is not visible.
1008 *
1009 * Hide tool-tip when Dolphin loses focus.
1010 */
1011 hideToolTip();
1012 abortTwoClicksRenaming();
1013 }
1014
1015 return QWidget::event(event);
1016 }
1017
1018 void DolphinView::activate()
1019 {
1020 setActive(true);
1021 }
1022
1023 void DolphinView::slotItemActivated(int index)
1024 {
1025 abortTwoClicksRenaming();
1026
1027 const KFileItem item = m_model->fileItem(index);
1028 if (!item.isNull()) {
1029 Q_EMIT itemActivated(item);
1030 }
1031 }
1032
1033 void DolphinView::slotItemsActivated(const KItemSet &indexes)
1034 {
1035 Q_ASSERT(indexes.count() >= 2);
1036
1037 abortTwoClicksRenaming();
1038
1039 const auto modifiers = QGuiApplication::keyboardModifiers();
1040
1041 if (indexes.count() > 5) {
1042 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
1043 #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
1044 const int answer = KMessageBox::warningTwoActions(this, question, {},
1045 #else
1046 const int answer = KMessageBox::warningYesNo(this, question, {},
1047 #endif
1048 KGuiItem(i18ncp("@action:button", "Open %1 Item", "Open %1 Items", indexes.count()),
1049 QStringLiteral("document-open")),
1050 KStandardGuiItem::cancel());
1051 #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
1052 if (answer != KMessageBox::PrimaryAction) {
1053 #else
1054 if (answer != KMessageBox::Yes) {
1055 #endif
1056 return;
1057 }
1058 }
1059
1060 KFileItemList items;
1061 items.reserve(indexes.count());
1062
1063 for (int index : indexes) {
1064 KFileItem item = m_model->fileItem(index);
1065 const QUrl& url = openItemAsFolderUrl(item);
1066
1067 if (!url.isEmpty()) {
1068 // Open folders in new tabs or in new windows depending on the modifier
1069 // The ctrl+shift behavior is ignored because we are handling multiple items
1070 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1071 if (modifiers & Qt::ShiftModifier && !(modifiers & Qt::ControlModifier)) {
1072 Q_EMIT windowRequested(url);
1073 } else {
1074 Q_EMIT tabRequested(url);
1075 }
1076 } else {
1077 items.append(item);
1078 }
1079 }
1080
1081 if (items.count() == 1) {
1082 Q_EMIT itemActivated(items.first());
1083 } else if (items.count() > 1) {
1084 Q_EMIT itemsActivated(items);
1085 }
1086 }
1087
1088 void DolphinView::slotItemMiddleClicked(int index)
1089 {
1090 const KFileItem& item = m_model->fileItem(index);
1091 const QUrl& url = openItemAsFolderUrl(item);
1092 const auto modifiers = QGuiApplication::keyboardModifiers();
1093 if (!url.isEmpty()) {
1094 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1095 if (modifiers & Qt::ShiftModifier) {
1096 Q_EMIT activeTabRequested(url);
1097 } else {
1098 Q_EMIT tabRequested(url);
1099 }
1100 } else if (isTabsForFilesEnabled()) {
1101 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1102 if (modifiers & Qt::ShiftModifier) {
1103 Q_EMIT activeTabRequested(item.url());
1104 } else {
1105 Q_EMIT tabRequested(item.url());
1106 }
1107 }
1108 }
1109
1110 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
1111 {
1112 // Force emit of a selection changed signal before we request the
1113 // context menu, to update the edit-actions first. (See Bug 294013)
1114 if (m_selectionChangedTimer->isActive()) {
1115 emitSelectionChangedSignal();
1116 }
1117
1118 const KFileItem item = m_model->fileItem(index);
1119 Q_EMIT requestContextMenu(pos.toPoint(), item, selectedItems(), url());
1120 }
1121
1122 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
1123 {
1124 Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), selectedItems(), url());
1125 }
1126
1127 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
1128 {
1129 ViewProperties props(viewPropertiesUrl());
1130
1131 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
1132
1133 KItemListView* view = m_container->controller()->view();
1134 const QList<QByteArray> visibleRolesSet = view->visibleRoles();
1135
1136 bool indexingEnabled = false;
1137 #if HAVE_BALOO
1138 Baloo::IndexerConfig config;
1139 indexingEnabled = config.fileIndexingEnabled();
1140 #endif
1141
1142 QString groupName;
1143 QMenu* groupMenu = nullptr;
1144
1145 // Add all roles to the menu that can be shown or hidden by the user
1146 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
1147 for (const KFileItemModel::RoleInfo& info : rolesInfo) {
1148 if (info.role == "text") {
1149 // It should not be possible to hide the "text" role
1150 continue;
1151 }
1152
1153 const QString text = m_model->roleDescription(info.role);
1154 QAction* action = nullptr;
1155 if (info.group.isEmpty()) {
1156 action = menu->addAction(text);
1157 } else {
1158 if (!groupMenu || info.group != groupName) {
1159 groupName = info.group;
1160 groupMenu = menu->addMenu(groupName);
1161 }
1162
1163 action = groupMenu->addAction(text);
1164 }
1165
1166 action->setCheckable(true);
1167 action->setChecked(visibleRolesSet.contains(info.role));
1168 action->setData(info.role);
1169
1170 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
1171 (info.requiresBaloo) ||
1172 (info.requiresIndexer && indexingEnabled);
1173 action->setEnabled(enable);
1174 }
1175
1176 menu->addSeparator();
1177
1178 QActionGroup* widthsGroup = new QActionGroup(menu);
1179 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
1180
1181 QAction* toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding"));
1182 toggleSidePaddingAction->setCheckable(true);
1183 toggleSidePaddingAction->setChecked(view->header()->sidePadding() > 0);
1184
1185 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1186 autoAdjustWidthsAction->setCheckable(true);
1187 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1188 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1189
1190 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1191 customWidthsAction->setCheckable(true);
1192 customWidthsAction->setChecked(!autoColumnWidths);
1193 customWidthsAction->setActionGroup(widthsGroup);
1194
1195 QAction* action = menu->exec(pos.toPoint());
1196 if (menu && action) {
1197 KItemListHeader* header = view->header();
1198
1199 if (action == autoAdjustWidthsAction) {
1200 // Clear the column-widths from the viewproperties and turn on
1201 // the automatic resizing of the columns
1202 props.setHeaderColumnWidths(QList<int>());
1203 header->setAutomaticColumnResizing(true);
1204 } else if (action == customWidthsAction) {
1205 // Apply the current column-widths as custom column-widths and turn
1206 // off the automatic resizing of the columns
1207 QList<int> columnWidths;
1208 const auto visibleRoles = view->visibleRoles();
1209 columnWidths.reserve(visibleRoles.count());
1210 for (const QByteArray& role : visibleRoles) {
1211 columnWidths.append(header->columnWidth(role));
1212 }
1213 props.setHeaderColumnWidths(columnWidths);
1214 header->setAutomaticColumnResizing(false);
1215 } else if (action == toggleSidePaddingAction) {
1216 header->setSidePadding(toggleSidePaddingAction->isChecked() ? 20 : 0);
1217 } else {
1218 // Show or hide the selected role
1219 const QByteArray selectedRole = action->data().toByteArray();
1220
1221 QList<QByteArray> visibleRoles = view->visibleRoles();
1222 if (action->isChecked()) {
1223 visibleRoles.append(selectedRole);
1224 } else {
1225 visibleRoles.removeOne(selectedRole);
1226 }
1227
1228 view->setVisibleRoles(visibleRoles);
1229 props.setVisibleRoles(visibleRoles);
1230
1231 QList<int> columnWidths;
1232 if (!header->automaticColumnResizing()) {
1233 const auto visibleRoles = view->visibleRoles();
1234 columnWidths.reserve(visibleRoles.count());
1235 for (const QByteArray& role : visibleRoles) {
1236 columnWidths.append(header->columnWidth(role));
1237 }
1238 }
1239 props.setHeaderColumnWidths(columnWidths);
1240 }
1241 }
1242
1243 delete menu;
1244 }
1245
1246 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1247 {
1248 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1249
1250 ViewProperties props(viewPropertiesUrl());
1251 QList<int> columnWidths = props.headerColumnWidths();
1252 if (columnWidths.count() != visibleRoles.count()) {
1253 columnWidths.clear();
1254 columnWidths.reserve(visibleRoles.count());
1255 const KItemListHeader* header = m_view->header();
1256 for (const QByteArray& role : visibleRoles) {
1257 const int width = header->columnWidth(role);
1258 columnWidths.append(width);
1259 }
1260 }
1261
1262 const int roleIndex = visibleRoles.indexOf(role);
1263 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1264 columnWidths[roleIndex] = current;
1265
1266 props.setHeaderColumnWidths(columnWidths);
1267 }
1268
1269 void DolphinView::slotSidePaddingWidthChanged(qreal width)
1270 {
1271 ViewProperties props(viewPropertiesUrl());
1272 DetailsModeSettings::setSidePadding(int(width));
1273 m_view->writeSettings();
1274 }
1275
1276 void DolphinView::slotItemHovered(int index)
1277 {
1278 const KFileItem item = m_model->fileItem(index);
1279
1280 if (GeneralSettings::showToolTips() && !m_dragging) {
1281 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1282 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1283 itemRect.moveTo(pos);
1284
1285 #if HAVE_BALOO
1286 auto nativeParent = nativeParentWidget();
1287 if (nativeParent) {
1288 m_toolTipManager->showToolTip(item, itemRect, nativeParent->windowHandle());
1289 }
1290 #endif
1291 }
1292
1293 Q_EMIT requestItemInfo(item);
1294 }
1295
1296 void DolphinView::slotItemUnhovered(int index)
1297 {
1298 Q_UNUSED(index)
1299 hideToolTip();
1300 Q_EMIT requestItemInfo(KFileItem());
1301 }
1302
1303 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1304 {
1305 QUrl destUrl;
1306 KFileItem destItem = m_model->fileItem(index);
1307 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1308 // Use the URL of the view as drop target if the item is no directory
1309 // or desktop-file
1310 destItem = m_model->rootItem();
1311 destUrl = url();
1312 } else {
1313 // The item represents a directory or desktop-file
1314 destUrl = destItem.mostLocalUrl();
1315 }
1316
1317 QDropEvent dropEvent(event->pos().toPoint(),
1318 event->possibleActions(),
1319 event->mimeData(),
1320 event->buttons(),
1321 event->modifiers());
1322 dropUrls(destUrl, &dropEvent, this);
1323
1324 setActive(true);
1325 }
1326
1327 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1328 {
1329 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1330
1331 if (job) {
1332 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1333
1334 if (destUrl == url()) {
1335 // Mark the dropped urls as selected.
1336 m_clearSelectionBeforeSelectingNewItems = true;
1337 m_markFirstNewlySelectedItemAsCurrent = true;
1338 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1339 }
1340 }
1341 }
1342
1343 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1344 {
1345 if (previous != nullptr) {
1346 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1347 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1348 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1349 m_versionControlObserver->setModel(nullptr);
1350 }
1351
1352 if (current) {
1353 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1354 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1355 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1356 m_versionControlObserver->setModel(fileItemModel);
1357 }
1358 }
1359
1360 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1361 {
1362 Q_UNUSED(itemIndex)
1363
1364 hideToolTip();
1365
1366 if (buttons & Qt::BackButton) {
1367 Q_EMIT goBackRequested();
1368 } else if (buttons & Qt::ForwardButton) {
1369 Q_EMIT goForwardRequested();
1370 }
1371 }
1372
1373 void DolphinView::slotSelectedItemTextPressed(int index)
1374 {
1375 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1376 const KFileItem item = m_model->fileItem(index);
1377 const KFileItemListProperties capabilities(KFileItemList() << item);
1378 if (capabilities.supportsMoving()) {
1379 m_twoClicksRenamingItemUrl = item.url();
1380 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1381 }
1382 }
1383 }
1384
1385 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1386 {
1387 slotItemCreated(to);
1388 }
1389
1390 void DolphinView::slotItemCreated(const QUrl& url)
1391 {
1392 if (m_markFirstNewlySelectedItemAsCurrent) {
1393 markUrlAsCurrent(url);
1394 m_markFirstNewlySelectedItemAsCurrent = false;
1395 }
1396 m_selectedUrls << url;
1397 }
1398
1399 void DolphinView::slotJobResult(KJob *job)
1400 {
1401 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
1402 Q_EMIT errorMessage(job->errorString());
1403 }
1404 if (!m_selectedUrls.isEmpty()) {
1405 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1406 }
1407 }
1408
1409 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1410 {
1411 const int currentCount = current.count();
1412 const int previousCount = previous.count();
1413 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1414 (currentCount > 0 && previousCount == 0);
1415
1416 // If nothing has been selected before and something got selected (or if something
1417 // was selected before and now nothing is selected) the selectionChangedSignal must
1418 // be emitted asynchronously as fast as possible to update the edit-actions.
1419 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1420 m_selectionChangedTimer->start();
1421 }
1422
1423 void DolphinView::emitSelectionChangedSignal()
1424 {
1425 m_selectionChangedTimer->stop();
1426 Q_EMIT selectionChanged(selectedItems());
1427 }
1428
1429 void DolphinView::slotStatJobResult(KJob *job)
1430 {
1431 int folderCount = 0;
1432 int fileCount = 0;
1433 KIO::filesize_t totalFileSize = 0;
1434 bool countFileSize = true;
1435
1436 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1437 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1438 // We have a precomputed value.
1439 totalFileSize = static_cast<KIO::filesize_t>(
1440 entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1441 countFileSize = false;
1442 }
1443
1444 const int itemCount = m_model->count();
1445 for (int i = 0; i < itemCount; ++i) {
1446 const KFileItem item = m_model->fileItem(i);
1447 if (item.isDir()) {
1448 ++folderCount;
1449 } else {
1450 ++fileCount;
1451 if (countFileSize) {
1452 totalFileSize += item.size();
1453 }
1454 }
1455 }
1456 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1457 }
1458
1459 void DolphinView::updateSortRole(const QByteArray& role)
1460 {
1461 ViewProperties props(viewPropertiesUrl());
1462 props.setSortRole(role);
1463
1464 KItemModelBase* model = m_container->controller()->model();
1465 model->setSortRole(role);
1466
1467 Q_EMIT sortRoleChanged(role);
1468 }
1469
1470 void DolphinView::updateSortOrder(Qt::SortOrder order)
1471 {
1472 ViewProperties props(viewPropertiesUrl());
1473 props.setSortOrder(order);
1474
1475 m_model->setSortOrder(order);
1476
1477 Q_EMIT sortOrderChanged(order);
1478 }
1479
1480 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1481 {
1482 ViewProperties props(viewPropertiesUrl());
1483 props.setSortFoldersFirst(foldersFirst);
1484
1485 m_model->setSortDirectoriesFirst(foldersFirst);
1486
1487 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1488 }
1489
1490 void DolphinView::updateSortHiddenLast(bool hiddenLast)
1491 {
1492 ViewProperties props(viewPropertiesUrl());
1493 props.setSortHiddenLast(hiddenLast);
1494
1495 m_model->setSortHiddenLast(hiddenLast);
1496
1497 Q_EMIT sortHiddenLastChanged(hiddenLast);
1498 }
1499
1500
1501 QPair<bool, QString> DolphinView::pasteInfo() const
1502 {
1503 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1504 QPair<bool, QString> info;
1505 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1506 return info;
1507 }
1508
1509 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1510 {
1511 m_tabsForFiles = tabsForFiles;
1512 }
1513
1514 bool DolphinView::isTabsForFilesEnabled() const
1515 {
1516 return m_tabsForFiles;
1517 }
1518
1519 bool DolphinView::itemsExpandable() const
1520 {
1521 return m_mode == DetailsView;
1522 }
1523
1524 bool DolphinView::isExpanded(const KFileItem& item) const
1525 {
1526 Q_ASSERT(item.isDir());
1527 Q_ASSERT(items().contains(item));
1528 if (!itemsExpandable()) {
1529 return false;
1530 }
1531 return m_model->isExpanded(m_model->index(item));
1532 }
1533
1534 void DolphinView::restoreState(QDataStream& stream)
1535 {
1536 // Read the version number of the view state and check if the version is supported.
1537 quint32 version = 0;
1538 stream >> version;
1539 if (version != 1) {
1540 // The version of the view state isn't supported, we can't restore it.
1541 return;
1542 }
1543
1544 // Restore the current item that had the keyboard focus
1545 stream >> m_currentItemUrl;
1546
1547 // Restore the previously selected items
1548 stream >> m_selectedUrls;
1549
1550 // Restore the view position
1551 stream >> m_restoredContentsPosition;
1552
1553 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1554 QSet<QUrl> urls;
1555 stream >> urls;
1556 m_model->restoreExpandedDirectories(urls);
1557 }
1558
1559 void DolphinView::saveState(QDataStream& stream)
1560 {
1561 stream << quint32(1); // View state version
1562
1563 // Save the current item that has the keyboard focus
1564 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1565 if (currentIndex != -1) {
1566 KFileItem item = m_model->fileItem(currentIndex);
1567 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1568 QUrl currentItemUrl = item.url();
1569 stream << currentItemUrl;
1570 } else {
1571 stream << QUrl();
1572 }
1573
1574 // Save the selected urls
1575 stream << selectedItems().urlList();
1576
1577 // Save view position
1578 const qreal x = m_container->horizontalScrollBar()->value();
1579 const qreal y = m_container->verticalScrollBar()->value();
1580 stream << QPoint(x, y);
1581
1582 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1583 stream << m_model->expandedDirectories();
1584 }
1585
1586 KFileItem DolphinView::rootItem() const
1587 {
1588 return m_model->rootItem();
1589 }
1590
1591 void DolphinView::setViewPropertiesContext(const QString& context)
1592 {
1593 m_viewPropertiesContext = context;
1594 }
1595
1596 QString DolphinView::viewPropertiesContext() const
1597 {
1598 return m_viewPropertiesContext;
1599 }
1600
1601 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1602 {
1603 if (item.isNull()) {
1604 return QUrl();
1605 }
1606
1607 QUrl url = item.targetUrl();
1608
1609 if (item.isDir()) {
1610 return url;
1611 }
1612
1613 if (item.isMimeTypeKnown()) {
1614 const QString& mimetype = item.mimetype();
1615
1616 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1617 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1618 // zip:/<path>/ when clicking on a zip file, etc.
1619 // The .protocol file specifies the mimetype that the kioslave handles.
1620 // Note that we don't use mimetype inheritance since we don't want to
1621 // open OpenDocument files as zip folders...
1622 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1623 if (!protocol.isEmpty()) {
1624 url.setScheme(protocol);
1625 return url;
1626 }
1627 }
1628
1629 if (mimetype == QLatin1String("application/x-desktop")) {
1630 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1631 KDesktopFile desktopFile(url.toLocalFile());
1632 if (desktopFile.hasLinkType()) {
1633 const QString linkUrl = desktopFile.readUrl();
1634 if (!linkUrl.startsWith(QLatin1String("http"))) {
1635 return QUrl::fromUserInput(linkUrl);
1636 }
1637 }
1638 }
1639 }
1640
1641 return QUrl();
1642 }
1643
1644 void DolphinView::resetZoomLevel()
1645 {
1646 ViewModeSettings settings{m_mode};
1647 settings.useDefaults(true);
1648 const int defaultIconSize = settings.iconSize();
1649 settings.useDefaults(false);
1650
1651 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize)));
1652 }
1653
1654 void DolphinView::observeCreatedItem(const QUrl& url)
1655 {
1656 if (m_active) {
1657 forceUrlsSelection(url, {url});
1658 }
1659 }
1660
1661 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1662 {
1663 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1664 Q_EMIT redirection(oldUrl, newUrl);
1665 m_url = newUrl; // #186947
1666 }
1667 }
1668
1669 void DolphinView::updateViewState()
1670 {
1671 if (m_currentItemUrl != QUrl()) {
1672 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1673
1674 // if there is a selection already, leave it that way
1675 if (!selectionManager->hasSelection()) {
1676 const int currentIndex = m_model->index(m_currentItemUrl);
1677 if (currentIndex != -1) {
1678 selectionManager->setCurrentItem(currentIndex);
1679
1680 // scroll to current item and reset the state
1681 if (m_scrollToCurrentItem) {
1682 m_view->scrollToItem(currentIndex);
1683 m_scrollToCurrentItem = false;
1684 }
1685 m_currentItemUrl = QUrl();
1686 } else {
1687 selectionManager->setCurrentItem(0);
1688 }
1689 } else {
1690 m_currentItemUrl = QUrl();
1691 }
1692 }
1693
1694 if (!m_restoredContentsPosition.isNull()) {
1695 const int x = m_restoredContentsPosition.x();
1696 const int y = m_restoredContentsPosition.y();
1697 m_restoredContentsPosition = QPoint();
1698
1699 m_container->horizontalScrollBar()->setValue(x);
1700 m_container->verticalScrollBar()->setValue(y);
1701 }
1702
1703 if (!m_selectedUrls.isEmpty()) {
1704 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1705
1706 // if there is a selection already, leave it that way
1707 if (!selectionManager->hasSelection()) {
1708 if (m_clearSelectionBeforeSelectingNewItems) {
1709 selectionManager->clearSelection();
1710 m_clearSelectionBeforeSelectingNewItems = false;
1711 }
1712
1713 KItemSet selectedItems = selectionManager->selectedItems();
1714
1715 QList<QUrl>::iterator it = m_selectedUrls.begin();
1716 while (it != m_selectedUrls.end()) {
1717 const int index = m_model->index(*it);
1718 if (index >= 0) {
1719 selectedItems.insert(index);
1720 it = m_selectedUrls.erase(it);
1721 } else {
1722 ++it;
1723 }
1724 }
1725
1726 if (!selectedItems.isEmpty()) {
1727 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1728 selectionManager->setSelectedItems(selectedItems);
1729 }
1730 }
1731 }
1732 }
1733
1734 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1735 {
1736 if (GeneralSettings::showToolTips()) {
1737 #if HAVE_BALOO
1738 m_toolTipManager->hideToolTip(behavior);
1739 #else
1740 Q_UNUSED(behavior)
1741 #endif
1742 } else if (m_mode == DolphinView::IconsView) {
1743 QToolTip::hideText();
1744 }
1745 }
1746
1747 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1748 {
1749 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1750
1751 // verify that only one item is selected
1752 if (selectionManager->selectedItems().count() == 1) {
1753 const int index = selectionManager->currentItem();
1754 const QUrl fileItemUrl = m_model->fileItem(index).url();
1755
1756 // check if the selected item was the same item that started the twoClicksRenaming
1757 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1758 renameSelectedItems();
1759 }
1760 }
1761 }
1762
1763 void DolphinView::slotTrashFileFinished(KJob* job)
1764 {
1765 if (job->error() == 0) {
1766 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1767 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1768 Q_EMIT errorMessage(job->errorString());
1769 }
1770 }
1771
1772 void DolphinView::slotDeleteFileFinished(KJob* job)
1773 {
1774 if (job->error() == 0) {
1775 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1776 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1777 Q_EMIT errorMessage(job->errorString());
1778 }
1779 }
1780
1781 void DolphinView::slotRenamingResult(KJob* job)
1782 {
1783 if (job->error()) {
1784 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1785 Q_ASSERT(copyJob);
1786 const QUrl newUrl = copyJob->destUrl();
1787 const int index = m_model->index(newUrl);
1788 if (index >= 0) {
1789 QHash<QByteArray, QVariant> data;
1790 const QUrl oldUrl = copyJob->srcUrls().at(0);
1791 data.insert("text", oldUrl.fileName());
1792 m_model->setData(index, data);
1793 }
1794 }
1795 }
1796
1797 void DolphinView::slotDirectoryLoadingStarted()
1798 {
1799 m_loadingState = LoadingState::Loading;
1800 updatePlaceholderLabel();
1801
1802 // Disable the writestate temporary until it can be determined in a fast way
1803 // in DolphinView::slotDirectoryLoadingCompleted()
1804 if (m_isFolderWritable) {
1805 m_isFolderWritable = false;
1806 Q_EMIT writeStateChanged(m_isFolderWritable);
1807 }
1808
1809 Q_EMIT directoryLoadingStarted();
1810 }
1811
1812 void DolphinView::slotDirectoryLoadingCompleted()
1813 {
1814 m_loadingState = LoadingState::Completed;
1815
1816 // Update the view-state. This has to be done asynchronously
1817 // because the view might not be in its final state yet.
1818 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1819
1820 // Update the placeholder label in case we found that the folder was empty
1821 // after loading it
1822
1823 Q_EMIT directoryLoadingCompleted();
1824
1825 updatePlaceholderLabel();
1826 updateWritableState();
1827 }
1828
1829 void DolphinView::slotDirectoryLoadingCanceled()
1830 {
1831 m_loadingState = LoadingState::Canceled;
1832
1833 updatePlaceholderLabel();
1834
1835 Q_EMIT directoryLoadingCanceled();
1836 }
1837
1838 void DolphinView::slotItemsChanged()
1839 {
1840 m_assureVisibleCurrentIndex = false;
1841 }
1842
1843 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1844 {
1845 Q_UNUSED(previous)
1846 Q_ASSERT(m_model->sortOrder() == current);
1847
1848 ViewProperties props(viewPropertiesUrl());
1849 props.setSortOrder(current);
1850
1851 Q_EMIT sortOrderChanged(current);
1852 }
1853
1854 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1855 {
1856 Q_UNUSED(previous)
1857 Q_ASSERT(m_model->sortRole() == current);
1858
1859 ViewProperties props(viewPropertiesUrl());
1860 props.setSortRole(current);
1861
1862 Q_EMIT sortRoleChanged(current);
1863 }
1864
1865 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1866 const QList<QByteArray>& previous)
1867 {
1868 Q_UNUSED(previous)
1869 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1870
1871 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1872
1873 m_visibleRoles = current;
1874
1875 ViewProperties props(viewPropertiesUrl());
1876 props.setVisibleRoles(m_visibleRoles);
1877
1878 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1879 }
1880
1881 void DolphinView::slotRoleEditingCanceled()
1882 {
1883 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1884 this, &DolphinView::slotRoleEditingFinished);
1885 }
1886
1887 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1888 {
1889 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1890 this, &DolphinView::slotRoleEditingFinished);
1891
1892 const KFileItemList items = selectedItems();
1893 if (items.count() != 1) {
1894 return;
1895 }
1896
1897 if (role == "text") {
1898 const KFileItem oldItem = items.first();
1899 const EditResult retVal = value.value<EditResult>();
1900 const QString newName = retVal.newName;
1901 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1902 const QUrl oldUrl = oldItem.url();
1903
1904 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1905 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1906
1907 #ifndef Q_OS_WIN
1908 //Confirm hiding file/directory by renaming inline
1909 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1910 KGuiItem yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden"));
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 }