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