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