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