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