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