]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Add new settings for permissions column format
[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 action->setToolTip(info.tooltip);
1171
1172 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (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(), event->possibleActions(), event->mimeData(), event->buttons(), event->modifiers());
1318 dropUrls(destUrl, &dropEvent, this);
1319
1320 setActive(true);
1321 }
1322
1323 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1324 {
1325 KIO::DropJob *job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1326
1327 if (job) {
1328 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1329
1330 if (destUrl == url()) {
1331 // Mark the dropped urls as selected.
1332 m_clearSelectionBeforeSelectingNewItems = true;
1333 m_markFirstNewlySelectedItemAsCurrent = true;
1334 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1335 }
1336 }
1337 }
1338
1339 void DolphinView::slotModelChanged(KItemModelBase *current, KItemModelBase *previous)
1340 {
1341 if (previous != nullptr) {
1342 Q_ASSERT(qobject_cast<KFileItemModel *>(previous));
1343 KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(previous);
1344 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1345 m_versionControlObserver->setModel(nullptr);
1346 }
1347
1348 if (current) {
1349 Q_ASSERT(qobject_cast<KFileItemModel *>(current));
1350 KFileItemModel *fileItemModel = static_cast<KFileItemModel *>(current);
1351 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1352 m_versionControlObserver->setModel(fileItemModel);
1353 }
1354 }
1355
1356 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1357 {
1358 Q_UNUSED(itemIndex)
1359
1360 hideToolTip();
1361
1362 if (buttons & Qt::BackButton) {
1363 Q_EMIT goBackRequested();
1364 } else if (buttons & Qt::ForwardButton) {
1365 Q_EMIT goForwardRequested();
1366 }
1367 }
1368
1369 void DolphinView::slotSelectedItemTextPressed(int index)
1370 {
1371 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1372 const KFileItem item = m_model->fileItem(index);
1373 const KFileItemListProperties capabilities(KFileItemList() << item);
1374 if (capabilities.supportsMoving()) {
1375 m_twoClicksRenamingItemUrl = item.url();
1376 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1377 }
1378 }
1379 }
1380
1381 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1382 {
1383 slotItemCreated(to);
1384 }
1385
1386 void DolphinView::slotItemCreated(const QUrl &url)
1387 {
1388 if (m_markFirstNewlySelectedItemAsCurrent) {
1389 markUrlAsCurrent(url);
1390 m_markFirstNewlySelectedItemAsCurrent = false;
1391 }
1392 m_selectedUrls << url;
1393 }
1394
1395 void DolphinView::slotJobResult(KJob *job)
1396 {
1397 if (job->error() && job->error() != KIO::ERR_USER_CANCELED) {
1398 Q_EMIT errorMessage(job->errorString());
1399 }
1400 if (!m_selectedUrls.isEmpty()) {
1401 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1402 }
1403 }
1404
1405 void DolphinView::slotSelectionChanged(const KItemSet &current, const KItemSet &previous)
1406 {
1407 m_selectNextItem = false;
1408 const int currentCount = current.count();
1409 const int previousCount = previous.count();
1410 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || (currentCount > 0 && previousCount == 0);
1411
1412 // If nothing has been selected before and something got selected (or if something
1413 // was selected before and now nothing is selected) the selectionChangedSignal must
1414 // be emitted asynchronously as fast as possible to update the edit-actions.
1415 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1416 m_selectionChangedTimer->start();
1417 }
1418
1419 void DolphinView::emitSelectionChangedSignal()
1420 {
1421 m_selectionChangedTimer->stop();
1422 Q_EMIT selectionChanged(selectedItems());
1423 }
1424
1425 void DolphinView::slotStatJobResult(KJob *job)
1426 {
1427 int folderCount = 0;
1428 int fileCount = 0;
1429 KIO::filesize_t totalFileSize = 0;
1430 bool countFileSize = true;
1431
1432 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1433 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1434 // We have a precomputed value.
1435 totalFileSize = static_cast<KIO::filesize_t>(entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1436 countFileSize = false;
1437 }
1438
1439 const int itemCount = m_model->count();
1440 for (int i = 0; i < itemCount; ++i) {
1441 const KFileItem item = m_model->fileItem(i);
1442 if (item.isDir()) {
1443 ++folderCount;
1444 } else {
1445 ++fileCount;
1446 if (countFileSize) {
1447 totalFileSize += item.size();
1448 }
1449 }
1450 }
1451 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1452 }
1453
1454 void DolphinView::updateSortRole(const QByteArray &role)
1455 {
1456 ViewProperties props(viewPropertiesUrl());
1457 props.setSortRole(role);
1458
1459 KItemModelBase *model = m_container->controller()->model();
1460 model->setSortRole(role);
1461
1462 Q_EMIT sortRoleChanged(role);
1463 }
1464
1465 void DolphinView::updateSortOrder(Qt::SortOrder order)
1466 {
1467 ViewProperties props(viewPropertiesUrl());
1468 props.setSortOrder(order);
1469
1470 m_model->setSortOrder(order);
1471
1472 Q_EMIT sortOrderChanged(order);
1473 }
1474
1475 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1476 {
1477 ViewProperties props(viewPropertiesUrl());
1478 props.setSortFoldersFirst(foldersFirst);
1479
1480 m_model->setSortDirectoriesFirst(foldersFirst);
1481
1482 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1483 }
1484
1485 void DolphinView::updateSortHiddenLast(bool hiddenLast)
1486 {
1487 ViewProperties props(viewPropertiesUrl());
1488 props.setSortHiddenLast(hiddenLast);
1489
1490 m_model->setSortHiddenLast(hiddenLast);
1491
1492 Q_EMIT sortHiddenLastChanged(hiddenLast);
1493 }
1494
1495 QPair<bool, QString> DolphinView::pasteInfo() const
1496 {
1497 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1498 QPair<bool, QString> info;
1499 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1500 return info;
1501 }
1502
1503 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1504 {
1505 m_tabsForFiles = tabsForFiles;
1506 }
1507
1508 bool DolphinView::isTabsForFilesEnabled() const
1509 {
1510 return m_tabsForFiles;
1511 }
1512
1513 bool DolphinView::itemsExpandable() const
1514 {
1515 return m_mode == DetailsView;
1516 }
1517
1518 bool DolphinView::isExpanded(const KFileItem &item) const
1519 {
1520 Q_ASSERT(item.isDir());
1521 Q_ASSERT(items().contains(item));
1522 if (!itemsExpandable()) {
1523 return false;
1524 }
1525 return m_model->isExpanded(m_model->index(item));
1526 }
1527
1528 void DolphinView::restoreState(QDataStream &stream)
1529 {
1530 // Read the version number of the view state and check if the version is supported.
1531 quint32 version = 0;
1532 stream >> version;
1533 if (version != 1) {
1534 // The version of the view state isn't supported, we can't restore it.
1535 return;
1536 }
1537
1538 // Restore the current item that had the keyboard focus
1539 stream >> m_currentItemUrl;
1540
1541 // Restore the previously selected items
1542 stream >> m_selectedUrls;
1543
1544 // Restore the view position
1545 stream >> m_restoredContentsPosition;
1546
1547 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1548 QSet<QUrl> urls;
1549 stream >> urls;
1550 m_model->restoreExpandedDirectories(urls);
1551 }
1552
1553 void DolphinView::saveState(QDataStream &stream)
1554 {
1555 stream << quint32(1); // View state version
1556
1557 // Save the current item that has the keyboard focus
1558 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1559 if (currentIndex != -1) {
1560 KFileItem item = m_model->fileItem(currentIndex);
1561 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1562 QUrl currentItemUrl = item.url();
1563 stream << currentItemUrl;
1564 } else {
1565 stream << QUrl();
1566 }
1567
1568 // Save the selected urls
1569 stream << selectedItems().urlList();
1570
1571 // Save view position
1572 const qreal x = m_container->horizontalScrollBar()->value();
1573 const qreal y = m_container->verticalScrollBar()->value();
1574 stream << QPoint(x, y);
1575
1576 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1577 stream << m_model->expandedDirectories();
1578 }
1579
1580 KFileItem DolphinView::rootItem() const
1581 {
1582 return m_model->rootItem();
1583 }
1584
1585 void DolphinView::setViewPropertiesContext(const QString &context)
1586 {
1587 m_viewPropertiesContext = context;
1588 }
1589
1590 QString DolphinView::viewPropertiesContext() const
1591 {
1592 return m_viewPropertiesContext;
1593 }
1594
1595 QUrl DolphinView::openItemAsFolderUrl(const KFileItem &item, const bool browseThroughArchives)
1596 {
1597 if (item.isNull()) {
1598 return QUrl();
1599 }
1600
1601 QUrl url = item.targetUrl();
1602
1603 if (item.isDir()) {
1604 return url;
1605 }
1606
1607 if (item.isMimeTypeKnown()) {
1608 const QString &mimetype = item.mimetype();
1609
1610 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1611 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1612 // zip:/<path>/ when clicking on a zip file, etc.
1613 // The .protocol file specifies the mimetype that the kioslave handles.
1614 // Note that we don't use mimetype inheritance since we don't want to
1615 // open OpenDocument files as zip folders...
1616 const QString &protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1617 if (!protocol.isEmpty()) {
1618 url.setScheme(protocol);
1619 return url;
1620 }
1621 }
1622
1623 if (mimetype == QLatin1String("application/x-desktop")) {
1624 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1625 KDesktopFile desktopFile(url.toLocalFile());
1626 if (desktopFile.hasLinkType()) {
1627 const QString linkUrl = desktopFile.readUrl();
1628 if (!linkUrl.startsWith(QLatin1String("http"))) {
1629 return QUrl::fromUserInput(linkUrl);
1630 }
1631 }
1632 }
1633 }
1634
1635 return QUrl();
1636 }
1637
1638 void DolphinView::resetZoomLevel()
1639 {
1640 ViewModeSettings settings{m_mode};
1641 settings.useDefaults(true);
1642 const int defaultIconSize = settings.iconSize();
1643 settings.useDefaults(false);
1644
1645 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize)));
1646 }
1647
1648 void DolphinView::observeCreatedItem(const QUrl &url)
1649 {
1650 if (m_active) {
1651 forceUrlsSelection(url, {url});
1652 }
1653 }
1654
1655 void DolphinView::slotDirectoryRedirection(const QUrl &oldUrl, const QUrl &newUrl)
1656 {
1657 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1658 Q_EMIT redirection(oldUrl, newUrl);
1659 m_url = newUrl; // #186947
1660 }
1661 }
1662
1663 void DolphinView::updateViewState()
1664 {
1665 if (m_currentItemUrl != QUrl()) {
1666 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1667
1668 // if there is a selection already, leave it that way
1669 if (!selectionManager->hasSelection()) {
1670 const int currentIndex = m_model->index(m_currentItemUrl);
1671 if (currentIndex != -1) {
1672 selectionManager->setCurrentItem(currentIndex);
1673
1674 // scroll to current item and reset the state
1675 if (m_scrollToCurrentItem) {
1676 m_view->scrollToItem(currentIndex);
1677 m_scrollToCurrentItem = false;
1678 }
1679 m_currentItemUrl = QUrl();
1680 } else {
1681 selectionManager->setCurrentItem(0);
1682 }
1683 } else {
1684 m_currentItemUrl = QUrl();
1685 }
1686 }
1687
1688 if (!m_restoredContentsPosition.isNull()) {
1689 const int x = m_restoredContentsPosition.x();
1690 const int y = m_restoredContentsPosition.y();
1691 m_restoredContentsPosition = QPoint();
1692
1693 m_container->horizontalScrollBar()->setValue(x);
1694 m_container->verticalScrollBar()->setValue(y);
1695 }
1696
1697 if (!m_selectedUrls.isEmpty()) {
1698 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1699
1700 // if there is a selection already, leave it that way
1701 if (!selectionManager->hasSelection()) {
1702 if (m_clearSelectionBeforeSelectingNewItems) {
1703 selectionManager->clearSelection();
1704 m_clearSelectionBeforeSelectingNewItems = false;
1705 }
1706
1707 KItemSet selectedItems = selectionManager->selectedItems();
1708
1709 QList<QUrl>::iterator it = m_selectedUrls.begin();
1710 while (it != m_selectedUrls.end()) {
1711 const int index = m_model->index(*it);
1712 if (index >= 0) {
1713 selectedItems.insert(index);
1714 it = m_selectedUrls.erase(it);
1715 } else {
1716 ++it;
1717 }
1718 }
1719
1720 if (!selectedItems.isEmpty()) {
1721 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1722 selectionManager->setSelectedItems(selectedItems);
1723 }
1724 }
1725 }
1726 }
1727
1728 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1729 {
1730 if (GeneralSettings::showToolTips()) {
1731 #if HAVE_BALOO
1732 m_toolTipManager->hideToolTip(behavior);
1733 #else
1734 Q_UNUSED(behavior)
1735 #endif
1736 } else if (m_mode == DolphinView::IconsView) {
1737 QToolTip::hideText();
1738 }
1739 }
1740
1741 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1742 {
1743 const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1744
1745 // verify that only one item is selected
1746 if (selectionManager->selectedItems().count() == 1) {
1747 const int index = selectionManager->currentItem();
1748 const QUrl fileItemUrl = m_model->fileItem(index).url();
1749
1750 // check if the selected item was the same item that started the twoClicksRenaming
1751 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1752 renameSelectedItems();
1753 }
1754 }
1755 }
1756
1757 void DolphinView::slotTrashFileFinished(KJob *job)
1758 {
1759 if (job->error() == 0) {
1760 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1761 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1762 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1763 Q_EMIT errorMessage(job->errorString());
1764 }
1765 }
1766
1767 void DolphinView::slotDeleteFileFinished(KJob *job)
1768 {
1769 if (job->error() == 0) {
1770 selectNextItem(); // Fixes BUG: 419914 via selecting next item
1771 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1772 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1773 Q_EMIT errorMessage(job->errorString());
1774 }
1775 }
1776
1777 void DolphinView::selectNextItem()
1778 {
1779 if (m_active && m_selectNextItem) {
1780 KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
1781 if (selectedItems().isEmpty()) {
1782 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1783 return;
1784 }
1785 const auto lastSelectedIndex = m_model->index(selectedItems().last());
1786 if (lastSelectedIndex < 0) {
1787 Q_ASSERT_X(false, "DolphinView", "Selecting the next item failed.");
1788 return;
1789 }
1790 auto nextItem = lastSelectedIndex + 1;
1791 if (nextItem >= itemsCount()) {
1792 nextItem = lastSelectedIndex - selectedItemsCount();
1793 }
1794 if (nextItem >= 0) {
1795 selectionManager->setSelected(nextItem, 1);
1796 }
1797 m_selectNextItem = false;
1798 }
1799 }
1800
1801 void DolphinView::slotRenamingResult(KJob *job)
1802 {
1803 if (job->error()) {
1804 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1805 Q_ASSERT(copyJob);
1806 const QUrl newUrl = copyJob->destUrl();
1807 const int index = m_model->index(newUrl);
1808 if (index >= 0) {
1809 QHash<QByteArray, QVariant> data;
1810 const QUrl oldUrl = copyJob->srcUrls().at(0);
1811 data.insert("text", oldUrl.fileName());
1812 m_model->setData(index, data);
1813 }
1814 }
1815 }
1816
1817 void DolphinView::slotDirectoryLoadingStarted()
1818 {
1819 m_loadingState = LoadingState::Loading;
1820 updatePlaceholderLabel();
1821
1822 // Disable the writestate temporary until it can be determined in a fast way
1823 // in DolphinView::slotDirectoryLoadingCompleted()
1824 if (m_isFolderWritable) {
1825 m_isFolderWritable = false;
1826 Q_EMIT writeStateChanged(m_isFolderWritable);
1827 }
1828
1829 Q_EMIT directoryLoadingStarted();
1830 }
1831
1832 void DolphinView::slotDirectoryLoadingCompleted()
1833 {
1834 m_loadingState = LoadingState::Completed;
1835
1836 // Update the view-state. This has to be done asynchronously
1837 // because the view might not be in its final state yet.
1838 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1839
1840 // Update the placeholder label in case we found that the folder was empty
1841 // after loading it
1842
1843 Q_EMIT directoryLoadingCompleted();
1844
1845 updatePlaceholderLabel();
1846 updateWritableState();
1847 }
1848
1849 void DolphinView::slotDirectoryLoadingCanceled()
1850 {
1851 m_loadingState = LoadingState::Canceled;
1852
1853 updatePlaceholderLabel();
1854
1855 Q_EMIT directoryLoadingCanceled();
1856 }
1857
1858 void DolphinView::slotItemsChanged()
1859 {
1860 m_assureVisibleCurrentIndex = false;
1861 }
1862
1863 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1864 {
1865 Q_UNUSED(previous)
1866 Q_ASSERT(m_model->sortOrder() == current);
1867
1868 ViewProperties props(viewPropertiesUrl());
1869 props.setSortOrder(current);
1870
1871 Q_EMIT sortOrderChanged(current);
1872 }
1873
1874 void DolphinView::slotSortRoleChangedByHeader(const QByteArray &current, const QByteArray &previous)
1875 {
1876 Q_UNUSED(previous)
1877 Q_ASSERT(m_model->sortRole() == current);
1878
1879 ViewProperties props(viewPropertiesUrl());
1880 props.setSortRole(current);
1881
1882 Q_EMIT sortRoleChanged(current);
1883 }
1884
1885 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray> &current, const QList<QByteArray> &previous)
1886 {
1887 Q_UNUSED(previous)
1888 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1889
1890 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1891
1892 m_visibleRoles = current;
1893
1894 ViewProperties props(viewPropertiesUrl());
1895 props.setVisibleRoles(m_visibleRoles);
1896
1897 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1898 }
1899
1900 void DolphinView::slotRoleEditingCanceled()
1901 {
1902 disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
1903 }
1904
1905 void DolphinView::slotRoleEditingFinished(int index, const QByteArray &role, const QVariant &value)
1906 {
1907 disconnect(m_view, &DolphinItemListView::roleEditingFinished, this, &DolphinView::slotRoleEditingFinished);
1908
1909 const KFileItemList items = selectedItems();
1910 if (items.count() != 1) {
1911 return;
1912 }
1913
1914 if (role == "text") {
1915 const KFileItem oldItem = items.first();
1916 const EditResult retVal = value.value<EditResult>();
1917 const QString newName = retVal.newName;
1918 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1919 const QUrl oldUrl = oldItem.url();
1920
1921 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1922 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1923
1924 #ifndef Q_OS_WIN
1925 // Confirm hiding file/directory by renaming inline
1926 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1927 KGuiItem yesGuiItem(i18nc("@action:button", "Rename and Hide"), QStringLiteral("view-hidden"));
1928
1929 #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
1930 const auto code =
1931 KMessageBox::questionTwoActions(this,
1932 #else
1933 const auto code =
1934 KMessageBox::questionYesNo(this,
1935 #endif
1936 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1937 "Do you still want to rename it?")
1938 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1939 "Do you still want to rename it?"),
1940 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1941 yesGuiItem,
1942 KStandardGuiItem::cancel(),
1943 QStringLiteral("ConfirmHide"));
1944
1945 #if KWIDGETSADDONS_VERSION >= QT_VERSION_CHECK(5, 100, 0)
1946 if (code == KMessageBox::SecondaryAction) {
1947 #else
1948 if (code == KMessageBox::No) {
1949 #endif
1950 return;
1951 }
1952 }
1953 #endif
1954
1955 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1956 if (!newNameExistsAlready && m_model->index(oldUrl) == index) {
1957 // Only change the data in the model if no item with the new name
1958 // is in the model yet. If there is an item with the new name
1959 // already, calling KIO::CopyJob will open a dialog
1960 // asking for a new name, and KFileItemModel will update the
1961 // data when the dir lister signals that the file name has changed.
1962 QHash<QByteArray, QVariant> data;
1963 data.insert(role, retVal.newName);
1964 m_model->setData(index, data);
1965 }
1966
1967 KIO::Job *job = KIO::moveAs(oldUrl, newUrl);
1968 KJobWidgets::setWindow(job, this);
1969 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1970 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1971
1972 forceUrlsSelection(newUrl, {newUrl});
1973
1974 if (!newNameExistsAlready) {
1975 // Only connect the result signal if there is no item with the new name
1976 // in the model yet, see bug 328262.
1977 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1978 }
1979 }
1980 if (retVal.direction != EditDone) {
1981 const short indexShift = retVal.direction == EditNext ? 1 : -1;
1982 m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect);
1983 m_container->controller()->selectionManager()->setSelected(index + indexShift, 1, KItemListSelectionManager::Select);
1984 renameSelectedItems();
1985 }
1986 }
1987 }
1988
1989 void DolphinView::loadDirectory(const QUrl &url, bool reload)
1990 {
1991 if (!url.isValid()) {
1992 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1993 if (location.isEmpty()) {
1994 Q_EMIT errorMessage(i18nc("@info:status", "The location is empty."));
1995 } else {
1996 Q_EMIT errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1997 }
1998 return;
1999 }
2000
2001 if (reload) {
2002 m_model->refreshDirectory(url);
2003 } else {
2004 m_model->loadDirectory(url);
2005 }
2006 }
2007
2008 void DolphinView::applyViewProperties()
2009 {
2010 const ViewProperties props(viewPropertiesUrl());
2011 applyViewProperties(props);
2012 }
2013
2014 void DolphinView::applyViewProperties(const ViewProperties &props)
2015 {
2016 m_view->beginTransaction();
2017
2018 const Mode mode = props.viewMode();
2019 if (m_mode != mode) {
2020 const Mode previousMode = m_mode;
2021 m_mode = mode;
2022
2023 // Changing the mode might result in changing
2024 // the zoom level. Remember the old zoom level so
2025 // that zoomLevelChanged() can get emitted.
2026 const int oldZoomLevel = m_view->zoomLevel();
2027 applyModeToView();
2028
2029 Q_EMIT modeChanged(m_mode, previousMode);
2030
2031 if (m_view->zoomLevel() != oldZoomLevel) {
2032 Q_EMIT zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
2033 }
2034 }
2035
2036 const bool hiddenFilesShown = props.hiddenFilesShown();
2037 if (hiddenFilesShown != m_model->showHiddenFiles()) {
2038 m_model->setShowHiddenFiles(hiddenFilesShown);
2039 Q_EMIT hiddenFilesShownChanged(hiddenFilesShown);
2040 }
2041
2042 const bool groupedSorting = props.groupedSorting();
2043 if (groupedSorting != m_model->groupedSorting()) {
2044 m_model->setGroupedSorting(groupedSorting);
2045 Q_EMIT groupedSortingChanged(groupedSorting);
2046 }
2047
2048 const QByteArray sortRole = props.sortRole();
2049 if (sortRole != m_model->sortRole()) {
2050 m_model->setSortRole(sortRole);
2051 Q_EMIT sortRoleChanged(sortRole);
2052 }
2053
2054 const Qt::SortOrder sortOrder = props.sortOrder();
2055 if (sortOrder != m_model->sortOrder()) {
2056 m_model->setSortOrder(sortOrder);
2057 Q_EMIT sortOrderChanged(sortOrder);
2058 }
2059
2060 const bool sortFoldersFirst = props.sortFoldersFirst();
2061 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
2062 m_model->setSortDirectoriesFirst(sortFoldersFirst);
2063 Q_EMIT sortFoldersFirstChanged(sortFoldersFirst);
2064 }
2065
2066 const bool sortHiddenLast = props.sortHiddenLast();
2067 if (sortHiddenLast != m_model->sortHiddenLast()) {
2068 m_model->setSortHiddenLast(sortHiddenLast);
2069 Q_EMIT sortHiddenLastChanged(sortHiddenLast);
2070 }
2071
2072 const QList<QByteArray> visibleRoles = props.visibleRoles();
2073 if (visibleRoles != m_visibleRoles) {
2074 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
2075 m_visibleRoles = visibleRoles;
2076 m_view->setVisibleRoles(visibleRoles);
2077 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
2078 }
2079
2080 const bool previewsShown = props.previewsShown();
2081 if (previewsShown != m_view->previewsShown()) {
2082 const int oldZoomLevel = zoomLevel();
2083
2084 m_view->setPreviewsShown(previewsShown);
2085 Q_EMIT previewsShownChanged(previewsShown);
2086
2087 // Changing the preview-state might result in a changed zoom-level
2088 if (oldZoomLevel != zoomLevel()) {
2089 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
2090 }
2091 }
2092
2093 KItemListView *itemListView = m_container->controller()->view();
2094 if (itemListView->isHeaderVisible()) {
2095 KItemListHeader *header = itemListView->header();
2096 const QList<int> headerColumnWidths = props.headerColumnWidths();
2097 const int rolesCount = m_visibleRoles.count();
2098 if (headerColumnWidths.count() == rolesCount) {
2099 header->setAutomaticColumnResizing(false);
2100
2101 QHash<QByteArray, qreal> columnWidths;
2102 for (int i = 0; i < rolesCount; ++i) {
2103 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
2104 }
2105 header->setColumnWidths(columnWidths);
2106 } else {
2107 header->setAutomaticColumnResizing(true);
2108 }
2109 header->setSidePadding(DetailsModeSettings::sidePadding());
2110 }
2111
2112 m_view->endTransaction();
2113 }
2114
2115 void DolphinView::applyModeToView()
2116 {
2117 switch (m_mode) {
2118 case IconsView:
2119 m_view->setItemLayout(KFileItemListView::IconsLayout);
2120 break;
2121 case CompactView:
2122 m_view->setItemLayout(KFileItemListView::CompactLayout);
2123 break;
2124 case DetailsView:
2125 m_view->setItemLayout(KFileItemListView::DetailsLayout);
2126 break;
2127 default:
2128 Q_ASSERT(false);
2129 break;
2130 }
2131 }
2132
2133 void DolphinView::pasteToUrl(const QUrl &url)
2134 {
2135 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
2136 KJobWidgets::setWindow(job, this);
2137 m_clearSelectionBeforeSelectingNewItems = true;
2138 m_markFirstNewlySelectedItemAsCurrent = true;
2139 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
2140 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotJobResult);
2141 }
2142
2143 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
2144 {
2145 QList<QUrl> urls;
2146
2147 const KFileItemList items = selectedItems();
2148 urls.reserve(items.count());
2149 for (const KFileItem &item : items) {
2150 urls.append(item.url());
2151 }
2152
2153 if (itemsExpandable()) {
2154 // TODO: Check if we still need KDirModel for this in KDE 5.0
2155 urls = KDirModel::simplifiedUrlList(urls);
2156 }
2157
2158 return urls;
2159 }
2160
2161 QMimeData *DolphinView::selectionMimeData() const
2162 {
2163 const KItemListSelectionManager *selectionManager = m_container->controller()->selectionManager();
2164 const KItemSet selectedIndexes = selectionManager->selectedItems();
2165
2166 return m_model->createMimeData(selectedIndexes);
2167 }
2168
2169 void DolphinView::updateWritableState()
2170 {
2171 const bool wasFolderWritable = m_isFolderWritable;
2172 m_isFolderWritable = false;
2173
2174 KFileItem item = m_model->rootItem();
2175 if (item.isNull()) {
2176 // Try to find out if the URL is writable even if the "root item" is
2177 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2178 item = KFileItem(url());
2179 item.setDelayedMimeTypes(true);
2180 }
2181
2182 KFileItemListProperties capabilities(KFileItemList() << item);
2183 m_isFolderWritable = capabilities.supportsWriting();
2184
2185 if (m_isFolderWritable != wasFolderWritable) {
2186 Q_EMIT writeStateChanged(m_isFolderWritable);
2187 }
2188 }
2189
2190 QUrl DolphinView::viewPropertiesUrl() const
2191 {
2192 if (m_viewPropertiesContext.isEmpty()) {
2193 return m_url;
2194 }
2195
2196 QUrl url;
2197 url.setScheme(m_url.scheme());
2198 url.setPath(m_viewPropertiesContext);
2199 return url;
2200 }
2201
2202 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl> &urls)
2203 {
2204 forceUrlsSelection(urls.first(), urls);
2205 }
2206
2207 void DolphinView::forceUrlsSelection(const QUrl &current, const QList<QUrl> &selected)
2208 {
2209 clearSelection();
2210 m_clearSelectionBeforeSelectingNewItems = true;
2211 markUrlAsCurrent(current);
2212 markUrlsAsSelected(selected);
2213 }
2214
2215 void DolphinView::copyPathToClipboard()
2216 {
2217 const KFileItemList list = selectedItems();
2218 if (list.isEmpty()) {
2219 return;
2220 }
2221 const KFileItem &item = list.at(0);
2222 QString path = item.localPath();
2223 if (path.isEmpty()) {
2224 path = item.url().toDisplayString();
2225 }
2226 QClipboard *clipboard = QApplication::clipboard();
2227 if (clipboard == nullptr) {
2228 return;
2229 }
2230 clipboard->setText(path);
2231 }
2232
2233 void DolphinView::slotIncreaseZoom()
2234 {
2235 setZoomLevel(zoomLevel() + 1);
2236 }
2237
2238 void DolphinView::slotDecreaseZoom()
2239 {
2240 setZoomLevel(zoomLevel() - 1);
2241 }
2242
2243 void DolphinView::slotSwipeUp()
2244 {
2245 Q_EMIT goUpRequested();
2246 }
2247
2248 void DolphinView::showLoadingPlaceholder()
2249 {
2250 m_placeholderLabel->setText(i18n("Loading..."));
2251 m_placeholderLabel->setVisible(true);
2252 }
2253
2254 void DolphinView::updatePlaceholderLabel()
2255 {
2256 m_showLoadingPlaceholderTimer->stop();
2257 if (itemsCount() > 0) {
2258 m_placeholderLabel->setVisible(false);
2259 return;
2260 }
2261
2262 if (m_loadingState == LoadingState::Loading) {
2263 m_placeholderLabel->setVisible(false);
2264 m_showLoadingPlaceholderTimer->start();
2265 return;
2266 }
2267
2268 if (m_loadingState == LoadingState::Canceled) {
2269 m_placeholderLabel->setText(i18n("Loading canceled"));
2270 } else if (!nameFilter().isEmpty()) {
2271 m_placeholderLabel->setText(i18n("No items matching the filter"));
2272 } else if (m_url.scheme() == QLatin1String("baloosearch") || m_url.scheme() == QLatin1String("filenamesearch")) {
2273 m_placeholderLabel->setText(i18n("No items matching the search"));
2274 } else if (m_url.scheme() == QLatin1String("trash") && m_url.path() == QLatin1String("/")) {
2275 m_placeholderLabel->setText(i18n("Trash is empty"));
2276 } else if (m_url.scheme() == QLatin1String("tags")) {
2277 if (m_url.path() == QLatin1Char('/')) {
2278 m_placeholderLabel->setText(i18n("No tags"));
2279 } else {
2280 const QString tagName = m_url.path().mid(1); // Remove leading /
2281 m_placeholderLabel->setText(i18n("No files tagged with \"%1\"", tagName));
2282 }
2283
2284 } else if (m_url.scheme() == QLatin1String("recentlyused")) {
2285 m_placeholderLabel->setText(i18n("No recently used items"));
2286 } else if (m_url.scheme() == QLatin1String("smb")) {
2287 m_placeholderLabel->setText(i18n("No shared folders found"));
2288 } else if (m_url.scheme() == QLatin1String("network")) {
2289 m_placeholderLabel->setText(i18n("No relevant network resources found"));
2290 } else if (m_url.scheme() == QLatin1String("mtp") && m_url.path() == QLatin1String("/")) {
2291 m_placeholderLabel->setText(i18n("No MTP-compatible devices found"));
2292 } else if (m_url.scheme() == QLatin1String("afc") && m_url.path() == QLatin1String("/")) {
2293 m_placeholderLabel->setText(i18n("No Apple devices found"));
2294 } else if (m_url.scheme() == QLatin1String("bluetooth")) {
2295 m_placeholderLabel->setText(i18n("No Bluetooth devices found"));
2296 } else {
2297 m_placeholderLabel->setText(i18n("Folder is empty"));
2298 }
2299
2300 m_placeholderLabel->setVisible(true);
2301 }
2302
2303 void DolphinView::tryShowNameToolTip(QHelpEvent *event)
2304 {
2305 if (!GeneralSettings::showToolTips() && m_mode == DolphinView::IconsView) {
2306 const std::optional<int> index = m_view->itemAt(event->pos());
2307
2308 if (!index.has_value()) {
2309 return;
2310 }
2311
2312 // Check whether the filename has been elided
2313 const bool isElided = m_view->isElided(index.value());
2314
2315 if (isElided) {
2316 const KFileItem item = m_model->fileItem(index.value());
2317 const QString text = item.text();
2318 const QPoint pos = mapToGlobal(event->pos());
2319 QToolTip::showText(pos, text);
2320 }
2321 }
2322 }