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