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