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