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