]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Merge branch 'release/21.08'
[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 "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 <QPointer>
60 #include <QScrollBar>
61 #include <QSize>
62 #include <QTimer>
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::setVisibleRoles(const QList<QByteArray>& roles)
467 {
468 const QList<QByteArray> previousRoles = roles;
469
470 ViewProperties props(viewPropertiesUrl());
471 props.setVisibleRoles(roles);
472
473 m_visibleRoles = roles;
474 m_view->setVisibleRoles(roles);
475
476 Q_EMIT visibleRolesChanged(m_visibleRoles, previousRoles);
477 }
478
479 QList<QByteArray> DolphinView::visibleRoles() const
480 {
481 return m_visibleRoles;
482 }
483
484 void DolphinView::reload()
485 {
486 QByteArray viewState;
487 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
488 saveState(saveStream);
489
490 setUrl(url());
491 loadDirectory(url(), true);
492
493 QDataStream restoreStream(viewState);
494 restoreState(restoreStream);
495 }
496
497 void DolphinView::readSettings()
498 {
499 const int oldZoomLevel = m_view->zoomLevel();
500
501 GeneralSettings::self()->load();
502 m_view->readSettings();
503 applyViewProperties();
504
505 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
506 m_container->controller()->setAutoActivationDelay(delay);
507
508 const int newZoomLevel = m_view->zoomLevel();
509 if (newZoomLevel != oldZoomLevel) {
510 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
511 }
512 }
513
514 void DolphinView::writeSettings()
515 {
516 GeneralSettings::self()->save();
517 m_view->writeSettings();
518 }
519
520 void DolphinView::setNameFilter(const QString& nameFilter)
521 {
522 m_model->setNameFilter(nameFilter);
523 }
524
525 QString DolphinView::nameFilter() const
526 {
527 return m_model->nameFilter();
528 }
529
530 void DolphinView::setMimeTypeFilters(const QStringList& filters)
531 {
532 return m_model->setMimeTypeFilters(filters);
533 }
534
535 QStringList DolphinView::mimeTypeFilters() const
536 {
537 return m_model->mimeTypeFilters();
538 }
539
540 void DolphinView::requestStatusBarText()
541 {
542 if (m_statJobForStatusBarText) {
543 // Kill the pending request.
544 m_statJobForStatusBarText->kill();
545 }
546
547 if (m_container->controller()->selectionManager()->hasSelection()) {
548 int folderCount = 0;
549 int fileCount = 0;
550 KIO::filesize_t totalFileSize = 0;
551
552 // Give a summary of the status of the selected files
553 const KFileItemList list = selectedItems();
554 for (const KFileItem& item : list) {
555 if (item.isDir()) {
556 ++folderCount;
557 } else {
558 ++fileCount;
559 totalFileSize += item.size();
560 }
561 }
562
563 if (folderCount + fileCount == 1) {
564 // If only one item is selected, show info about it
565 Q_EMIT statusBarTextChanged(list.first().getStatusBarInfo());
566 } else {
567 // At least 2 items are selected
568 emitStatusBarText(folderCount, fileCount, totalFileSize, HasSelection);
569 }
570 } else { // has no selection
571 if (!m_model->rootItem().url().isValid()) {
572 return;
573 }
574
575 m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(),
576 KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
577 connect(m_statJobForStatusBarText, &KJob::result,
578 this, &DolphinView::slotStatJobResult);
579 m_statJobForStatusBarText->start();
580 }
581 }
582
583 void DolphinView::emitStatusBarText(const int folderCount, const int fileCount,
584 KIO::filesize_t totalFileSize, const Selection selection)
585 {
586 QString foldersText;
587 QString filesText;
588 QString summary;
589
590 if (selection == HasSelection) {
591 // At least 2 items are selected because the case of 1 selected item is handled in
592 // DolphinView::requestStatusBarText().
593 foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
594 filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
595 } else {
596 foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount);
597 filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount);
598 }
599
600 if (fileCount > 0 && folderCount > 0) {
601 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
602 foldersText, filesText,
603 KFormat().formatByteSize(totalFileSize));
604 } else if (fileCount > 0) {
605 summary = i18nc("@info:status files (size)", "%1 (%2)",
606 filesText,
607 KFormat().formatByteSize(totalFileSize));
608 } else if (folderCount > 0) {
609 summary = foldersText;
610 } else {
611 summary = i18nc("@info:status", "0 Folders, 0 Files");
612 }
613 Q_EMIT statusBarTextChanged(summary);
614 }
615
616 QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
617 {
618 QList<QAction*> actions;
619
620 if (items.isEmpty()) {
621 const KFileItem item = m_model->rootItem();
622 if (!item.isNull()) {
623 actions = m_versionControlObserver->actions(KFileItemList() << item);
624 }
625 } else {
626 actions = m_versionControlObserver->actions(items);
627 }
628
629 return actions;
630 }
631
632 void DolphinView::setUrl(const QUrl& url)
633 {
634 if (url == m_url) {
635 return;
636 }
637
638 clearSelection();
639
640 m_url = url;
641
642 hideToolTip();
643
644 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
645 this, &DolphinView::slotRoleEditingFinished);
646
647 // It is important to clear the items from the model before
648 // applying the view properties, otherwise expensive operations
649 // might be done on the existing items although they get cleared
650 // anyhow afterwards by loadDirectory().
651 m_model->clear();
652 applyViewProperties();
653 loadDirectory(url);
654
655 Q_EMIT urlChanged(url);
656 }
657
658 void DolphinView::selectAll()
659 {
660 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
661 selectionManager->setSelected(0, m_model->count());
662 }
663
664 void DolphinView::invertSelection()
665 {
666 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
667 selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
668 }
669
670 void DolphinView::clearSelection()
671 {
672 m_selectedUrls.clear();
673 m_container->controller()->selectionManager()->clearSelection();
674 }
675
676 void DolphinView::renameSelectedItems()
677 {
678 const KFileItemList items = selectedItems();
679 if (items.isEmpty()) {
680 return;
681 }
682
683 if (items.count() == 1 && GeneralSettings::renameInline()) {
684 const int index = m_model->index(items.first());
685
686 QMetaObject::Connection * const connection = new QMetaObject::Connection;
687 *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=](){
688 QObject::disconnect(*connection);
689 delete connection;
690
691 m_view->editRole(index, "text");
692
693 hideToolTip();
694
695 connect(m_view, &DolphinItemListView::roleEditingFinished,
696 this, &DolphinView::slotRoleEditingFinished);
697 });
698 m_view->scrollToItem(index);
699
700 } else {
701 KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(items, this);
702 connect(dialog, &KIO::RenameFileDialog::renamingFinished,
703 this, &DolphinView::slotRenameDialogRenamingFinished);
704
705 dialog->open();
706 }
707
708 // Assure that the current index remains visible when KFileItemModel
709 // will notify the view about changed items (which might result in
710 // a changed sorting).
711 m_assureVisibleCurrentIndex = true;
712 }
713
714 void DolphinView::trashSelectedItems()
715 {
716 const QList<QUrl> list = simplifiedSelectedUrls();
717 KIO::JobUiDelegate uiDelegate;
718 uiDelegate.setWindow(window());
719 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) {
720 KIO::Job* job = KIO::trash(list);
721 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job);
722 KJobWidgets::setWindow(job, this);
723 connect(job, &KIO::Job::result,
724 this, &DolphinView::slotTrashFileFinished);
725 }
726 }
727
728 void DolphinView::deleteSelectedItems()
729 {
730 const QList<QUrl> list = simplifiedSelectedUrls();
731
732 KIO::JobUiDelegate uiDelegate;
733 uiDelegate.setWindow(window());
734 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) {
735 KIO::Job* job = KIO::del(list);
736 KJobWidgets::setWindow(job, this);
737 connect(job, &KIO::Job::result,
738 this, &DolphinView::slotDeleteFileFinished);
739 }
740 }
741
742 void DolphinView::cutSelectedItemsToClipboard()
743 {
744 QMimeData* mimeData = selectionMimeData();
745 KIO::setClipboardDataCut(mimeData, true);
746 QApplication::clipboard()->setMimeData(mimeData);
747 }
748
749 void DolphinView::copySelectedItemsToClipboard()
750 {
751 QMimeData* mimeData = selectionMimeData();
752 QApplication::clipboard()->setMimeData(mimeData);
753 }
754
755 void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
756 {
757 KIO::CopyJob* job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
758 KJobWidgets::setWindow(job, this);
759
760 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
761 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
762 KIO::FileUndoManager::self()->recordCopyJob(job);
763 }
764
765 void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
766 {
767 KIO::CopyJob* job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
768 KJobWidgets::setWindow(job, this);
769
770 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
771 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
772 KIO::FileUndoManager::self()->recordCopyJob(job);
773
774 }
775
776 void DolphinView::paste()
777 {
778 pasteToUrl(url());
779 }
780
781 void DolphinView::pasteIntoFolder()
782 {
783 const KFileItemList items = selectedItems();
784 if ((items.count() == 1) && items.first().isDir()) {
785 pasteToUrl(items.first().url());
786 }
787 }
788
789 void DolphinView::duplicateSelectedItems()
790 {
791 const KFileItemList itemList = selectedItems();
792 if (itemList.isEmpty()) {
793 return;
794 }
795
796 const QMimeDatabase db;
797
798 // Duplicate all selected items and append "copy" to the end of the file name
799 // but before the filename extension, if present
800 QList<QUrl> newSelection;
801 for (const auto &item : itemList) {
802 const QUrl originalURL = item.url();
803 const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
804 const QString originalFileName = item.name();
805
806 QString extension = db.suffixForFileName(originalFileName);
807
808 QUrl duplicateURL = originalURL;
809
810 // No extension; new filename is "<oldfilename> copy"
811 if (extension.isEmpty()) {
812 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFileName));
813 // There's an extension; new filename is "<oldfilename> copy.<extension>"
814 } else {
815 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
816 extension = QLatin1String(".") + extension;
817 const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size());
818 // Preserve file's original filename extension in case the casing differs
819 // from what QMimeDatabase::suffixForFileName() returned
820 const QString originalExtension = originalFileName.right(extension.size());
821 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension);
822 }
823
824 KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL);
825 KJobWidgets::setWindow(job, this);
826
827 if (job) {
828 newSelection << duplicateURL;
829 KIO::FileUndoManager::self()->recordCopyJob(job);
830 }
831 }
832
833 forceUrlsSelection(newSelection.first(), newSelection);
834 }
835
836 void DolphinView::stopLoading()
837 {
838 m_model->cancelDirectoryLoading();
839 }
840
841 void DolphinView::updatePalette()
842 {
843 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
844 if (!m_active) {
845 color.setAlpha(150);
846 }
847
848 QWidget* viewport = m_container->viewport();
849 if (viewport) {
850 QPalette palette;
851 palette.setColor(viewport->backgroundRole(), color);
852 viewport->setPalette(palette);
853 }
854
855 update();
856 }
857
858 void DolphinView::abortTwoClicksRenaming()
859 {
860 m_twoClicksRenamingItemUrl.clear();
861 m_twoClicksRenamingTimer->stop();
862 }
863
864 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
865 {
866 switch (event->type()) {
867 case QEvent::PaletteChange:
868 updatePalette();
869 QPixmapCache::clear();
870 break;
871
872 case QEvent::WindowActivate:
873 case QEvent::WindowDeactivate:
874 updatePalette();
875 break;
876
877 case QEvent::KeyPress:
878 hideToolTip(ToolTipManager::HideBehavior::Instantly);
879 if (GeneralSettings::useTabForSwitchingSplitView()) {
880 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
881 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
882 Q_EMIT toggleActiveViewRequested();
883 return true;
884 }
885 }
886 break;
887 case QEvent::FocusIn:
888 if (watched == m_container) {
889 setActive(true);
890 }
891 break;
892
893 case QEvent::GraphicsSceneDragEnter:
894 if (watched == m_view) {
895 m_dragging = true;
896 abortTwoClicksRenaming();
897 }
898 break;
899
900 case QEvent::GraphicsSceneDragLeave:
901 if (watched == m_view) {
902 m_dragging = false;
903 }
904 break;
905
906 case QEvent::GraphicsSceneDrop:
907 if (watched == m_view) {
908 m_dragging = false;
909 }
910 default:
911 break;
912 }
913
914 return QWidget::eventFilter(watched, event);
915 }
916
917 void DolphinView::wheelEvent(QWheelEvent* event)
918 {
919 if (event->modifiers().testFlag(Qt::ControlModifier)) {
920 const QPoint numDegrees = event->angleDelta() / 8;
921 const QPoint numSteps = numDegrees / 15;
922
923 setZoomLevel(zoomLevel() + numSteps.y());
924 event->accept();
925 } else {
926 event->ignore();
927 }
928 }
929
930 void DolphinView::hideEvent(QHideEvent* event)
931 {
932 hideToolTip();
933 QWidget::hideEvent(event);
934 }
935
936 bool DolphinView::event(QEvent* event)
937 {
938 if (event->type() == QEvent::WindowDeactivate) {
939 /* See Bug 297355
940 * Dolphin leaves file preview tooltips open even when is not visible.
941 *
942 * Hide tool-tip when Dolphin loses focus.
943 */
944 hideToolTip();
945 abortTwoClicksRenaming();
946 }
947
948 return QWidget::event(event);
949 }
950
951 void DolphinView::activate()
952 {
953 setActive(true);
954 }
955
956 void DolphinView::slotItemActivated(int index)
957 {
958 abortTwoClicksRenaming();
959
960 const KFileItem item = m_model->fileItem(index);
961 if (!item.isNull()) {
962 Q_EMIT itemActivated(item);
963 }
964 }
965
966 void DolphinView::slotItemsActivated(const KItemSet& indexes)
967 {
968 Q_ASSERT(indexes.count() >= 2);
969
970 abortTwoClicksRenaming();
971
972 if (indexes.count() > 5) {
973 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
974 const int answer = KMessageBox::warningYesNo(this, question);
975 if (answer != KMessageBox::Yes) {
976 return;
977 }
978 }
979
980 KFileItemList items;
981 items.reserve(indexes.count());
982
983 for (int index : indexes) {
984 KFileItem item = m_model->fileItem(index);
985 const QUrl& url = openItemAsFolderUrl(item);
986
987 if (!url.isEmpty()) { // Open folders in new tabs
988 Q_EMIT tabRequested(url);
989 } else {
990 items.append(item);
991 }
992 }
993
994 if (items.count() == 1) {
995 Q_EMIT itemActivated(items.first());
996 } else if (items.count() > 1) {
997 Q_EMIT itemsActivated(items);
998 }
999 }
1000
1001 void DolphinView::slotItemMiddleClicked(int index)
1002 {
1003 const KFileItem& item = m_model->fileItem(index);
1004 const QUrl& url = openItemAsFolderUrl(item);
1005 if (!url.isEmpty()) {
1006 Q_EMIT tabRequested(url);
1007 } else if (isTabsForFilesEnabled()) {
1008 Q_EMIT tabRequested(item.url());
1009 }
1010 }
1011
1012 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
1013 {
1014 // Force emit of a selection changed signal before we request the
1015 // context menu, to update the edit-actions first. (See Bug 294013)
1016 if (m_selectionChangedTimer->isActive()) {
1017 emitSelectionChangedSignal();
1018 }
1019
1020 const KFileItem item = m_model->fileItem(index);
1021 Q_EMIT requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
1022 }
1023
1024 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
1025 {
1026 Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
1027 }
1028
1029 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
1030 {
1031 ViewProperties props(viewPropertiesUrl());
1032
1033 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
1034
1035 KItemListView* view = m_container->controller()->view();
1036 const QList<QByteArray> visibleRolesSet = view->visibleRoles();
1037
1038 bool indexingEnabled = false;
1039 #ifdef HAVE_BALOO
1040 Baloo::IndexerConfig config;
1041 indexingEnabled = config.fileIndexingEnabled();
1042 #endif
1043
1044 QString groupName;
1045 QMenu* groupMenu = nullptr;
1046
1047 // Add all roles to the menu that can be shown or hidden by the user
1048 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
1049 for (const KFileItemModel::RoleInfo& info : rolesInfo) {
1050 if (info.role == "text") {
1051 // It should not be possible to hide the "text" role
1052 continue;
1053 }
1054
1055 const QString text = m_model->roleDescription(info.role);
1056 QAction* action = nullptr;
1057 if (info.group.isEmpty()) {
1058 action = menu->addAction(text);
1059 } else {
1060 if (!groupMenu || info.group != groupName) {
1061 groupName = info.group;
1062 groupMenu = menu->addMenu(groupName);
1063 }
1064
1065 action = groupMenu->addAction(text);
1066 }
1067
1068 action->setCheckable(true);
1069 action->setChecked(visibleRolesSet.contains(info.role));
1070 action->setData(info.role);
1071
1072 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
1073 (info.requiresBaloo) ||
1074 (info.requiresIndexer && indexingEnabled);
1075 action->setEnabled(enable);
1076 }
1077
1078 menu->addSeparator();
1079
1080 QActionGroup* widthsGroup = new QActionGroup(menu);
1081 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
1082
1083 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1084 autoAdjustWidthsAction->setCheckable(true);
1085 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1086 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1087
1088 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1089 customWidthsAction->setCheckable(true);
1090 customWidthsAction->setChecked(!autoColumnWidths);
1091 customWidthsAction->setActionGroup(widthsGroup);
1092
1093 QAction* action = menu->exec(pos.toPoint());
1094 if (menu && action) {
1095 KItemListHeader* header = view->header();
1096
1097 if (action == autoAdjustWidthsAction) {
1098 // Clear the column-widths from the viewproperties and turn on
1099 // the automatic resizing of the columns
1100 props.setHeaderColumnWidths(QList<int>());
1101 header->setAutomaticColumnResizing(true);
1102 } else if (action == customWidthsAction) {
1103 // Apply the current column-widths as custom column-widths and turn
1104 // off the automatic resizing of the columns
1105 QList<int> columnWidths;
1106 const auto visibleRoles = view->visibleRoles();
1107 columnWidths.reserve(visibleRoles.count());
1108 for (const QByteArray& role : visibleRoles) {
1109 columnWidths.append(header->columnWidth(role));
1110 }
1111 props.setHeaderColumnWidths(columnWidths);
1112 header->setAutomaticColumnResizing(false);
1113 } else {
1114 // Show or hide the selected role
1115 const QByteArray selectedRole = action->data().toByteArray();
1116
1117 QList<QByteArray> visibleRoles = view->visibleRoles();
1118 if (action->isChecked()) {
1119 visibleRoles.append(selectedRole);
1120 } else {
1121 visibleRoles.removeOne(selectedRole);
1122 }
1123
1124 view->setVisibleRoles(visibleRoles);
1125 props.setVisibleRoles(visibleRoles);
1126
1127 QList<int> columnWidths;
1128 if (!header->automaticColumnResizing()) {
1129 const auto visibleRoles = view->visibleRoles();
1130 columnWidths.reserve(visibleRoles.count());
1131 for (const QByteArray& role : visibleRoles) {
1132 columnWidths.append(header->columnWidth(role));
1133 }
1134 }
1135 props.setHeaderColumnWidths(columnWidths);
1136 }
1137 }
1138
1139 delete menu;
1140 }
1141
1142 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1143 {
1144 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1145
1146 ViewProperties props(viewPropertiesUrl());
1147 QList<int> columnWidths = props.headerColumnWidths();
1148 if (columnWidths.count() != visibleRoles.count()) {
1149 columnWidths.clear();
1150 columnWidths.reserve(visibleRoles.count());
1151 const KItemListHeader* header = m_view->header();
1152 for (const QByteArray& role : visibleRoles) {
1153 const int width = header->columnWidth(role);
1154 columnWidths.append(width);
1155 }
1156 }
1157
1158 const int roleIndex = visibleRoles.indexOf(role);
1159 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1160 columnWidths[roleIndex] = current;
1161
1162 props.setHeaderColumnWidths(columnWidths);
1163 }
1164
1165 void DolphinView::slotItemHovered(int index)
1166 {
1167 const KFileItem item = m_model->fileItem(index);
1168
1169 if (GeneralSettings::showToolTips() && !m_dragging) {
1170 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1171 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1172 itemRect.moveTo(pos);
1173
1174 #ifdef HAVE_BALOO
1175 m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle());
1176 #endif
1177 }
1178
1179 Q_EMIT requestItemInfo(item);
1180 }
1181
1182 void DolphinView::slotItemUnhovered(int index)
1183 {
1184 Q_UNUSED(index)
1185 hideToolTip();
1186 Q_EMIT requestItemInfo(KFileItem());
1187 }
1188
1189 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1190 {
1191 QUrl destUrl;
1192 KFileItem destItem = m_model->fileItem(index);
1193 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1194 // Use the URL of the view as drop target if the item is no directory
1195 // or desktop-file
1196 destItem = m_model->rootItem();
1197 destUrl = url();
1198 } else {
1199 // The item represents a directory or desktop-file
1200 destUrl = destItem.mostLocalUrl();
1201 }
1202
1203 QDropEvent dropEvent(event->pos().toPoint(),
1204 event->possibleActions(),
1205 event->mimeData(),
1206 event->buttons(),
1207 event->modifiers());
1208 dropUrls(destUrl, &dropEvent, this);
1209
1210 setActive(true);
1211 }
1212
1213 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1214 {
1215 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1216
1217 if (job) {
1218 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1219
1220 if (destUrl == url()) {
1221 // Mark the dropped urls as selected.
1222 m_clearSelectionBeforeSelectingNewItems = true;
1223 m_markFirstNewlySelectedItemAsCurrent = true;
1224 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1225 }
1226 }
1227 }
1228
1229 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1230 {
1231 if (previous != nullptr) {
1232 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1233 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1234 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1235 m_versionControlObserver->setModel(nullptr);
1236 }
1237
1238 if (current) {
1239 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1240 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1241 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1242 m_versionControlObserver->setModel(fileItemModel);
1243 }
1244 }
1245
1246 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1247 {
1248 Q_UNUSED(itemIndex)
1249
1250 hideToolTip();
1251
1252 if (buttons & Qt::BackButton) {
1253 Q_EMIT goBackRequested();
1254 } else if (buttons & Qt::ForwardButton) {
1255 Q_EMIT goForwardRequested();
1256 }
1257 }
1258
1259 void DolphinView::slotSelectedItemTextPressed(int index)
1260 {
1261 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1262 const KFileItem item = m_model->fileItem(index);
1263 const KFileItemListProperties capabilities(KFileItemList() << item);
1264 if (capabilities.supportsMoving()) {
1265 m_twoClicksRenamingItemUrl = item.url();
1266 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1267 }
1268 }
1269 }
1270
1271 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1272 {
1273 slotItemCreated(to);
1274 }
1275
1276 void DolphinView::slotItemCreated(const QUrl& url)
1277 {
1278 if (m_markFirstNewlySelectedItemAsCurrent) {
1279 markUrlAsCurrent(url);
1280 m_markFirstNewlySelectedItemAsCurrent = false;
1281 }
1282 m_selectedUrls << url;
1283 }
1284
1285 void DolphinView::slotJobResult(KJob *job)
1286 {
1287 if (job->error()) {
1288 Q_EMIT errorMessage(job->errorString());
1289 }
1290 if (!m_selectedUrls.isEmpty()) {
1291 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1292 }
1293 }
1294
1295 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1296 {
1297 const int currentCount = current.count();
1298 const int previousCount = previous.count();
1299 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1300 (currentCount > 0 && previousCount == 0);
1301
1302 // If nothing has been selected before and something got selected (or if something
1303 // was selected before and now nothing is selected) the selectionChangedSignal must
1304 // be emitted asynchronously as fast as possible to update the edit-actions.
1305 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1306 m_selectionChangedTimer->start();
1307 }
1308
1309 void DolphinView::emitSelectionChangedSignal()
1310 {
1311 m_selectionChangedTimer->stop();
1312 Q_EMIT selectionChanged(selectedItems());
1313 }
1314
1315 void DolphinView::slotStatJobResult(KJob *job)
1316 {
1317 int folderCount = 0;
1318 int fileCount = 0;
1319 KIO::filesize_t totalFileSize = 0;
1320 bool countFileSize = true;
1321
1322 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1323 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1324 // We have a precomputed value.
1325 totalFileSize = static_cast<KIO::filesize_t>(
1326 entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1327 countFileSize = false;
1328 }
1329
1330 const int itemCount = m_model->count();
1331 for (int i = 0; i < itemCount; ++i) {
1332 const KFileItem item = m_model->fileItem(i);
1333 if (item.isDir()) {
1334 ++folderCount;
1335 } else {
1336 ++fileCount;
1337 if (countFileSize) {
1338 totalFileSize += item.size();
1339 }
1340 }
1341 }
1342 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1343 }
1344
1345 void DolphinView::updateSortRole(const QByteArray& role)
1346 {
1347 ViewProperties props(viewPropertiesUrl());
1348 props.setSortRole(role);
1349
1350 KItemModelBase* model = m_container->controller()->model();
1351 model->setSortRole(role);
1352
1353 Q_EMIT sortRoleChanged(role);
1354 }
1355
1356 void DolphinView::updateSortOrder(Qt::SortOrder order)
1357 {
1358 ViewProperties props(viewPropertiesUrl());
1359 props.setSortOrder(order);
1360
1361 m_model->setSortOrder(order);
1362
1363 Q_EMIT sortOrderChanged(order);
1364 }
1365
1366 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1367 {
1368 ViewProperties props(viewPropertiesUrl());
1369 props.setSortFoldersFirst(foldersFirst);
1370
1371 m_model->setSortDirectoriesFirst(foldersFirst);
1372
1373 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1374 }
1375
1376 QPair<bool, QString> DolphinView::pasteInfo() const
1377 {
1378 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1379 QPair<bool, QString> info;
1380 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1381 return info;
1382 }
1383
1384 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1385 {
1386 m_tabsForFiles = tabsForFiles;
1387 }
1388
1389 bool DolphinView::isTabsForFilesEnabled() const
1390 {
1391 return m_tabsForFiles;
1392 }
1393
1394 bool DolphinView::itemsExpandable() const
1395 {
1396 return m_mode == DetailsView;
1397 }
1398
1399 void DolphinView::restoreState(QDataStream& stream)
1400 {
1401 // Read the version number of the view state and check if the version is supported.
1402 quint32 version = 0;
1403 stream >> version;
1404 if (version != 1) {
1405 // The version of the view state isn't supported, we can't restore it.
1406 return;
1407 }
1408
1409 // Restore the current item that had the keyboard focus
1410 stream >> m_currentItemUrl;
1411
1412 // Restore the previously selected items
1413 stream >> m_selectedUrls;
1414
1415 // Restore the view position
1416 stream >> m_restoredContentsPosition;
1417
1418 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1419 QSet<QUrl> urls;
1420 stream >> urls;
1421 m_model->restoreExpandedDirectories(urls);
1422 }
1423
1424 void DolphinView::saveState(QDataStream& stream)
1425 {
1426 stream << quint32(1); // View state version
1427
1428 // Save the current item that has the keyboard focus
1429 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1430 if (currentIndex != -1) {
1431 KFileItem item = m_model->fileItem(currentIndex);
1432 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1433 QUrl currentItemUrl = item.url();
1434 stream << currentItemUrl;
1435 } else {
1436 stream << QUrl();
1437 }
1438
1439 // Save the selected urls
1440 stream << selectedItems().urlList();
1441
1442 // Save view position
1443 const qreal x = m_container->horizontalScrollBar()->value();
1444 const qreal y = m_container->verticalScrollBar()->value();
1445 stream << QPoint(x, y);
1446
1447 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1448 stream << m_model->expandedDirectories();
1449 }
1450
1451 KFileItem DolphinView::rootItem() const
1452 {
1453 return m_model->rootItem();
1454 }
1455
1456 void DolphinView::setViewPropertiesContext(const QString& context)
1457 {
1458 m_viewPropertiesContext = context;
1459 }
1460
1461 QString DolphinView::viewPropertiesContext() const
1462 {
1463 return m_viewPropertiesContext;
1464 }
1465
1466 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1467 {
1468 if (item.isNull()) {
1469 return QUrl();
1470 }
1471
1472 QUrl url = item.targetUrl();
1473
1474 if (item.isDir()) {
1475 return url;
1476 }
1477
1478 if (item.isMimeTypeKnown()) {
1479 const QString& mimetype = item.mimetype();
1480
1481 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1482 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1483 // zip:/<path>/ when clicking on a zip file, etc.
1484 // The .protocol file specifies the mimetype that the kioslave handles.
1485 // Note that we don't use mimetype inheritance since we don't want to
1486 // open OpenDocument files as zip folders...
1487 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1488 if (!protocol.isEmpty()) {
1489 url.setScheme(protocol);
1490 return url;
1491 }
1492 }
1493
1494 if (mimetype == QLatin1String("application/x-desktop")) {
1495 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1496 KDesktopFile desktopFile(url.toLocalFile());
1497 if (desktopFile.hasLinkType()) {
1498 const QString linkUrl = desktopFile.readUrl();
1499 if (!linkUrl.startsWith(QLatin1String("http"))) {
1500 return QUrl::fromUserInput(linkUrl);
1501 }
1502 }
1503 }
1504 }
1505
1506 return QUrl();
1507 }
1508
1509 void DolphinView::resetZoomLevel()
1510 {
1511 ViewModeSettings::ViewMode mode;
1512
1513 switch (m_mode) {
1514 case IconsView: mode = ViewModeSettings::IconsMode; break;
1515 case CompactView: mode = ViewModeSettings::CompactMode; break;
1516 case DetailsView: mode = ViewModeSettings::DetailsMode; break;
1517 }
1518 const ViewModeSettings settings(mode);
1519 const QSize iconSize = QSize(settings.iconSize(), settings.iconSize());
1520 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize));
1521 }
1522
1523 void DolphinView::observeCreatedItem(const QUrl& url)
1524 {
1525 if (m_active) {
1526 forceUrlsSelection(url, {url});
1527 }
1528 }
1529
1530 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1531 {
1532 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1533 Q_EMIT redirection(oldUrl, newUrl);
1534 m_url = newUrl; // #186947
1535 }
1536 }
1537
1538 void DolphinView::updateViewState()
1539 {
1540 if (m_currentItemUrl != QUrl()) {
1541 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1542
1543 // if there is a selection already, leave it that way
1544 if (!selectionManager->hasSelection()) {
1545 const int currentIndex = m_model->index(m_currentItemUrl);
1546 if (currentIndex != -1) {
1547 selectionManager->setCurrentItem(currentIndex);
1548
1549 // scroll to current item and reset the state
1550 if (m_scrollToCurrentItem) {
1551 m_view->scrollToItem(currentIndex);
1552 m_scrollToCurrentItem = false;
1553 }
1554 } else {
1555 selectionManager->setCurrentItem(0);
1556 }
1557 }
1558
1559 m_currentItemUrl = QUrl();
1560 }
1561
1562 if (!m_restoredContentsPosition.isNull()) {
1563 const int x = m_restoredContentsPosition.x();
1564 const int y = m_restoredContentsPosition.y();
1565 m_restoredContentsPosition = QPoint();
1566
1567 m_container->horizontalScrollBar()->setValue(x);
1568 m_container->verticalScrollBar()->setValue(y);
1569 }
1570
1571 if (!m_selectedUrls.isEmpty()) {
1572 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1573
1574 // if there is a selection already, leave it that way
1575 if (!selectionManager->hasSelection()) {
1576 if (m_clearSelectionBeforeSelectingNewItems) {
1577 selectionManager->clearSelection();
1578 m_clearSelectionBeforeSelectingNewItems = false;
1579 }
1580
1581 KItemSet selectedItems = selectionManager->selectedItems();
1582
1583 QList<QUrl>::iterator it = m_selectedUrls.begin();
1584 while (it != m_selectedUrls.end()) {
1585 const int index = m_model->index(*it);
1586 if (index >= 0) {
1587 selectedItems.insert(index);
1588 it = m_selectedUrls.erase(it);
1589 } else {
1590 ++it;
1591 }
1592 }
1593
1594 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1595 selectionManager->setSelectedItems(selectedItems);
1596 }
1597 }
1598 }
1599
1600 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1601 {
1602 #ifdef HAVE_BALOO
1603 if (GeneralSettings::showToolTips()) {
1604 m_toolTipManager->hideToolTip(behavior);
1605 }
1606 #else
1607 Q_UNUSED(behavior)
1608 #endif
1609 }
1610
1611 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1612 {
1613 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1614
1615 // verify that only one item is selected
1616 if (selectionManager->selectedItems().count() == 1) {
1617 const int index = selectionManager->currentItem();
1618 const QUrl fileItemUrl = m_model->fileItem(index).url();
1619
1620 // check if the selected item was the same item that started the twoClicksRenaming
1621 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1622 renameSelectedItems();
1623 }
1624 }
1625 }
1626
1627 void DolphinView::slotTrashFileFinished(KJob* job)
1628 {
1629 if (job->error() == 0) {
1630 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1631 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1632 Q_EMIT errorMessage(job->errorString());
1633 }
1634 }
1635
1636 void DolphinView::slotDeleteFileFinished(KJob* job)
1637 {
1638 if (job->error() == 0) {
1639 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1640 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1641 Q_EMIT errorMessage(job->errorString());
1642 }
1643 }
1644
1645 void DolphinView::slotRenamingResult(KJob* job)
1646 {
1647 if (job->error()) {
1648 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1649 Q_ASSERT(copyJob);
1650 const QUrl newUrl = copyJob->destUrl();
1651 const int index = m_model->index(newUrl);
1652 if (index >= 0) {
1653 QHash<QByteArray, QVariant> data;
1654 const QUrl oldUrl = copyJob->srcUrls().at(0);
1655 data.insert("text", oldUrl.fileName());
1656 m_model->setData(index, data);
1657 }
1658 }
1659 }
1660
1661 void DolphinView::slotDirectoryLoadingStarted()
1662 {
1663 m_loading = true;
1664 updatePlaceholderLabel();
1665
1666 // Disable the writestate temporary until it can be determined in a fast way
1667 // in DolphinView::slotDirectoryLoadingCompleted()
1668 if (m_isFolderWritable) {
1669 m_isFolderWritable = false;
1670 Q_EMIT writeStateChanged(m_isFolderWritable);
1671 }
1672
1673 Q_EMIT directoryLoadingStarted();
1674 }
1675
1676 void DolphinView::slotDirectoryLoadingCompleted()
1677 {
1678 m_loading = false;
1679
1680 // Update the view-state. This has to be done asynchronously
1681 // because the view might not be in its final state yet.
1682 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1683
1684 // Update the placeholder label in case we found that the folder was empty
1685 // after loading it
1686
1687 Q_EMIT directoryLoadingCompleted();
1688
1689 updatePlaceholderLabel();
1690 updateWritableState();
1691 }
1692
1693 void DolphinView::slotDirectoryLoadingCanceled()
1694 {
1695 m_loading = false;
1696
1697 updatePlaceholderLabel();
1698
1699 Q_EMIT directoryLoadingCanceled();
1700 }
1701
1702 void DolphinView::slotItemsChanged()
1703 {
1704 m_assureVisibleCurrentIndex = false;
1705 }
1706
1707 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1708 {
1709 Q_UNUSED(previous)
1710 Q_ASSERT(m_model->sortOrder() == current);
1711
1712 ViewProperties props(viewPropertiesUrl());
1713 props.setSortOrder(current);
1714
1715 Q_EMIT sortOrderChanged(current);
1716 }
1717
1718 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1719 {
1720 Q_UNUSED(previous)
1721 Q_ASSERT(m_model->sortRole() == current);
1722
1723 ViewProperties props(viewPropertiesUrl());
1724 props.setSortRole(current);
1725
1726 Q_EMIT sortRoleChanged(current);
1727 }
1728
1729 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1730 const QList<QByteArray>& previous)
1731 {
1732 Q_UNUSED(previous)
1733 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1734
1735 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1736
1737 m_visibleRoles = current;
1738
1739 ViewProperties props(viewPropertiesUrl());
1740 props.setVisibleRoles(m_visibleRoles);
1741
1742 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1743 }
1744
1745 void DolphinView::slotRoleEditingCanceled()
1746 {
1747 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1748 this, &DolphinView::slotRoleEditingFinished);
1749 }
1750
1751 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1752 {
1753 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1754 this, &DolphinView::slotRoleEditingFinished);
1755
1756 const KFileItemList items = selectedItems();
1757 if (items.count() != 1) {
1758 return;
1759 }
1760
1761 if (role == "text") {
1762 const KFileItem oldItem = items.first();
1763 const EditResult retVal = value.value<EditResult>();
1764 const QString newName = retVal.newName;
1765 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1766 const QUrl oldUrl = oldItem.url();
1767
1768 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1769 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1770
1771 #ifndef Q_OS_WIN
1772 //Confirm hiding file/directory by renaming inline
1773 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1774 KGuiItem yesGuiItem(KStandardGuiItem::yes());
1775 yesGuiItem.setText(i18nc("@action:button", "Rename and Hide"));
1776
1777 const auto code = KMessageBox::questionYesNo(this,
1778 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1779 "Do you still want to rename it?")
1780 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1781 "Do you still want to rename it?"),
1782 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1783 yesGuiItem,
1784 KStandardGuiItem::cancel(),
1785 QStringLiteral("ConfirmHide")
1786 );
1787
1788 if (code == KMessageBox::No) {
1789 return;
1790 }
1791 }
1792 #endif
1793
1794 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1795 if (!newNameExistsAlready && m_model->index(oldUrl) == index) {
1796 // Only change the data in the model if no item with the new name
1797 // is in the model yet. If there is an item with the new name
1798 // already, calling KIO::CopyJob will open a dialog
1799 // asking for a new name, and KFileItemModel will update the
1800 // data when the dir lister signals that the file name has changed.
1801 QHash<QByteArray, QVariant> data;
1802 data.insert(role, retVal.newName);
1803 m_model->setData(index, data);
1804 }
1805
1806 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1807 KJobWidgets::setWindow(job, this);
1808 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1809 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1810
1811 forceUrlsSelection(newUrl, {newUrl});
1812
1813 if (!newNameExistsAlready) {
1814 // Only connect the result signal if there is no item with the new name
1815 // in the model yet, see bug 328262.
1816 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1817 }
1818 }
1819 if (retVal.direction != EditDone) {
1820 const short indexShift = retVal.direction == EditNext ? 1 : -1;
1821 m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect);
1822 m_container->controller()->selectionManager()->setSelected(index + indexShift, 1,
1823 KItemListSelectionManager::Select);
1824 renameSelectedItems();
1825 }
1826 }
1827 }
1828
1829 void DolphinView::loadDirectory(const QUrl& url, bool reload)
1830 {
1831 if (!url.isValid()) {
1832 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1833 if (location.isEmpty()) {
1834 Q_EMIT errorMessage(i18nc("@info:status", "The location is empty."));
1835 } else {
1836 Q_EMIT errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1837 }
1838 return;
1839 }
1840
1841 if (reload) {
1842 m_model->refreshDirectory(url);
1843 } else {
1844 m_model->loadDirectory(url);
1845 }
1846 }
1847
1848 void DolphinView::applyViewProperties()
1849 {
1850 const ViewProperties props(viewPropertiesUrl());
1851 applyViewProperties(props);
1852 }
1853
1854 void DolphinView::applyViewProperties(const ViewProperties& props)
1855 {
1856 m_view->beginTransaction();
1857
1858 const Mode mode = props.viewMode();
1859 if (m_mode != mode) {
1860 const Mode previousMode = m_mode;
1861 m_mode = mode;
1862
1863 // Changing the mode might result in changing
1864 // the zoom level. Remember the old zoom level so
1865 // that zoomLevelChanged() can get emitted.
1866 const int oldZoomLevel = m_view->zoomLevel();
1867 applyModeToView();
1868
1869 Q_EMIT modeChanged(m_mode, previousMode);
1870
1871 if (m_view->zoomLevel() != oldZoomLevel) {
1872 Q_EMIT zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1873 }
1874 }
1875
1876 const bool hiddenFilesShown = props.hiddenFilesShown();
1877 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1878 m_model->setShowHiddenFiles(hiddenFilesShown);
1879 Q_EMIT hiddenFilesShownChanged(hiddenFilesShown);
1880 }
1881
1882 const bool groupedSorting = props.groupedSorting();
1883 if (groupedSorting != m_model->groupedSorting()) {
1884 m_model->setGroupedSorting(groupedSorting);
1885 Q_EMIT groupedSortingChanged(groupedSorting);
1886 }
1887
1888 const QByteArray sortRole = props.sortRole();
1889 if (sortRole != m_model->sortRole()) {
1890 m_model->setSortRole(sortRole);
1891 Q_EMIT sortRoleChanged(sortRole);
1892 }
1893
1894 const Qt::SortOrder sortOrder = props.sortOrder();
1895 if (sortOrder != m_model->sortOrder()) {
1896 m_model->setSortOrder(sortOrder);
1897 Q_EMIT sortOrderChanged(sortOrder);
1898 }
1899
1900 const bool sortFoldersFirst = props.sortFoldersFirst();
1901 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1902 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1903 Q_EMIT sortFoldersFirstChanged(sortFoldersFirst);
1904 }
1905
1906 const QList<QByteArray> visibleRoles = props.visibleRoles();
1907 if (visibleRoles != m_visibleRoles) {
1908 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1909 m_visibleRoles = visibleRoles;
1910 m_view->setVisibleRoles(visibleRoles);
1911 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1912 }
1913
1914 const bool previewsShown = props.previewsShown();
1915 if (previewsShown != m_view->previewsShown()) {
1916 const int oldZoomLevel = zoomLevel();
1917
1918 m_view->setPreviewsShown(previewsShown);
1919 Q_EMIT previewsShownChanged(previewsShown);
1920
1921 // Changing the preview-state might result in a changed zoom-level
1922 if (oldZoomLevel != zoomLevel()) {
1923 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
1924 }
1925 }
1926
1927 KItemListView* itemListView = m_container->controller()->view();
1928 if (itemListView->isHeaderVisible()) {
1929 KItemListHeader* header = itemListView->header();
1930 const QList<int> headerColumnWidths = props.headerColumnWidths();
1931 const int rolesCount = m_visibleRoles.count();
1932 if (headerColumnWidths.count() == rolesCount) {
1933 header->setAutomaticColumnResizing(false);
1934
1935 QHash<QByteArray, qreal> columnWidths;
1936 for (int i = 0; i < rolesCount; ++i) {
1937 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1938 }
1939 header->setColumnWidths(columnWidths);
1940 } else {
1941 header->setAutomaticColumnResizing(true);
1942 }
1943 }
1944
1945 m_view->endTransaction();
1946 }
1947
1948 void DolphinView::applyModeToView()
1949 {
1950 switch (m_mode) {
1951 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1952 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1953 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1954 default: Q_ASSERT(false); break;
1955 }
1956 }
1957
1958 void DolphinView::pasteToUrl(const QUrl& url)
1959 {
1960 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
1961 KJobWidgets::setWindow(job, this);
1962 m_clearSelectionBeforeSelectingNewItems = true;
1963 m_markFirstNewlySelectedItemAsCurrent = true;
1964 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
1965 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotJobResult);
1966 }
1967
1968 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
1969 {
1970 QList<QUrl> urls;
1971
1972 const KFileItemList items = selectedItems();
1973 urls.reserve(items.count());
1974 for (const KFileItem& item : items) {
1975 urls.append(item.url());
1976 }
1977
1978 if (itemsExpandable()) {
1979 // TODO: Check if we still need KDirModel for this in KDE 5.0
1980 urls = KDirModel::simplifiedUrlList(urls);
1981 }
1982
1983 return urls;
1984 }
1985
1986 QMimeData* DolphinView::selectionMimeData() const
1987 {
1988 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1989 const KItemSet selectedIndexes = selectionManager->selectedItems();
1990
1991 return m_model->createMimeData(selectedIndexes);
1992 }
1993
1994 void DolphinView::updateWritableState()
1995 {
1996 const bool wasFolderWritable = m_isFolderWritable;
1997 m_isFolderWritable = false;
1998
1999 KFileItem item = m_model->rootItem();
2000 if (item.isNull()) {
2001 // Try to find out if the URL is writable even if the "root item" is
2002 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2003 item = KFileItem(url());
2004 item.setDelayedMimeTypes(true);
2005 }
2006
2007 KFileItemListProperties capabilities(KFileItemList() << item);
2008 m_isFolderWritable = capabilities.supportsWriting();
2009
2010 if (m_isFolderWritable != wasFolderWritable) {
2011 Q_EMIT writeStateChanged(m_isFolderWritable);
2012 }
2013 }
2014
2015 QUrl DolphinView::viewPropertiesUrl() const
2016 {
2017 if (m_viewPropertiesContext.isEmpty()) {
2018 return m_url;
2019 }
2020
2021 QUrl url;
2022 url.setScheme(m_url.scheme());
2023 url.setPath(m_viewPropertiesContext);
2024 return url;
2025 }
2026
2027 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
2028 {
2029 forceUrlsSelection(urls.first(), urls);
2030 }
2031
2032 void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
2033 {
2034 clearSelection();
2035 m_clearSelectionBeforeSelectingNewItems = true;
2036 markUrlAsCurrent(current);
2037 markUrlsAsSelected(selected);
2038 }
2039
2040 void DolphinView::copyPathToClipboard()
2041 {
2042 const KFileItemList list = selectedItems();
2043 if (list.isEmpty()) {
2044 return;
2045 }
2046 const KFileItem& item = list.at(0);
2047 QString path = item.localPath();
2048 if (path.isEmpty()) {
2049 path = item.url().toDisplayString();
2050 }
2051 QClipboard* clipboard = QApplication::clipboard();
2052 if (clipboard == nullptr) {
2053 return;
2054 }
2055 clipboard->setText(path);
2056 }
2057
2058 void DolphinView::slotIncreaseZoom()
2059 {
2060 setZoomLevel(zoomLevel() + 1);
2061 }
2062
2063 void DolphinView::slotDecreaseZoom()
2064 {
2065 setZoomLevel(zoomLevel() - 1);
2066 }
2067
2068 void DolphinView::slotSwipeUp()
2069 {
2070 Q_EMIT goUpRequested();
2071 }
2072
2073 void DolphinView::showLoadingPlaceholder()
2074 {
2075 m_placeholderLabel->setText(i18n("Loading..."));
2076 m_placeholderLabel->setVisible(true);
2077 }
2078
2079 void DolphinView::updatePlaceholderLabel()
2080 {
2081 m_showLoadingPlaceholderTimer->stop();
2082 if (itemsCount() > 0) {
2083 m_placeholderLabel->setVisible(false);
2084 return;
2085 }
2086
2087 if (m_loading) {
2088 m_placeholderLabel->setVisible(false);
2089 m_showLoadingPlaceholderTimer->start();
2090 return;
2091 }
2092
2093 if (!nameFilter().isEmpty()) {
2094 m_placeholderLabel->setText(i18n("No items matching the filter"));
2095 } else if (m_url.scheme() == QLatin1String("baloosearch") || m_url.scheme() == QLatin1String("filenamesearch")) {
2096 m_placeholderLabel->setText(i18n("No items matching the search"));
2097 } else if (m_url.scheme() == QLatin1String("trash") && m_url.path() == QLatin1String("/")) {
2098 m_placeholderLabel->setText(i18n("Trash is empty"));
2099 } else if (m_url.scheme() == QLatin1String("tags")) {
2100 m_placeholderLabel->setText(i18n("No tags"));
2101 } else if (m_url.scheme() == QLatin1String("recentlyused")) {
2102 m_placeholderLabel->setText(i18n("No recently used items"));
2103 } else if (m_url.scheme() == QLatin1String("smb")) {
2104 m_placeholderLabel->setText(i18n("No shared folders found"));
2105 } else if (m_url.scheme() == QLatin1String("network")) {
2106 m_placeholderLabel->setText(i18n("No relevant network resources found"));
2107 } else if (m_url.scheme() == QLatin1String("mtp") && m_url.path() == QLatin1String("/")) {
2108 m_placeholderLabel->setText(i18n("No MTP-compatible devices found"));
2109 } else if (m_url.scheme() == QLatin1String("bluetooth")) {
2110 m_placeholderLabel->setText(i18n("No Bluetooth devices found"));
2111 } else {
2112 m_placeholderLabel->setText(i18n("Folder is empty"));
2113 }
2114
2115 m_placeholderLabel->setVisible(true);
2116 }