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