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