]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
portalize drag urls
[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 #if 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 #include <KUrlMimeData>
49
50 #include <QAbstractItemView>
51 #include <QActionGroup>
52 #include <QApplication>
53 #include <QClipboard>
54 #include <QDropEvent>
55 #include <QGraphicsOpacityEffect>
56 #include <QGraphicsSceneDragDropEvent>
57 #include <QLabel>
58 #include <QMenu>
59 #include <QMimeDatabase>
60 #include <QPixmapCache>
61 #include <QScrollBar>
62 #include <QSize>
63 #include <QTimer>
64 #include <QToolTip>
65 #include <QVBoxLayout>
66
67 DolphinView::DolphinView(const QUrl& url, QWidget* parent) :
68 QWidget(parent),
69 m_active(true),
70 m_tabsForFiles(false),
71 m_assureVisibleCurrentIndex(false),
72 m_isFolderWritable(true),
73 m_dragging(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::sidePaddingChanged,
206 this, &DolphinView::slotSidePaddingWidthChanged);
207
208 KItemListSelectionManager* selectionManager = controller->selectionManager();
209 connect(selectionManager, &KItemListSelectionManager::selectionChanged,
210 this, &DolphinView::slotSelectionChanged);
211
212 #if 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 KUrlMimeData::exportUrlsToPortal(mimeData);
762 QApplication::clipboard()->setMimeData(mimeData);
763 }
764
765 void DolphinView::copySelectedItemsToClipboard()
766 {
767 QMimeData *mimeData = selectionMimeData();
768 KUrlMimeData::exportUrlsToPortal(mimeData);
769 QApplication::clipboard()->setMimeData(mimeData);
770 }
771
772 void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
773 {
774 KIO::CopyJob* job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
775 KJobWidgets::setWindow(job, this);
776
777 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
778 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
779 KIO::FileUndoManager::self()->recordCopyJob(job);
780 }
781
782 void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
783 {
784 KIO::CopyJob* job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
785 KJobWidgets::setWindow(job, this);
786
787 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
788 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
789 KIO::FileUndoManager::self()->recordCopyJob(job);
790
791 }
792
793 void DolphinView::paste()
794 {
795 pasteToUrl(url());
796 }
797
798 void DolphinView::pasteIntoFolder()
799 {
800 const KFileItemList items = selectedItems();
801 if ((items.count() == 1) && items.first().isDir()) {
802 pasteToUrl(items.first().url());
803 }
804 }
805
806 void DolphinView::duplicateSelectedItems()
807 {
808 const KFileItemList itemList = selectedItems();
809 if (itemList.isEmpty()) {
810 return;
811 }
812
813 const QMimeDatabase db;
814
815 // Duplicate all selected items and append "copy" to the end of the file name
816 // but before the filename extension, if present
817 QList<QUrl> newSelection;
818 for (const auto &item : itemList) {
819 const QUrl originalURL = item.url();
820 const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
821 const QString originalFileName = item.name();
822
823 QString extension = db.suffixForFileName(originalFileName);
824
825 QUrl duplicateURL = originalURL;
826
827 // No extension; new filename is "<oldfilename> copy"
828 if (extension.isEmpty()) {
829 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFileName));
830 // There's an extension; new filename is "<oldfilename> copy.<extension>"
831 } else {
832 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
833 extension = QLatin1String(".") + extension;
834 const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size());
835 // Preserve file's original filename extension in case the casing differs
836 // from what QMimeDatabase::suffixForFileName() returned
837 const QString originalExtension = originalFileName.right(extension.size());
838 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension);
839 }
840
841 KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL);
842 KJobWidgets::setWindow(job, this);
843
844 if (job) {
845 newSelection << duplicateURL;
846 KIO::FileUndoManager::self()->recordCopyJob(job);
847 }
848 }
849
850 forceUrlsSelection(newSelection.first(), newSelection);
851 }
852
853 void DolphinView::stopLoading()
854 {
855 m_model->cancelDirectoryLoading();
856 }
857
858 void DolphinView::updatePalette()
859 {
860 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
861 if (!m_active) {
862 color.setAlpha(150);
863 }
864
865 QWidget* viewport = m_container->viewport();
866 if (viewport) {
867 QPalette palette;
868 palette.setColor(viewport->backgroundRole(), color);
869 viewport->setPalette(palette);
870 }
871
872 update();
873 }
874
875 void DolphinView::abortTwoClicksRenaming()
876 {
877 m_twoClicksRenamingItemUrl.clear();
878 m_twoClicksRenamingTimer->stop();
879 }
880
881 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
882 {
883 switch (event->type()) {
884 case QEvent::PaletteChange:
885 updatePalette();
886 QPixmapCache::clear();
887 break;
888
889 case QEvent::WindowActivate:
890 case QEvent::WindowDeactivate:
891 updatePalette();
892 break;
893
894 case QEvent::KeyPress:
895 hideToolTip(ToolTipManager::HideBehavior::Instantly);
896 if (GeneralSettings::useTabForSwitchingSplitView()) {
897 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
898 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
899 Q_EMIT toggleActiveViewRequested();
900 return true;
901 }
902 }
903 break;
904 case QEvent::FocusIn:
905 if (watched == m_container) {
906 setActive(true);
907 }
908 break;
909
910 case QEvent::GraphicsSceneDragEnter:
911 if (watched == m_view) {
912 m_dragging = true;
913 abortTwoClicksRenaming();
914 }
915 break;
916
917 case QEvent::GraphicsSceneDragLeave:
918 if (watched == m_view) {
919 m_dragging = false;
920 }
921 break;
922
923 case QEvent::GraphicsSceneDrop:
924 if (watched == m_view) {
925 m_dragging = false;
926 }
927 break;
928
929 case QEvent::ToolTip:
930 tryShowNameToolTip(static_cast<QHelpEvent*>(event));
931
932 default:
933 break;
934 }
935
936 return QWidget::eventFilter(watched, event);
937 }
938
939 void DolphinView::wheelEvent(QWheelEvent* event)
940 {
941 if (event->modifiers().testFlag(Qt::ControlModifier)) {
942 const QPoint numDegrees = event->angleDelta() / 8;
943 const QPoint numSteps = numDegrees / 15;
944
945 setZoomLevel(zoomLevel() + numSteps.y());
946 event->accept();
947 } else {
948 event->ignore();
949 }
950 }
951
952 void DolphinView::hideEvent(QHideEvent* event)
953 {
954 hideToolTip();
955 QWidget::hideEvent(event);
956 }
957
958 bool DolphinView::event(QEvent* event)
959 {
960 if (event->type() == QEvent::WindowDeactivate) {
961 /* See Bug 297355
962 * Dolphin leaves file preview tooltips open even when is not visible.
963 *
964 * Hide tool-tip when Dolphin loses focus.
965 */
966 hideToolTip();
967 abortTwoClicksRenaming();
968 }
969
970 return QWidget::event(event);
971 }
972
973 void DolphinView::activate()
974 {
975 setActive(true);
976 }
977
978 void DolphinView::slotItemActivated(int index)
979 {
980 abortTwoClicksRenaming();
981
982 const KFileItem item = m_model->fileItem(index);
983 if (!item.isNull()) {
984 Q_EMIT itemActivated(item);
985 }
986 }
987
988 void DolphinView::slotItemsActivated(const KItemSet &indexes)
989 {
990 Q_ASSERT(indexes.count() >= 2);
991
992 abortTwoClicksRenaming();
993
994 const auto modifiers = QGuiApplication::keyboardModifiers();
995
996 if (indexes.count() > 5) {
997 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
998 const int answer = KMessageBox::warningYesNo(this, question);
999 if (answer != KMessageBox::Yes) {
1000 return;
1001 }
1002 }
1003
1004 KFileItemList items;
1005 items.reserve(indexes.count());
1006
1007 for (int index : indexes) {
1008 KFileItem item = m_model->fileItem(index);
1009 const QUrl& url = openItemAsFolderUrl(item);
1010
1011 if (!url.isEmpty()) {
1012 // Open folders in new tabs or in new windows depending on the modifier
1013 // The ctrl+shift behavior is ignored because we are handling multiple items
1014 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1015 if (modifiers & Qt::ShiftModifier && !(modifiers & Qt::ControlModifier)) {
1016 Q_EMIT windowRequested(url);
1017 } else {
1018 Q_EMIT tabRequested(url);
1019 }
1020 } else {
1021 items.append(item);
1022 }
1023 }
1024
1025 if (items.count() == 1) {
1026 Q_EMIT itemActivated(items.first());
1027 } else if (items.count() > 1) {
1028 Q_EMIT itemsActivated(items);
1029 }
1030 }
1031
1032 void DolphinView::slotItemMiddleClicked(int index)
1033 {
1034 const KFileItem& item = m_model->fileItem(index);
1035 const QUrl& url = openItemAsFolderUrl(item);
1036 const auto modifiers = QGuiApplication::keyboardModifiers();
1037 if (!url.isEmpty()) {
1038 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1039 if (modifiers & Qt::ShiftModifier) {
1040 Q_EMIT activeTabRequested(url);
1041 } else {
1042 Q_EMIT tabRequested(url);
1043 }
1044 } else if (isTabsForFilesEnabled()) {
1045 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1046 if (modifiers & Qt::ShiftModifier) {
1047 Q_EMIT activeTabRequested(item.url());
1048 } else {
1049 Q_EMIT tabRequested(item.url());
1050 }
1051 }
1052 }
1053
1054 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
1055 {
1056 // Force emit of a selection changed signal before we request the
1057 // context menu, to update the edit-actions first. (See Bug 294013)
1058 if (m_selectionChangedTimer->isActive()) {
1059 emitSelectionChangedSignal();
1060 }
1061
1062 const KFileItem item = m_model->fileItem(index);
1063 Q_EMIT requestContextMenu(pos.toPoint(), item, selectedItems(), url());
1064 }
1065
1066 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
1067 {
1068 Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), selectedItems(), url());
1069 }
1070
1071 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
1072 {
1073 ViewProperties props(viewPropertiesUrl());
1074
1075 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
1076
1077 KItemListView* view = m_container->controller()->view();
1078 const QList<QByteArray> visibleRolesSet = view->visibleRoles();
1079
1080 bool indexingEnabled = false;
1081 #if HAVE_BALOO
1082 Baloo::IndexerConfig config;
1083 indexingEnabled = config.fileIndexingEnabled();
1084 #endif
1085
1086 QString groupName;
1087 QMenu* groupMenu = nullptr;
1088
1089 // Add all roles to the menu that can be shown or hidden by the user
1090 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
1091 for (const KFileItemModel::RoleInfo& info : rolesInfo) {
1092 if (info.role == "text") {
1093 // It should not be possible to hide the "text" role
1094 continue;
1095 }
1096
1097 const QString text = m_model->roleDescription(info.role);
1098 QAction* action = nullptr;
1099 if (info.group.isEmpty()) {
1100 action = menu->addAction(text);
1101 } else {
1102 if (!groupMenu || info.group != groupName) {
1103 groupName = info.group;
1104 groupMenu = menu->addMenu(groupName);
1105 }
1106
1107 action = groupMenu->addAction(text);
1108 }
1109
1110 action->setCheckable(true);
1111 action->setChecked(visibleRolesSet.contains(info.role));
1112 action->setData(info.role);
1113
1114 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
1115 (info.requiresBaloo) ||
1116 (info.requiresIndexer && indexingEnabled);
1117 action->setEnabled(enable);
1118 }
1119
1120 menu->addSeparator();
1121
1122 QActionGroup* widthsGroup = new QActionGroup(menu);
1123 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
1124
1125 QAction* toggleSidePaddingAction = menu->addAction(i18nc("@action:inmenu", "Side Padding"));
1126 toggleSidePaddingAction->setCheckable(true);
1127 toggleSidePaddingAction->setChecked(view->header()->sidePadding() > 0);
1128
1129 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1130 autoAdjustWidthsAction->setCheckable(true);
1131 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1132 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1133
1134 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1135 customWidthsAction->setCheckable(true);
1136 customWidthsAction->setChecked(!autoColumnWidths);
1137 customWidthsAction->setActionGroup(widthsGroup);
1138
1139 QAction* action = menu->exec(pos.toPoint());
1140 if (menu && action) {
1141 KItemListHeader* header = view->header();
1142
1143 if (action == autoAdjustWidthsAction) {
1144 // Clear the column-widths from the viewproperties and turn on
1145 // the automatic resizing of the columns
1146 props.setHeaderColumnWidths(QList<int>());
1147 header->setAutomaticColumnResizing(true);
1148 } else if (action == customWidthsAction) {
1149 // Apply the current column-widths as custom column-widths and turn
1150 // off the automatic resizing of the columns
1151 QList<int> columnWidths;
1152 const auto visibleRoles = view->visibleRoles();
1153 columnWidths.reserve(visibleRoles.count());
1154 for (const QByteArray& role : visibleRoles) {
1155 columnWidths.append(header->columnWidth(role));
1156 }
1157 props.setHeaderColumnWidths(columnWidths);
1158 header->setAutomaticColumnResizing(false);
1159 } else if (action == toggleSidePaddingAction) {
1160 header->setSidePadding(toggleSidePaddingAction->isChecked() ? 20 : 0);
1161 } else {
1162 // Show or hide the selected role
1163 const QByteArray selectedRole = action->data().toByteArray();
1164
1165 QList<QByteArray> visibleRoles = view->visibleRoles();
1166 if (action->isChecked()) {
1167 visibleRoles.append(selectedRole);
1168 } else {
1169 visibleRoles.removeOne(selectedRole);
1170 }
1171
1172 view->setVisibleRoles(visibleRoles);
1173 props.setVisibleRoles(visibleRoles);
1174
1175 QList<int> columnWidths;
1176 if (!header->automaticColumnResizing()) {
1177 const auto visibleRoles = view->visibleRoles();
1178 columnWidths.reserve(visibleRoles.count());
1179 for (const QByteArray& role : visibleRoles) {
1180 columnWidths.append(header->columnWidth(role));
1181 }
1182 }
1183 props.setHeaderColumnWidths(columnWidths);
1184 }
1185 }
1186
1187 delete menu;
1188 }
1189
1190 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1191 {
1192 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1193
1194 ViewProperties props(viewPropertiesUrl());
1195 QList<int> columnWidths = props.headerColumnWidths();
1196 if (columnWidths.count() != visibleRoles.count()) {
1197 columnWidths.clear();
1198 columnWidths.reserve(visibleRoles.count());
1199 const KItemListHeader* header = m_view->header();
1200 for (const QByteArray& role : visibleRoles) {
1201 const int width = header->columnWidth(role);
1202 columnWidths.append(width);
1203 }
1204 }
1205
1206 const int roleIndex = visibleRoles.indexOf(role);
1207 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1208 columnWidths[roleIndex] = current;
1209
1210 props.setHeaderColumnWidths(columnWidths);
1211 }
1212
1213 void DolphinView::slotSidePaddingWidthChanged(qreal width)
1214 {
1215 ViewProperties props(viewPropertiesUrl());
1216 DetailsModeSettings::setSidePadding(int(width));
1217 m_view->writeSettings();
1218 }
1219
1220 void DolphinView::slotItemHovered(int index)
1221 {
1222 const KFileItem item = m_model->fileItem(index);
1223
1224 if (GeneralSettings::showToolTips() && !m_dragging) {
1225 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1226 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1227 itemRect.moveTo(pos);
1228
1229 #if HAVE_BALOO
1230 auto nativeParent = nativeParentWidget();
1231 if (nativeParent) {
1232 m_toolTipManager->showToolTip(item, itemRect, nativeParent->windowHandle());
1233 }
1234 #endif
1235 }
1236
1237 Q_EMIT requestItemInfo(item);
1238 }
1239
1240 void DolphinView::slotItemUnhovered(int index)
1241 {
1242 Q_UNUSED(index)
1243 hideToolTip();
1244 Q_EMIT requestItemInfo(KFileItem());
1245 }
1246
1247 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1248 {
1249 QUrl destUrl;
1250 KFileItem destItem = m_model->fileItem(index);
1251 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1252 // Use the URL of the view as drop target if the item is no directory
1253 // or desktop-file
1254 destItem = m_model->rootItem();
1255 destUrl = url();
1256 } else {
1257 // The item represents a directory or desktop-file
1258 destUrl = destItem.mostLocalUrl();
1259 }
1260
1261 QDropEvent dropEvent(event->pos().toPoint(),
1262 event->possibleActions(),
1263 event->mimeData(),
1264 event->buttons(),
1265 event->modifiers());
1266 dropUrls(destUrl, &dropEvent, this);
1267
1268 setActive(true);
1269 }
1270
1271 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1272 {
1273 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1274
1275 if (job) {
1276 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1277
1278 if (destUrl == url()) {
1279 // Mark the dropped urls as selected.
1280 m_clearSelectionBeforeSelectingNewItems = true;
1281 m_markFirstNewlySelectedItemAsCurrent = true;
1282 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1283 }
1284 }
1285 }
1286
1287 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1288 {
1289 if (previous != nullptr) {
1290 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1291 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1292 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1293 m_versionControlObserver->setModel(nullptr);
1294 }
1295
1296 if (current) {
1297 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1298 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1299 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1300 m_versionControlObserver->setModel(fileItemModel);
1301 }
1302 }
1303
1304 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1305 {
1306 Q_UNUSED(itemIndex)
1307
1308 hideToolTip();
1309
1310 if (buttons & Qt::BackButton) {
1311 Q_EMIT goBackRequested();
1312 } else if (buttons & Qt::ForwardButton) {
1313 Q_EMIT goForwardRequested();
1314 }
1315 }
1316
1317 void DolphinView::slotSelectedItemTextPressed(int index)
1318 {
1319 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1320 const KFileItem item = m_model->fileItem(index);
1321 const KFileItemListProperties capabilities(KFileItemList() << item);
1322 if (capabilities.supportsMoving()) {
1323 m_twoClicksRenamingItemUrl = item.url();
1324 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1325 }
1326 }
1327 }
1328
1329 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1330 {
1331 slotItemCreated(to);
1332 }
1333
1334 void DolphinView::slotItemCreated(const QUrl& url)
1335 {
1336 if (m_markFirstNewlySelectedItemAsCurrent) {
1337 markUrlAsCurrent(url);
1338 m_markFirstNewlySelectedItemAsCurrent = false;
1339 }
1340 m_selectedUrls << url;
1341 }
1342
1343 void DolphinView::slotJobResult(KJob *job)
1344 {
1345 if (job->error()) {
1346 Q_EMIT errorMessage(job->errorString());
1347 }
1348 if (!m_selectedUrls.isEmpty()) {
1349 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1350 }
1351 }
1352
1353 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1354 {
1355 const int currentCount = current.count();
1356 const int previousCount = previous.count();
1357 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1358 (currentCount > 0 && previousCount == 0);
1359
1360 // If nothing has been selected before and something got selected (or if something
1361 // was selected before and now nothing is selected) the selectionChangedSignal must
1362 // be emitted asynchronously as fast as possible to update the edit-actions.
1363 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1364 m_selectionChangedTimer->start();
1365 }
1366
1367 void DolphinView::emitSelectionChangedSignal()
1368 {
1369 m_selectionChangedTimer->stop();
1370 Q_EMIT selectionChanged(selectedItems());
1371 }
1372
1373 void DolphinView::slotStatJobResult(KJob *job)
1374 {
1375 int folderCount = 0;
1376 int fileCount = 0;
1377 KIO::filesize_t totalFileSize = 0;
1378 bool countFileSize = true;
1379
1380 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1381 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1382 // We have a precomputed value.
1383 totalFileSize = static_cast<KIO::filesize_t>(
1384 entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1385 countFileSize = false;
1386 }
1387
1388 const int itemCount = m_model->count();
1389 for (int i = 0; i < itemCount; ++i) {
1390 const KFileItem item = m_model->fileItem(i);
1391 if (item.isDir()) {
1392 ++folderCount;
1393 } else {
1394 ++fileCount;
1395 if (countFileSize) {
1396 totalFileSize += item.size();
1397 }
1398 }
1399 }
1400 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1401 }
1402
1403 void DolphinView::updateSortRole(const QByteArray& role)
1404 {
1405 ViewProperties props(viewPropertiesUrl());
1406 props.setSortRole(role);
1407
1408 KItemModelBase* model = m_container->controller()->model();
1409 model->setSortRole(role);
1410
1411 Q_EMIT sortRoleChanged(role);
1412 }
1413
1414 void DolphinView::updateSortOrder(Qt::SortOrder order)
1415 {
1416 ViewProperties props(viewPropertiesUrl());
1417 props.setSortOrder(order);
1418
1419 m_model->setSortOrder(order);
1420
1421 Q_EMIT sortOrderChanged(order);
1422 }
1423
1424 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1425 {
1426 ViewProperties props(viewPropertiesUrl());
1427 props.setSortFoldersFirst(foldersFirst);
1428
1429 m_model->setSortDirectoriesFirst(foldersFirst);
1430
1431 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1432 }
1433
1434 void DolphinView::updateSortHiddenLast(bool hiddenLast)
1435 {
1436 ViewProperties props(viewPropertiesUrl());
1437 props.setSortHiddenLast(hiddenLast);
1438
1439 m_model->setSortHiddenLast(hiddenLast);
1440
1441 Q_EMIT sortHiddenLastChanged(hiddenLast);
1442 }
1443
1444
1445 QPair<bool, QString> DolphinView::pasteInfo() const
1446 {
1447 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1448 QPair<bool, QString> info;
1449 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1450 return info;
1451 }
1452
1453 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1454 {
1455 m_tabsForFiles = tabsForFiles;
1456 }
1457
1458 bool DolphinView::isTabsForFilesEnabled() const
1459 {
1460 return m_tabsForFiles;
1461 }
1462
1463 bool DolphinView::itemsExpandable() const
1464 {
1465 return m_mode == DetailsView;
1466 }
1467
1468 void DolphinView::restoreState(QDataStream& stream)
1469 {
1470 // Read the version number of the view state and check if the version is supported.
1471 quint32 version = 0;
1472 stream >> version;
1473 if (version != 1) {
1474 // The version of the view state isn't supported, we can't restore it.
1475 return;
1476 }
1477
1478 // Restore the current item that had the keyboard focus
1479 stream >> m_currentItemUrl;
1480
1481 // Restore the previously selected items
1482 stream >> m_selectedUrls;
1483
1484 // Restore the view position
1485 stream >> m_restoredContentsPosition;
1486
1487 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1488 QSet<QUrl> urls;
1489 stream >> urls;
1490 m_model->restoreExpandedDirectories(urls);
1491 }
1492
1493 void DolphinView::saveState(QDataStream& stream)
1494 {
1495 stream << quint32(1); // View state version
1496
1497 // Save the current item that has the keyboard focus
1498 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1499 if (currentIndex != -1) {
1500 KFileItem item = m_model->fileItem(currentIndex);
1501 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1502 QUrl currentItemUrl = item.url();
1503 stream << currentItemUrl;
1504 } else {
1505 stream << QUrl();
1506 }
1507
1508 // Save the selected urls
1509 stream << selectedItems().urlList();
1510
1511 // Save view position
1512 const qreal x = m_container->horizontalScrollBar()->value();
1513 const qreal y = m_container->verticalScrollBar()->value();
1514 stream << QPoint(x, y);
1515
1516 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1517 stream << m_model->expandedDirectories();
1518 }
1519
1520 KFileItem DolphinView::rootItem() const
1521 {
1522 return m_model->rootItem();
1523 }
1524
1525 void DolphinView::setViewPropertiesContext(const QString& context)
1526 {
1527 m_viewPropertiesContext = context;
1528 }
1529
1530 QString DolphinView::viewPropertiesContext() const
1531 {
1532 return m_viewPropertiesContext;
1533 }
1534
1535 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1536 {
1537 if (item.isNull()) {
1538 return QUrl();
1539 }
1540
1541 QUrl url = item.targetUrl();
1542
1543 if (item.isDir()) {
1544 return url;
1545 }
1546
1547 if (item.isMimeTypeKnown()) {
1548 const QString& mimetype = item.mimetype();
1549
1550 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1551 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1552 // zip:/<path>/ when clicking on a zip file, etc.
1553 // The .protocol file specifies the mimetype that the kioslave handles.
1554 // Note that we don't use mimetype inheritance since we don't want to
1555 // open OpenDocument files as zip folders...
1556 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1557 if (!protocol.isEmpty()) {
1558 url.setScheme(protocol);
1559 return url;
1560 }
1561 }
1562
1563 if (mimetype == QLatin1String("application/x-desktop")) {
1564 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1565 KDesktopFile desktopFile(url.toLocalFile());
1566 if (desktopFile.hasLinkType()) {
1567 const QString linkUrl = desktopFile.readUrl();
1568 if (!linkUrl.startsWith(QLatin1String("http"))) {
1569 return QUrl::fromUserInput(linkUrl);
1570 }
1571 }
1572 }
1573 }
1574
1575 return QUrl();
1576 }
1577
1578 void DolphinView::resetZoomLevel()
1579 {
1580 ViewModeSettings settings{m_mode};
1581 settings.useDefaults(true);
1582 const int defaultIconSize = settings.iconSize();
1583 settings.useDefaults(false);
1584
1585 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize)));
1586 }
1587
1588 void DolphinView::observeCreatedItem(const QUrl& url)
1589 {
1590 if (m_active) {
1591 forceUrlsSelection(url, {url});
1592 }
1593 }
1594
1595 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1596 {
1597 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1598 Q_EMIT redirection(oldUrl, newUrl);
1599 m_url = newUrl; // #186947
1600 }
1601 }
1602
1603 void DolphinView::updateViewState()
1604 {
1605 if (m_currentItemUrl != QUrl()) {
1606 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1607
1608 // if there is a selection already, leave it that way
1609 if (!selectionManager->hasSelection()) {
1610 const int currentIndex = m_model->index(m_currentItemUrl);
1611 if (currentIndex != -1) {
1612 selectionManager->setCurrentItem(currentIndex);
1613
1614 // scroll to current item and reset the state
1615 if (m_scrollToCurrentItem) {
1616 m_view->scrollToItem(currentIndex);
1617 m_scrollToCurrentItem = false;
1618 }
1619 m_currentItemUrl = QUrl();
1620 } else {
1621 selectionManager->setCurrentItem(0);
1622 }
1623 } else {
1624 m_currentItemUrl = QUrl();
1625 }
1626 }
1627
1628 if (!m_restoredContentsPosition.isNull()) {
1629 const int x = m_restoredContentsPosition.x();
1630 const int y = m_restoredContentsPosition.y();
1631 m_restoredContentsPosition = QPoint();
1632
1633 m_container->horizontalScrollBar()->setValue(x);
1634 m_container->verticalScrollBar()->setValue(y);
1635 }
1636
1637 if (!m_selectedUrls.isEmpty()) {
1638 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1639
1640 // if there is a selection already, leave it that way
1641 if (!selectionManager->hasSelection()) {
1642 if (m_clearSelectionBeforeSelectingNewItems) {
1643 selectionManager->clearSelection();
1644 m_clearSelectionBeforeSelectingNewItems = false;
1645 }
1646
1647 KItemSet selectedItems = selectionManager->selectedItems();
1648
1649 QList<QUrl>::iterator it = m_selectedUrls.begin();
1650 while (it != m_selectedUrls.end()) {
1651 const int index = m_model->index(*it);
1652 if (index >= 0) {
1653 selectedItems.insert(index);
1654 it = m_selectedUrls.erase(it);
1655 } else {
1656 ++it;
1657 }
1658 }
1659
1660 if (!selectedItems.isEmpty()) {
1661 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1662 selectionManager->setSelectedItems(selectedItems);
1663 }
1664 }
1665 }
1666 }
1667
1668 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1669 {
1670 if (GeneralSettings::showToolTips()) {
1671 #if HAVE_BALOO
1672 m_toolTipManager->hideToolTip(behavior);
1673 #else
1674 Q_UNUSED(behavior)
1675 #endif
1676 } else if (m_mode == DolphinView::IconsView) {
1677 QToolTip::hideText();
1678 }
1679 }
1680
1681 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1682 {
1683 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1684
1685 // verify that only one item is selected
1686 if (selectionManager->selectedItems().count() == 1) {
1687 const int index = selectionManager->currentItem();
1688 const QUrl fileItemUrl = m_model->fileItem(index).url();
1689
1690 // check if the selected item was the same item that started the twoClicksRenaming
1691 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1692 renameSelectedItems();
1693 }
1694 }
1695 }
1696
1697 void DolphinView::slotTrashFileFinished(KJob* job)
1698 {
1699 if (job->error() == 0) {
1700 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1701 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1702 Q_EMIT errorMessage(job->errorString());
1703 }
1704 }
1705
1706 void DolphinView::slotDeleteFileFinished(KJob* job)
1707 {
1708 if (job->error() == 0) {
1709 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1710 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1711 Q_EMIT errorMessage(job->errorString());
1712 }
1713 }
1714
1715 void DolphinView::slotRenamingResult(KJob* job)
1716 {
1717 if (job->error()) {
1718 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1719 Q_ASSERT(copyJob);
1720 const QUrl newUrl = copyJob->destUrl();
1721 const int index = m_model->index(newUrl);
1722 if (index >= 0) {
1723 QHash<QByteArray, QVariant> data;
1724 const QUrl oldUrl = copyJob->srcUrls().at(0);
1725 data.insert("text", oldUrl.fileName());
1726 m_model->setData(index, data);
1727 }
1728 }
1729 }
1730
1731 void DolphinView::slotDirectoryLoadingStarted()
1732 {
1733 m_loadingState = LoadingState::Loading;
1734 updatePlaceholderLabel();
1735
1736 // Disable the writestate temporary until it can be determined in a fast way
1737 // in DolphinView::slotDirectoryLoadingCompleted()
1738 if (m_isFolderWritable) {
1739 m_isFolderWritable = false;
1740 Q_EMIT writeStateChanged(m_isFolderWritable);
1741 }
1742
1743 Q_EMIT directoryLoadingStarted();
1744 }
1745
1746 void DolphinView::slotDirectoryLoadingCompleted()
1747 {
1748 m_loadingState = LoadingState::Completed;
1749
1750 // Update the view-state. This has to be done asynchronously
1751 // because the view might not be in its final state yet.
1752 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1753
1754 // Update the placeholder label in case we found that the folder was empty
1755 // after loading it
1756
1757 Q_EMIT directoryLoadingCompleted();
1758
1759 updatePlaceholderLabel();
1760 updateWritableState();
1761 }
1762
1763 void DolphinView::slotDirectoryLoadingCanceled()
1764 {
1765 m_loadingState = LoadingState::Canceled;
1766
1767 updatePlaceholderLabel();
1768
1769 Q_EMIT directoryLoadingCanceled();
1770 }
1771
1772 void DolphinView::slotItemsChanged()
1773 {
1774 m_assureVisibleCurrentIndex = false;
1775 }
1776
1777 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1778 {
1779 Q_UNUSED(previous)
1780 Q_ASSERT(m_model->sortOrder() == current);
1781
1782 ViewProperties props(viewPropertiesUrl());
1783 props.setSortOrder(current);
1784
1785 Q_EMIT sortOrderChanged(current);
1786 }
1787
1788 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1789 {
1790 Q_UNUSED(previous)
1791 Q_ASSERT(m_model->sortRole() == current);
1792
1793 ViewProperties props(viewPropertiesUrl());
1794 props.setSortRole(current);
1795
1796 Q_EMIT sortRoleChanged(current);
1797 }
1798
1799 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1800 const QList<QByteArray>& previous)
1801 {
1802 Q_UNUSED(previous)
1803 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1804
1805 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1806
1807 m_visibleRoles = current;
1808
1809 ViewProperties props(viewPropertiesUrl());
1810 props.setVisibleRoles(m_visibleRoles);
1811
1812 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1813 }
1814
1815 void DolphinView::slotRoleEditingCanceled()
1816 {
1817 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1818 this, &DolphinView::slotRoleEditingFinished);
1819 }
1820
1821 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1822 {
1823 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1824 this, &DolphinView::slotRoleEditingFinished);
1825
1826 const KFileItemList items = selectedItems();
1827 if (items.count() != 1) {
1828 return;
1829 }
1830
1831 if (role == "text") {
1832 const KFileItem oldItem = items.first();
1833 const EditResult retVal = value.value<EditResult>();
1834 const QString newName = retVal.newName;
1835 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1836 const QUrl oldUrl = oldItem.url();
1837
1838 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1839 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1840
1841 #ifndef Q_OS_WIN
1842 //Confirm hiding file/directory by renaming inline
1843 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1844 KGuiItem yesGuiItem(KStandardGuiItem::yes());
1845 yesGuiItem.setText(i18nc("@action:button", "Rename and Hide"));
1846
1847 const auto code = KMessageBox::questionYesNo(this,
1848 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1849 "Do you still want to rename it?")
1850 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1851 "Do you still want to rename it?"),
1852 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1853 yesGuiItem,
1854 KStandardGuiItem::cancel(),
1855 QStringLiteral("ConfirmHide")
1856 );
1857
1858 if (code == KMessageBox::No) {
1859 return;
1860 }
1861 }
1862 #endif
1863
1864 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1865 if (!newNameExistsAlready && m_model->index(oldUrl) == index) {
1866 // Only change the data in the model if no item with the new name
1867 // is in the model yet. If there is an item with the new name
1868 // already, calling KIO::CopyJob will open a dialog
1869 // asking for a new name, and KFileItemModel will update the
1870 // data when the dir lister signals that the file name has changed.
1871 QHash<QByteArray, QVariant> data;
1872 data.insert(role, retVal.newName);
1873 m_model->setData(index, data);
1874 }
1875
1876 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1877 KJobWidgets::setWindow(job, this);
1878 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1879 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1880
1881 forceUrlsSelection(newUrl, {newUrl});
1882
1883 if (!newNameExistsAlready) {
1884 // Only connect the result signal if there is no item with the new name
1885 // in the model yet, see bug 328262.
1886 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1887 }
1888 }
1889 if (retVal.direction != EditDone) {
1890 const short indexShift = retVal.direction == EditNext ? 1 : -1;
1891 m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect);
1892 m_container->controller()->selectionManager()->setSelected(index + indexShift, 1,
1893 KItemListSelectionManager::Select);
1894 renameSelectedItems();
1895 }
1896 }
1897 }
1898
1899 void DolphinView::loadDirectory(const QUrl& url, bool reload)
1900 {
1901 if (!url.isValid()) {
1902 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1903 if (location.isEmpty()) {
1904 Q_EMIT errorMessage(i18nc("@info:status", "The location is empty."));
1905 } else {
1906 Q_EMIT errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1907 }
1908 return;
1909 }
1910
1911 if (reload) {
1912 m_model->refreshDirectory(url);
1913 } else {
1914 m_model->loadDirectory(url);
1915 }
1916 }
1917
1918 void DolphinView::applyViewProperties()
1919 {
1920 const ViewProperties props(viewPropertiesUrl());
1921 applyViewProperties(props);
1922 }
1923
1924 void DolphinView::applyViewProperties(const ViewProperties& props)
1925 {
1926 m_view->beginTransaction();
1927
1928 const Mode mode = props.viewMode();
1929 if (m_mode != mode) {
1930 const Mode previousMode = m_mode;
1931 m_mode = mode;
1932
1933 // Changing the mode might result in changing
1934 // the zoom level. Remember the old zoom level so
1935 // that zoomLevelChanged() can get emitted.
1936 const int oldZoomLevel = m_view->zoomLevel();
1937 applyModeToView();
1938
1939 Q_EMIT modeChanged(m_mode, previousMode);
1940
1941 if (m_view->zoomLevel() != oldZoomLevel) {
1942 Q_EMIT zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1943 }
1944 }
1945
1946 const bool hiddenFilesShown = props.hiddenFilesShown();
1947 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1948 m_model->setShowHiddenFiles(hiddenFilesShown);
1949 Q_EMIT hiddenFilesShownChanged(hiddenFilesShown);
1950 }
1951
1952 const bool groupedSorting = props.groupedSorting();
1953 if (groupedSorting != m_model->groupedSorting()) {
1954 m_model->setGroupedSorting(groupedSorting);
1955 Q_EMIT groupedSortingChanged(groupedSorting);
1956 }
1957
1958 const QByteArray sortRole = props.sortRole();
1959 if (sortRole != m_model->sortRole()) {
1960 m_model->setSortRole(sortRole);
1961 Q_EMIT sortRoleChanged(sortRole);
1962 }
1963
1964 const Qt::SortOrder sortOrder = props.sortOrder();
1965 if (sortOrder != m_model->sortOrder()) {
1966 m_model->setSortOrder(sortOrder);
1967 Q_EMIT sortOrderChanged(sortOrder);
1968 }
1969
1970 const bool sortFoldersFirst = props.sortFoldersFirst();
1971 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1972 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1973 Q_EMIT sortFoldersFirstChanged(sortFoldersFirst);
1974 }
1975
1976 const bool sortHiddenLast = props.sortHiddenLast();
1977 if (sortHiddenLast != m_model->sortHiddenLast()) {
1978 m_model->setSortHiddenLast(sortHiddenLast);
1979 Q_EMIT sortHiddenLastChanged(sortHiddenLast);
1980 }
1981
1982 const QList<QByteArray> visibleRoles = props.visibleRoles();
1983 if (visibleRoles != m_visibleRoles) {
1984 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1985 m_visibleRoles = visibleRoles;
1986 m_view->setVisibleRoles(visibleRoles);
1987 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1988 }
1989
1990 const bool previewsShown = props.previewsShown();
1991 if (previewsShown != m_view->previewsShown()) {
1992 const int oldZoomLevel = zoomLevel();
1993
1994 m_view->setPreviewsShown(previewsShown);
1995 Q_EMIT previewsShownChanged(previewsShown);
1996
1997 // Changing the preview-state might result in a changed zoom-level
1998 if (oldZoomLevel != zoomLevel()) {
1999 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
2000 }
2001 }
2002
2003 KItemListView* itemListView = m_container->controller()->view();
2004 if (itemListView->isHeaderVisible()) {
2005 KItemListHeader* header = itemListView->header();
2006 const QList<int> headerColumnWidths = props.headerColumnWidths();
2007 const int rolesCount = m_visibleRoles.count();
2008 if (headerColumnWidths.count() == rolesCount) {
2009 header->setAutomaticColumnResizing(false);
2010
2011 QHash<QByteArray, qreal> columnWidths;
2012 for (int i = 0; i < rolesCount; ++i) {
2013 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
2014 }
2015 header->setColumnWidths(columnWidths);
2016 } else {
2017 header->setAutomaticColumnResizing(true);
2018 }
2019 header->setSidePadding(DetailsModeSettings::sidePadding());
2020 }
2021
2022 m_view->endTransaction();
2023 }
2024
2025 void DolphinView::applyModeToView()
2026 {
2027 switch (m_mode) {
2028 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
2029 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
2030 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
2031 default: Q_ASSERT(false); break;
2032 }
2033 }
2034
2035 void DolphinView::pasteToUrl(const QUrl& url)
2036 {
2037 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
2038 KJobWidgets::setWindow(job, this);
2039 m_clearSelectionBeforeSelectingNewItems = true;
2040 m_markFirstNewlySelectedItemAsCurrent = true;
2041 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
2042 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotJobResult);
2043 }
2044
2045 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
2046 {
2047 QList<QUrl> urls;
2048
2049 const KFileItemList items = selectedItems();
2050 urls.reserve(items.count());
2051 for (const KFileItem& item : items) {
2052 urls.append(item.url());
2053 }
2054
2055 if (itemsExpandable()) {
2056 // TODO: Check if we still need KDirModel for this in KDE 5.0
2057 urls = KDirModel::simplifiedUrlList(urls);
2058 }
2059
2060 return urls;
2061 }
2062
2063 QMimeData* DolphinView::selectionMimeData() const
2064 {
2065 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
2066 const KItemSet selectedIndexes = selectionManager->selectedItems();
2067
2068 return m_model->createMimeData(selectedIndexes);
2069 }
2070
2071 void DolphinView::updateWritableState()
2072 {
2073 const bool wasFolderWritable = m_isFolderWritable;
2074 m_isFolderWritable = false;
2075
2076 KFileItem item = m_model->rootItem();
2077 if (item.isNull()) {
2078 // Try to find out if the URL is writable even if the "root item" is
2079 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2080 item = KFileItem(url());
2081 item.setDelayedMimeTypes(true);
2082 }
2083
2084 KFileItemListProperties capabilities(KFileItemList() << item);
2085 m_isFolderWritable = capabilities.supportsWriting();
2086
2087 if (m_isFolderWritable != wasFolderWritable) {
2088 Q_EMIT writeStateChanged(m_isFolderWritable);
2089 }
2090 }
2091
2092 QUrl DolphinView::viewPropertiesUrl() const
2093 {
2094 if (m_viewPropertiesContext.isEmpty()) {
2095 return m_url;
2096 }
2097
2098 QUrl url;
2099 url.setScheme(m_url.scheme());
2100 url.setPath(m_viewPropertiesContext);
2101 return url;
2102 }
2103
2104 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
2105 {
2106 forceUrlsSelection(urls.first(), urls);
2107 }
2108
2109 void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
2110 {
2111 clearSelection();
2112 m_clearSelectionBeforeSelectingNewItems = true;
2113 markUrlAsCurrent(current);
2114 markUrlsAsSelected(selected);
2115 }
2116
2117 void DolphinView::copyPathToClipboard()
2118 {
2119 const KFileItemList list = selectedItems();
2120 if (list.isEmpty()) {
2121 return;
2122 }
2123 const KFileItem& item = list.at(0);
2124 QString path = item.localPath();
2125 if (path.isEmpty()) {
2126 path = item.url().toDisplayString();
2127 }
2128 QClipboard* clipboard = QApplication::clipboard();
2129 if (clipboard == nullptr) {
2130 return;
2131 }
2132 clipboard->setText(path);
2133 }
2134
2135 void DolphinView::slotIncreaseZoom()
2136 {
2137 setZoomLevel(zoomLevel() + 1);
2138 }
2139
2140 void DolphinView::slotDecreaseZoom()
2141 {
2142 setZoomLevel(zoomLevel() - 1);
2143 }
2144
2145 void DolphinView::slotSwipeUp()
2146 {
2147 Q_EMIT goUpRequested();
2148 }
2149
2150 void DolphinView::showLoadingPlaceholder()
2151 {
2152 m_placeholderLabel->setText(i18n("Loading..."));
2153 m_placeholderLabel->setVisible(true);
2154 }
2155
2156 void DolphinView::updatePlaceholderLabel()
2157 {
2158 m_showLoadingPlaceholderTimer->stop();
2159 if (itemsCount() > 0) {
2160 m_placeholderLabel->setVisible(false);
2161 return;
2162 }
2163
2164 if (m_loadingState == LoadingState::Loading) {
2165 m_placeholderLabel->setVisible(false);
2166 m_showLoadingPlaceholderTimer->start();
2167 return;
2168 }
2169
2170 if (m_loadingState == LoadingState::Canceled) {
2171 m_placeholderLabel->setText(i18n("Loading canceled"));
2172 } else if (!nameFilter().isEmpty()) {
2173 m_placeholderLabel->setText(i18n("No items matching the filter"));
2174 } else if (m_url.scheme() == QLatin1String("baloosearch") || m_url.scheme() == QLatin1String("filenamesearch")) {
2175 m_placeholderLabel->setText(i18n("No items matching the search"));
2176 } else if (m_url.scheme() == QLatin1String("trash") && m_url.path() == QLatin1String("/")) {
2177 m_placeholderLabel->setText(i18n("Trash is empty"));
2178 } else if (m_url.scheme() == QLatin1String("tags")) {
2179 if (m_url.path() == QLatin1Char('/')) {
2180 m_placeholderLabel->setText(i18n("No tags"));
2181 } else {
2182 const QString tagName = m_url.path().mid(1); // Remove leading /
2183 m_placeholderLabel->setText(i18n("No files tagged with \"%1\"", tagName));
2184 }
2185
2186 } else if (m_url.scheme() == QLatin1String("recentlyused")) {
2187 m_placeholderLabel->setText(i18n("No recently used items"));
2188 } else if (m_url.scheme() == QLatin1String("smb")) {
2189 m_placeholderLabel->setText(i18n("No shared folders found"));
2190 } else if (m_url.scheme() == QLatin1String("network")) {
2191 m_placeholderLabel->setText(i18n("No relevant network resources found"));
2192 } else if (m_url.scheme() == QLatin1String("mtp") && m_url.path() == QLatin1String("/")) {
2193 m_placeholderLabel->setText(i18n("No MTP-compatible devices found"));
2194 } else if (m_url.scheme() == QLatin1String("bluetooth")) {
2195 m_placeholderLabel->setText(i18n("No Bluetooth devices found"));
2196 } else {
2197 m_placeholderLabel->setText(i18n("Folder is empty"));
2198 }
2199
2200 m_placeholderLabel->setVisible(true);
2201 }
2202
2203 void DolphinView::tryShowNameToolTip(QHelpEvent* event)
2204 {
2205 if (!GeneralSettings::showToolTips() && m_mode == DolphinView::IconsView) {
2206 const std::optional<int> index = m_view->itemAt(event->pos());
2207
2208 if (!index.has_value()) {
2209 return;
2210 }
2211
2212 // Check whether the filename has been elided
2213 const bool isElided = m_view->isElided(index.value());
2214
2215 if(isElided) {
2216 const KFileItem item = m_model->fileItem(index.value());
2217 const QString text = item.text();
2218 const QPoint pos = mapToGlobal(event->pos());
2219 QToolTip::showText(pos, text);
2220 }
2221 }
2222 }