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