]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Merge branch 'release/21.12'
[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 const auto modifiers = QGuiApplication::keyboardModifiers();
984
985 if (indexes.count() > 5) {
986 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
987 const int answer = KMessageBox::warningYesNo(this, question);
988 if (answer != KMessageBox::Yes) {
989 return;
990 }
991 }
992
993 KFileItemList items;
994 items.reserve(indexes.count());
995
996 for (int index : indexes) {
997 KFileItem item = m_model->fileItem(index);
998 const QUrl& url = openItemAsFolderUrl(item);
999
1000 if (!url.isEmpty()) {
1001 // Open folders in new tabs or in new windows depending on the modifier
1002 // The ctrl+shift behavior is ignored because we are handling multiple items
1003 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1004 if (modifiers & Qt::ShiftModifier && !(modifiers & Qt::ControlModifier)) {
1005 Q_EMIT windowRequested(url);
1006 } else {
1007 Q_EMIT tabRequested(url);
1008 }
1009 } else {
1010 items.append(item);
1011 }
1012 }
1013
1014 if (items.count() == 1) {
1015 Q_EMIT itemActivated(items.first());
1016 } else if (items.count() > 1) {
1017 Q_EMIT itemsActivated(items);
1018 }
1019 }
1020
1021 void DolphinView::slotItemMiddleClicked(int index)
1022 {
1023 const KFileItem& item = m_model->fileItem(index);
1024 const QUrl& url = openItemAsFolderUrl(item);
1025 const auto modifiers = QGuiApplication::keyboardModifiers();
1026 if (!url.isEmpty()) {
1027 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1028 if (modifiers & Qt::ShiftModifier) {
1029 Q_EMIT activeTabRequested(url);
1030 } else {
1031 Q_EMIT tabRequested(url);
1032 }
1033 } else if (isTabsForFilesEnabled()) {
1034 // keep in sync with KUrlNavigator::slotNavigatorButtonClicked
1035 if (modifiers & Qt::ShiftModifier) {
1036 Q_EMIT activeTabRequested(item.url());
1037 } else {
1038 Q_EMIT tabRequested(item.url());
1039 }
1040 }
1041 }
1042
1043 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
1044 {
1045 // Force emit of a selection changed signal before we request the
1046 // context menu, to update the edit-actions first. (See Bug 294013)
1047 if (m_selectionChangedTimer->isActive()) {
1048 emitSelectionChangedSignal();
1049 }
1050
1051 const KFileItem item = m_model->fileItem(index);
1052 Q_EMIT requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
1053 }
1054
1055 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
1056 {
1057 Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
1058 }
1059
1060 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
1061 {
1062 ViewProperties props(viewPropertiesUrl());
1063
1064 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
1065
1066 KItemListView* view = m_container->controller()->view();
1067 const QList<QByteArray> visibleRolesSet = view->visibleRoles();
1068
1069 bool indexingEnabled = false;
1070 #ifdef HAVE_BALOO
1071 Baloo::IndexerConfig config;
1072 indexingEnabled = config.fileIndexingEnabled();
1073 #endif
1074
1075 QString groupName;
1076 QMenu* groupMenu = nullptr;
1077
1078 // Add all roles to the menu that can be shown or hidden by the user
1079 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
1080 for (const KFileItemModel::RoleInfo& info : rolesInfo) {
1081 if (info.role == "text") {
1082 // It should not be possible to hide the "text" role
1083 continue;
1084 }
1085
1086 const QString text = m_model->roleDescription(info.role);
1087 QAction* action = nullptr;
1088 if (info.group.isEmpty()) {
1089 action = menu->addAction(text);
1090 } else {
1091 if (!groupMenu || info.group != groupName) {
1092 groupName = info.group;
1093 groupMenu = menu->addMenu(groupName);
1094 }
1095
1096 action = groupMenu->addAction(text);
1097 }
1098
1099 action->setCheckable(true);
1100 action->setChecked(visibleRolesSet.contains(info.role));
1101 action->setData(info.role);
1102
1103 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
1104 (info.requiresBaloo) ||
1105 (info.requiresIndexer && indexingEnabled);
1106 action->setEnabled(enable);
1107 }
1108
1109 menu->addSeparator();
1110
1111 QActionGroup* widthsGroup = new QActionGroup(menu);
1112 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
1113
1114 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1115 autoAdjustWidthsAction->setCheckable(true);
1116 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1117 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1118
1119 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1120 customWidthsAction->setCheckable(true);
1121 customWidthsAction->setChecked(!autoColumnWidths);
1122 customWidthsAction->setActionGroup(widthsGroup);
1123
1124 QAction* action = menu->exec(pos.toPoint());
1125 if (menu && action) {
1126 KItemListHeader* header = view->header();
1127
1128 if (action == autoAdjustWidthsAction) {
1129 // Clear the column-widths from the viewproperties and turn on
1130 // the automatic resizing of the columns
1131 props.setHeaderColumnWidths(QList<int>());
1132 header->setAutomaticColumnResizing(true);
1133 } else if (action == customWidthsAction) {
1134 // Apply the current column-widths as custom column-widths and turn
1135 // off the automatic resizing of the columns
1136 QList<int> columnWidths;
1137 const auto visibleRoles = view->visibleRoles();
1138 columnWidths.reserve(visibleRoles.count());
1139 for (const QByteArray& role : visibleRoles) {
1140 columnWidths.append(header->columnWidth(role));
1141 }
1142 props.setHeaderColumnWidths(columnWidths);
1143 header->setAutomaticColumnResizing(false);
1144 } else {
1145 // Show or hide the selected role
1146 const QByteArray selectedRole = action->data().toByteArray();
1147
1148 QList<QByteArray> visibleRoles = view->visibleRoles();
1149 if (action->isChecked()) {
1150 visibleRoles.append(selectedRole);
1151 } else {
1152 visibleRoles.removeOne(selectedRole);
1153 }
1154
1155 view->setVisibleRoles(visibleRoles);
1156 props.setVisibleRoles(visibleRoles);
1157
1158 QList<int> columnWidths;
1159 if (!header->automaticColumnResizing()) {
1160 const auto visibleRoles = view->visibleRoles();
1161 columnWidths.reserve(visibleRoles.count());
1162 for (const QByteArray& role : visibleRoles) {
1163 columnWidths.append(header->columnWidth(role));
1164 }
1165 }
1166 props.setHeaderColumnWidths(columnWidths);
1167 }
1168 }
1169
1170 delete menu;
1171 }
1172
1173 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1174 {
1175 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1176
1177 ViewProperties props(viewPropertiesUrl());
1178 QList<int> columnWidths = props.headerColumnWidths();
1179 if (columnWidths.count() != visibleRoles.count()) {
1180 columnWidths.clear();
1181 columnWidths.reserve(visibleRoles.count());
1182 const KItemListHeader* header = m_view->header();
1183 for (const QByteArray& role : visibleRoles) {
1184 const int width = header->columnWidth(role);
1185 columnWidths.append(width);
1186 }
1187 }
1188
1189 const int roleIndex = visibleRoles.indexOf(role);
1190 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1191 columnWidths[roleIndex] = current;
1192
1193 props.setHeaderColumnWidths(columnWidths);
1194 }
1195
1196 void DolphinView::slotItemHovered(int index)
1197 {
1198 const KFileItem item = m_model->fileItem(index);
1199
1200 if (GeneralSettings::showToolTips() && !m_dragging) {
1201 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1202 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1203 itemRect.moveTo(pos);
1204
1205 #ifdef HAVE_BALOO
1206 m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle());
1207 #endif
1208 }
1209
1210 Q_EMIT requestItemInfo(item);
1211 }
1212
1213 void DolphinView::slotItemUnhovered(int index)
1214 {
1215 Q_UNUSED(index)
1216 hideToolTip();
1217 Q_EMIT requestItemInfo(KFileItem());
1218 }
1219
1220 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1221 {
1222 QUrl destUrl;
1223 KFileItem destItem = m_model->fileItem(index);
1224 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1225 // Use the URL of the view as drop target if the item is no directory
1226 // or desktop-file
1227 destItem = m_model->rootItem();
1228 destUrl = url();
1229 } else {
1230 // The item represents a directory or desktop-file
1231 destUrl = destItem.mostLocalUrl();
1232 }
1233
1234 QDropEvent dropEvent(event->pos().toPoint(),
1235 event->possibleActions(),
1236 event->mimeData(),
1237 event->buttons(),
1238 event->modifiers());
1239 dropUrls(destUrl, &dropEvent, this);
1240
1241 setActive(true);
1242 }
1243
1244 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1245 {
1246 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1247
1248 if (job) {
1249 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1250
1251 if (destUrl == url()) {
1252 // Mark the dropped urls as selected.
1253 m_clearSelectionBeforeSelectingNewItems = true;
1254 m_markFirstNewlySelectedItemAsCurrent = true;
1255 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1256 }
1257 }
1258 }
1259
1260 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1261 {
1262 if (previous != nullptr) {
1263 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1264 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1265 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1266 m_versionControlObserver->setModel(nullptr);
1267 }
1268
1269 if (current) {
1270 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1271 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1272 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1273 m_versionControlObserver->setModel(fileItemModel);
1274 }
1275 }
1276
1277 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1278 {
1279 Q_UNUSED(itemIndex)
1280
1281 hideToolTip();
1282
1283 if (buttons & Qt::BackButton) {
1284 Q_EMIT goBackRequested();
1285 } else if (buttons & Qt::ForwardButton) {
1286 Q_EMIT goForwardRequested();
1287 }
1288 }
1289
1290 void DolphinView::slotSelectedItemTextPressed(int index)
1291 {
1292 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1293 const KFileItem item = m_model->fileItem(index);
1294 const KFileItemListProperties capabilities(KFileItemList() << item);
1295 if (capabilities.supportsMoving()) {
1296 m_twoClicksRenamingItemUrl = item.url();
1297 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1298 }
1299 }
1300 }
1301
1302 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1303 {
1304 slotItemCreated(to);
1305 }
1306
1307 void DolphinView::slotItemCreated(const QUrl& url)
1308 {
1309 if (m_markFirstNewlySelectedItemAsCurrent) {
1310 markUrlAsCurrent(url);
1311 m_markFirstNewlySelectedItemAsCurrent = false;
1312 }
1313 m_selectedUrls << url;
1314 }
1315
1316 void DolphinView::slotJobResult(KJob *job)
1317 {
1318 if (job->error()) {
1319 Q_EMIT errorMessage(job->errorString());
1320 }
1321 if (!m_selectedUrls.isEmpty()) {
1322 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1323 }
1324 }
1325
1326 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1327 {
1328 const int currentCount = current.count();
1329 const int previousCount = previous.count();
1330 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1331 (currentCount > 0 && previousCount == 0);
1332
1333 // If nothing has been selected before and something got selected (or if something
1334 // was selected before and now nothing is selected) the selectionChangedSignal must
1335 // be emitted asynchronously as fast as possible to update the edit-actions.
1336 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1337 m_selectionChangedTimer->start();
1338 }
1339
1340 void DolphinView::emitSelectionChangedSignal()
1341 {
1342 m_selectionChangedTimer->stop();
1343 Q_EMIT selectionChanged(selectedItems());
1344 }
1345
1346 void DolphinView::slotStatJobResult(KJob *job)
1347 {
1348 int folderCount = 0;
1349 int fileCount = 0;
1350 KIO::filesize_t totalFileSize = 0;
1351 bool countFileSize = true;
1352
1353 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1354 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1355 // We have a precomputed value.
1356 totalFileSize = static_cast<KIO::filesize_t>(
1357 entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1358 countFileSize = false;
1359 }
1360
1361 const int itemCount = m_model->count();
1362 for (int i = 0; i < itemCount; ++i) {
1363 const KFileItem item = m_model->fileItem(i);
1364 if (item.isDir()) {
1365 ++folderCount;
1366 } else {
1367 ++fileCount;
1368 if (countFileSize) {
1369 totalFileSize += item.size();
1370 }
1371 }
1372 }
1373 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1374 }
1375
1376 void DolphinView::updateSortRole(const QByteArray& role)
1377 {
1378 ViewProperties props(viewPropertiesUrl());
1379 props.setSortRole(role);
1380
1381 KItemModelBase* model = m_container->controller()->model();
1382 model->setSortRole(role);
1383
1384 Q_EMIT sortRoleChanged(role);
1385 }
1386
1387 void DolphinView::updateSortOrder(Qt::SortOrder order)
1388 {
1389 ViewProperties props(viewPropertiesUrl());
1390 props.setSortOrder(order);
1391
1392 m_model->setSortOrder(order);
1393
1394 Q_EMIT sortOrderChanged(order);
1395 }
1396
1397 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1398 {
1399 ViewProperties props(viewPropertiesUrl());
1400 props.setSortFoldersFirst(foldersFirst);
1401
1402 m_model->setSortDirectoriesFirst(foldersFirst);
1403
1404 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1405 }
1406
1407 void DolphinView::updateSortHiddenLast(bool hiddenLast)
1408 {
1409 ViewProperties props(viewPropertiesUrl());
1410 props.setSortHiddenLast(hiddenLast);
1411
1412 m_model->setSortHiddenLast(hiddenLast);
1413
1414 Q_EMIT sortHiddenLastChanged(hiddenLast);
1415 }
1416
1417
1418 QPair<bool, QString> DolphinView::pasteInfo() const
1419 {
1420 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1421 QPair<bool, QString> info;
1422 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1423 return info;
1424 }
1425
1426 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1427 {
1428 m_tabsForFiles = tabsForFiles;
1429 }
1430
1431 bool DolphinView::isTabsForFilesEnabled() const
1432 {
1433 return m_tabsForFiles;
1434 }
1435
1436 bool DolphinView::itemsExpandable() const
1437 {
1438 return m_mode == DetailsView;
1439 }
1440
1441 void DolphinView::restoreState(QDataStream& stream)
1442 {
1443 // Read the version number of the view state and check if the version is supported.
1444 quint32 version = 0;
1445 stream >> version;
1446 if (version != 1) {
1447 // The version of the view state isn't supported, we can't restore it.
1448 return;
1449 }
1450
1451 // Restore the current item that had the keyboard focus
1452 stream >> m_currentItemUrl;
1453
1454 // Restore the previously selected items
1455 stream >> m_selectedUrls;
1456
1457 // Restore the view position
1458 stream >> m_restoredContentsPosition;
1459
1460 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1461 QSet<QUrl> urls;
1462 stream >> urls;
1463 m_model->restoreExpandedDirectories(urls);
1464 }
1465
1466 void DolphinView::saveState(QDataStream& stream)
1467 {
1468 stream << quint32(1); // View state version
1469
1470 // Save the current item that has the keyboard focus
1471 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1472 if (currentIndex != -1) {
1473 KFileItem item = m_model->fileItem(currentIndex);
1474 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1475 QUrl currentItemUrl = item.url();
1476 stream << currentItemUrl;
1477 } else {
1478 stream << QUrl();
1479 }
1480
1481 // Save the selected urls
1482 stream << selectedItems().urlList();
1483
1484 // Save view position
1485 const qreal x = m_container->horizontalScrollBar()->value();
1486 const qreal y = m_container->verticalScrollBar()->value();
1487 stream << QPoint(x, y);
1488
1489 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1490 stream << m_model->expandedDirectories();
1491 }
1492
1493 KFileItem DolphinView::rootItem() const
1494 {
1495 return m_model->rootItem();
1496 }
1497
1498 void DolphinView::setViewPropertiesContext(const QString& context)
1499 {
1500 m_viewPropertiesContext = context;
1501 }
1502
1503 QString DolphinView::viewPropertiesContext() const
1504 {
1505 return m_viewPropertiesContext;
1506 }
1507
1508 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1509 {
1510 if (item.isNull()) {
1511 return QUrl();
1512 }
1513
1514 QUrl url = item.targetUrl();
1515
1516 if (item.isDir()) {
1517 return url;
1518 }
1519
1520 if (item.isMimeTypeKnown()) {
1521 const QString& mimetype = item.mimetype();
1522
1523 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1524 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1525 // zip:/<path>/ when clicking on a zip file, etc.
1526 // The .protocol file specifies the mimetype that the kioslave handles.
1527 // Note that we don't use mimetype inheritance since we don't want to
1528 // open OpenDocument files as zip folders...
1529 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1530 if (!protocol.isEmpty()) {
1531 url.setScheme(protocol);
1532 return url;
1533 }
1534 }
1535
1536 if (mimetype == QLatin1String("application/x-desktop")) {
1537 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1538 KDesktopFile desktopFile(url.toLocalFile());
1539 if (desktopFile.hasLinkType()) {
1540 const QString linkUrl = desktopFile.readUrl();
1541 if (!linkUrl.startsWith(QLatin1String("http"))) {
1542 return QUrl::fromUserInput(linkUrl);
1543 }
1544 }
1545 }
1546 }
1547
1548 return QUrl();
1549 }
1550
1551 void DolphinView::resetZoomLevel()
1552 {
1553 ViewModeSettings settings{m_mode};
1554 settings.useDefaults(true);
1555 const int defaultIconSize = settings.iconSize();
1556 settings.useDefaults(false);
1557
1558 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(QSize(defaultIconSize, defaultIconSize)));
1559 }
1560
1561 void DolphinView::observeCreatedItem(const QUrl& url)
1562 {
1563 if (m_active) {
1564 forceUrlsSelection(url, {url});
1565 }
1566 }
1567
1568 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1569 {
1570 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1571 Q_EMIT redirection(oldUrl, newUrl);
1572 m_url = newUrl; // #186947
1573 }
1574 }
1575
1576 void DolphinView::updateViewState()
1577 {
1578 if (m_currentItemUrl != QUrl()) {
1579 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1580
1581 // if there is a selection already, leave it that way
1582 if (!selectionManager->hasSelection()) {
1583 const int currentIndex = m_model->index(m_currentItemUrl);
1584 if (currentIndex != -1) {
1585 selectionManager->setCurrentItem(currentIndex);
1586
1587 // scroll to current item and reset the state
1588 if (m_scrollToCurrentItem) {
1589 m_view->scrollToItem(currentIndex);
1590 m_scrollToCurrentItem = false;
1591 }
1592 } else {
1593 selectionManager->setCurrentItem(0);
1594 }
1595 }
1596
1597 m_currentItemUrl = QUrl();
1598 }
1599
1600 if (!m_restoredContentsPosition.isNull()) {
1601 const int x = m_restoredContentsPosition.x();
1602 const int y = m_restoredContentsPosition.y();
1603 m_restoredContentsPosition = QPoint();
1604
1605 m_container->horizontalScrollBar()->setValue(x);
1606 m_container->verticalScrollBar()->setValue(y);
1607 }
1608
1609 if (!m_selectedUrls.isEmpty()) {
1610 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1611
1612 // if there is a selection already, leave it that way
1613 if (!selectionManager->hasSelection()) {
1614 if (m_clearSelectionBeforeSelectingNewItems) {
1615 selectionManager->clearSelection();
1616 m_clearSelectionBeforeSelectingNewItems = false;
1617 }
1618
1619 KItemSet selectedItems = selectionManager->selectedItems();
1620
1621 QList<QUrl>::iterator it = m_selectedUrls.begin();
1622 while (it != m_selectedUrls.end()) {
1623 const int index = m_model->index(*it);
1624 if (index >= 0) {
1625 selectedItems.insert(index);
1626 it = m_selectedUrls.erase(it);
1627 } else {
1628 ++it;
1629 }
1630 }
1631
1632 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1633 selectionManager->setSelectedItems(selectedItems);
1634 }
1635 }
1636 }
1637
1638 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1639 {
1640 #ifdef HAVE_BALOO
1641 if (GeneralSettings::showToolTips()) {
1642 m_toolTipManager->hideToolTip(behavior);
1643 }
1644 #else
1645 Q_UNUSED(behavior)
1646 #endif
1647 }
1648
1649 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1650 {
1651 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1652
1653 // verify that only one item is selected
1654 if (selectionManager->selectedItems().count() == 1) {
1655 const int index = selectionManager->currentItem();
1656 const QUrl fileItemUrl = m_model->fileItem(index).url();
1657
1658 // check if the selected item was the same item that started the twoClicksRenaming
1659 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1660 renameSelectedItems();
1661 }
1662 }
1663 }
1664
1665 void DolphinView::slotTrashFileFinished(KJob* job)
1666 {
1667 if (job->error() == 0) {
1668 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1669 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1670 Q_EMIT errorMessage(job->errorString());
1671 }
1672 }
1673
1674 void DolphinView::slotDeleteFileFinished(KJob* job)
1675 {
1676 if (job->error() == 0) {
1677 Q_EMIT operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1678 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1679 Q_EMIT errorMessage(job->errorString());
1680 }
1681 }
1682
1683 void DolphinView::slotRenamingResult(KJob* job)
1684 {
1685 if (job->error()) {
1686 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1687 Q_ASSERT(copyJob);
1688 const QUrl newUrl = copyJob->destUrl();
1689 const int index = m_model->index(newUrl);
1690 if (index >= 0) {
1691 QHash<QByteArray, QVariant> data;
1692 const QUrl oldUrl = copyJob->srcUrls().at(0);
1693 data.insert("text", oldUrl.fileName());
1694 m_model->setData(index, data);
1695 }
1696 }
1697 }
1698
1699 void DolphinView::slotDirectoryLoadingStarted()
1700 {
1701 m_loading = true;
1702 updatePlaceholderLabel();
1703
1704 // Disable the writestate temporary until it can be determined in a fast way
1705 // in DolphinView::slotDirectoryLoadingCompleted()
1706 if (m_isFolderWritable) {
1707 m_isFolderWritable = false;
1708 Q_EMIT writeStateChanged(m_isFolderWritable);
1709 }
1710
1711 Q_EMIT directoryLoadingStarted();
1712 }
1713
1714 void DolphinView::slotDirectoryLoadingCompleted()
1715 {
1716 m_loading = false;
1717
1718 // Update the view-state. This has to be done asynchronously
1719 // because the view might not be in its final state yet.
1720 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1721
1722 // Update the placeholder label in case we found that the folder was empty
1723 // after loading it
1724
1725 Q_EMIT directoryLoadingCompleted();
1726
1727 updatePlaceholderLabel();
1728 updateWritableState();
1729 }
1730
1731 void DolphinView::slotDirectoryLoadingCanceled()
1732 {
1733 m_loading = false;
1734
1735 updatePlaceholderLabel();
1736
1737 Q_EMIT directoryLoadingCanceled();
1738 }
1739
1740 void DolphinView::slotItemsChanged()
1741 {
1742 m_assureVisibleCurrentIndex = false;
1743 }
1744
1745 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1746 {
1747 Q_UNUSED(previous)
1748 Q_ASSERT(m_model->sortOrder() == current);
1749
1750 ViewProperties props(viewPropertiesUrl());
1751 props.setSortOrder(current);
1752
1753 Q_EMIT sortOrderChanged(current);
1754 }
1755
1756 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1757 {
1758 Q_UNUSED(previous)
1759 Q_ASSERT(m_model->sortRole() == current);
1760
1761 ViewProperties props(viewPropertiesUrl());
1762 props.setSortRole(current);
1763
1764 Q_EMIT sortRoleChanged(current);
1765 }
1766
1767 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1768 const QList<QByteArray>& previous)
1769 {
1770 Q_UNUSED(previous)
1771 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1772
1773 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1774
1775 m_visibleRoles = current;
1776
1777 ViewProperties props(viewPropertiesUrl());
1778 props.setVisibleRoles(m_visibleRoles);
1779
1780 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1781 }
1782
1783 void DolphinView::slotRoleEditingCanceled()
1784 {
1785 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1786 this, &DolphinView::slotRoleEditingFinished);
1787 }
1788
1789 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1790 {
1791 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1792 this, &DolphinView::slotRoleEditingFinished);
1793
1794 const KFileItemList items = selectedItems();
1795 if (items.count() != 1) {
1796 return;
1797 }
1798
1799 if (role == "text") {
1800 const KFileItem oldItem = items.first();
1801 const EditResult retVal = value.value<EditResult>();
1802 const QString newName = retVal.newName;
1803 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1804 const QUrl oldUrl = oldItem.url();
1805
1806 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1807 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1808
1809 #ifndef Q_OS_WIN
1810 //Confirm hiding file/directory by renaming inline
1811 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1812 KGuiItem yesGuiItem(KStandardGuiItem::yes());
1813 yesGuiItem.setText(i18nc("@action:button", "Rename and Hide"));
1814
1815 const auto code = KMessageBox::questionYesNo(this,
1816 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1817 "Do you still want to rename it?")
1818 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1819 "Do you still want to rename it?"),
1820 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1821 yesGuiItem,
1822 KStandardGuiItem::cancel(),
1823 QStringLiteral("ConfirmHide")
1824 );
1825
1826 if (code == KMessageBox::No) {
1827 return;
1828 }
1829 }
1830 #endif
1831
1832 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1833 if (!newNameExistsAlready && m_model->index(oldUrl) == index) {
1834 // Only change the data in the model if no item with the new name
1835 // is in the model yet. If there is an item with the new name
1836 // already, calling KIO::CopyJob will open a dialog
1837 // asking for a new name, and KFileItemModel will update the
1838 // data when the dir lister signals that the file name has changed.
1839 QHash<QByteArray, QVariant> data;
1840 data.insert(role, retVal.newName);
1841 m_model->setData(index, data);
1842 }
1843
1844 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1845 KJobWidgets::setWindow(job, this);
1846 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1847 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1848
1849 forceUrlsSelection(newUrl, {newUrl});
1850
1851 if (!newNameExistsAlready) {
1852 // Only connect the result signal if there is no item with the new name
1853 // in the model yet, see bug 328262.
1854 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1855 }
1856 }
1857 if (retVal.direction != EditDone) {
1858 const short indexShift = retVal.direction == EditNext ? 1 : -1;
1859 m_container->controller()->selectionManager()->setSelected(index, 1, KItemListSelectionManager::Deselect);
1860 m_container->controller()->selectionManager()->setSelected(index + indexShift, 1,
1861 KItemListSelectionManager::Select);
1862 renameSelectedItems();
1863 }
1864 }
1865 }
1866
1867 void DolphinView::loadDirectory(const QUrl& url, bool reload)
1868 {
1869 if (!url.isValid()) {
1870 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1871 if (location.isEmpty()) {
1872 Q_EMIT errorMessage(i18nc("@info:status", "The location is empty."));
1873 } else {
1874 Q_EMIT errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1875 }
1876 return;
1877 }
1878
1879 if (reload) {
1880 m_model->refreshDirectory(url);
1881 } else {
1882 m_model->loadDirectory(url);
1883 }
1884 }
1885
1886 void DolphinView::applyViewProperties()
1887 {
1888 const ViewProperties props(viewPropertiesUrl());
1889 applyViewProperties(props);
1890 }
1891
1892 void DolphinView::applyViewProperties(const ViewProperties& props)
1893 {
1894 m_view->beginTransaction();
1895
1896 const Mode mode = props.viewMode();
1897 if (m_mode != mode) {
1898 const Mode previousMode = m_mode;
1899 m_mode = mode;
1900
1901 // Changing the mode might result in changing
1902 // the zoom level. Remember the old zoom level so
1903 // that zoomLevelChanged() can get emitted.
1904 const int oldZoomLevel = m_view->zoomLevel();
1905 applyModeToView();
1906
1907 Q_EMIT modeChanged(m_mode, previousMode);
1908
1909 if (m_view->zoomLevel() != oldZoomLevel) {
1910 Q_EMIT zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1911 }
1912 }
1913
1914 const bool hiddenFilesShown = props.hiddenFilesShown();
1915 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1916 m_model->setShowHiddenFiles(hiddenFilesShown);
1917 Q_EMIT hiddenFilesShownChanged(hiddenFilesShown);
1918 }
1919
1920 const bool groupedSorting = props.groupedSorting();
1921 if (groupedSorting != m_model->groupedSorting()) {
1922 m_model->setGroupedSorting(groupedSorting);
1923 Q_EMIT groupedSortingChanged(groupedSorting);
1924 }
1925
1926 const QByteArray sortRole = props.sortRole();
1927 if (sortRole != m_model->sortRole()) {
1928 m_model->setSortRole(sortRole);
1929 Q_EMIT sortRoleChanged(sortRole);
1930 }
1931
1932 const Qt::SortOrder sortOrder = props.sortOrder();
1933 if (sortOrder != m_model->sortOrder()) {
1934 m_model->setSortOrder(sortOrder);
1935 Q_EMIT sortOrderChanged(sortOrder);
1936 }
1937
1938 const bool sortFoldersFirst = props.sortFoldersFirst();
1939 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1940 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1941 Q_EMIT sortFoldersFirstChanged(sortFoldersFirst);
1942 }
1943
1944 const bool sortHiddenLast = props.sortHiddenLast();
1945 if (sortHiddenLast != m_model->sortHiddenLast()) {
1946 m_model->setSortHiddenLast(sortHiddenLast);
1947 Q_EMIT sortHiddenLastChanged(sortHiddenLast);
1948 }
1949
1950 const QList<QByteArray> visibleRoles = props.visibleRoles();
1951 if (visibleRoles != m_visibleRoles) {
1952 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1953 m_visibleRoles = visibleRoles;
1954 m_view->setVisibleRoles(visibleRoles);
1955 Q_EMIT visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1956 }
1957
1958 const bool previewsShown = props.previewsShown();
1959 if (previewsShown != m_view->previewsShown()) {
1960 const int oldZoomLevel = zoomLevel();
1961
1962 m_view->setPreviewsShown(previewsShown);
1963 Q_EMIT previewsShownChanged(previewsShown);
1964
1965 // Changing the preview-state might result in a changed zoom-level
1966 if (oldZoomLevel != zoomLevel()) {
1967 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
1968 }
1969 }
1970
1971 KItemListView* itemListView = m_container->controller()->view();
1972 if (itemListView->isHeaderVisible()) {
1973 KItemListHeader* header = itemListView->header();
1974 const QList<int> headerColumnWidths = props.headerColumnWidths();
1975 const int rolesCount = m_visibleRoles.count();
1976 if (headerColumnWidths.count() == rolesCount) {
1977 header->setAutomaticColumnResizing(false);
1978
1979 QHash<QByteArray, qreal> columnWidths;
1980 for (int i = 0; i < rolesCount; ++i) {
1981 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1982 }
1983 header->setColumnWidths(columnWidths);
1984 } else {
1985 header->setAutomaticColumnResizing(true);
1986 }
1987 }
1988
1989 m_view->endTransaction();
1990 }
1991
1992 void DolphinView::applyModeToView()
1993 {
1994 switch (m_mode) {
1995 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1996 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1997 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1998 default: Q_ASSERT(false); break;
1999 }
2000 }
2001
2002 void DolphinView::pasteToUrl(const QUrl& url)
2003 {
2004 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
2005 KJobWidgets::setWindow(job, this);
2006 m_clearSelectionBeforeSelectingNewItems = true;
2007 m_markFirstNewlySelectedItemAsCurrent = true;
2008 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
2009 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotJobResult);
2010 }
2011
2012 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
2013 {
2014 QList<QUrl> urls;
2015
2016 const KFileItemList items = selectedItems();
2017 urls.reserve(items.count());
2018 for (const KFileItem& item : items) {
2019 urls.append(item.url());
2020 }
2021
2022 if (itemsExpandable()) {
2023 // TODO: Check if we still need KDirModel for this in KDE 5.0
2024 urls = KDirModel::simplifiedUrlList(urls);
2025 }
2026
2027 return urls;
2028 }
2029
2030 QMimeData* DolphinView::selectionMimeData() const
2031 {
2032 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
2033 const KItemSet selectedIndexes = selectionManager->selectedItems();
2034
2035 return m_model->createMimeData(selectedIndexes);
2036 }
2037
2038 void DolphinView::updateWritableState()
2039 {
2040 const bool wasFolderWritable = m_isFolderWritable;
2041 m_isFolderWritable = false;
2042
2043 KFileItem item = m_model->rootItem();
2044 if (item.isNull()) {
2045 // Try to find out if the URL is writable even if the "root item" is
2046 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
2047 item = KFileItem(url());
2048 item.setDelayedMimeTypes(true);
2049 }
2050
2051 KFileItemListProperties capabilities(KFileItemList() << item);
2052 m_isFolderWritable = capabilities.supportsWriting();
2053
2054 if (m_isFolderWritable != wasFolderWritable) {
2055 Q_EMIT writeStateChanged(m_isFolderWritable);
2056 }
2057 }
2058
2059 QUrl DolphinView::viewPropertiesUrl() const
2060 {
2061 if (m_viewPropertiesContext.isEmpty()) {
2062 return m_url;
2063 }
2064
2065 QUrl url;
2066 url.setScheme(m_url.scheme());
2067 url.setPath(m_viewPropertiesContext);
2068 return url;
2069 }
2070
2071 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
2072 {
2073 forceUrlsSelection(urls.first(), urls);
2074 }
2075
2076 void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
2077 {
2078 clearSelection();
2079 m_clearSelectionBeforeSelectingNewItems = true;
2080 markUrlAsCurrent(current);
2081 markUrlsAsSelected(selected);
2082 }
2083
2084 void DolphinView::copyPathToClipboard()
2085 {
2086 const KFileItemList list = selectedItems();
2087 if (list.isEmpty()) {
2088 return;
2089 }
2090 const KFileItem& item = list.at(0);
2091 QString path = item.localPath();
2092 if (path.isEmpty()) {
2093 path = item.url().toDisplayString();
2094 }
2095 QClipboard* clipboard = QApplication::clipboard();
2096 if (clipboard == nullptr) {
2097 return;
2098 }
2099 clipboard->setText(path);
2100 }
2101
2102 void DolphinView::slotIncreaseZoom()
2103 {
2104 setZoomLevel(zoomLevel() + 1);
2105 }
2106
2107 void DolphinView::slotDecreaseZoom()
2108 {
2109 setZoomLevel(zoomLevel() - 1);
2110 }
2111
2112 void DolphinView::slotSwipeUp()
2113 {
2114 Q_EMIT goUpRequested();
2115 }
2116
2117 void DolphinView::showLoadingPlaceholder()
2118 {
2119 m_placeholderLabel->setText(i18n("Loading..."));
2120 m_placeholderLabel->setVisible(true);
2121 }
2122
2123 void DolphinView::updatePlaceholderLabel()
2124 {
2125 m_showLoadingPlaceholderTimer->stop();
2126 if (itemsCount() > 0) {
2127 m_placeholderLabel->setVisible(false);
2128 return;
2129 }
2130
2131 if (m_loading) {
2132 m_placeholderLabel->setVisible(false);
2133 m_showLoadingPlaceholderTimer->start();
2134 return;
2135 }
2136
2137 if (!nameFilter().isEmpty()) {
2138 m_placeholderLabel->setText(i18n("No items matching the filter"));
2139 } else if (m_url.scheme() == QLatin1String("baloosearch") || m_url.scheme() == QLatin1String("filenamesearch")) {
2140 m_placeholderLabel->setText(i18n("No items matching the search"));
2141 } else if (m_url.scheme() == QLatin1String("trash") && m_url.path() == QLatin1String("/")) {
2142 m_placeholderLabel->setText(i18n("Trash is empty"));
2143 } else if (m_url.scheme() == QLatin1String("tags")) {
2144 m_placeholderLabel->setText(i18n("No tags"));
2145 } else if (m_url.scheme() == QLatin1String("recentlyused")) {
2146 m_placeholderLabel->setText(i18n("No recently used items"));
2147 } else if (m_url.scheme() == QLatin1String("smb")) {
2148 m_placeholderLabel->setText(i18n("No shared folders found"));
2149 } else if (m_url.scheme() == QLatin1String("network")) {
2150 m_placeholderLabel->setText(i18n("No relevant network resources found"));
2151 } else if (m_url.scheme() == QLatin1String("mtp") && m_url.path() == QLatin1String("/")) {
2152 m_placeholderLabel->setText(i18n("No MTP-compatible devices found"));
2153 } else if (m_url.scheme() == QLatin1String("bluetooth")) {
2154 m_placeholderLabel->setText(i18n("No Bluetooth devices found"));
2155 } else {
2156 m_placeholderLabel->setText(i18n("Folder is empty"));
2157 }
2158
2159 m_placeholderLabel->setVisible(true);
2160 }