]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Remove duplicate include from .h/.cpp
[dolphin.git] / src / views / dolphinview.cpp
1 /*
2 * SPDX-FileCopyrightText: 2006-2009 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2006 Gregor Kališnik <gregor@podnapisi.net>
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include "dolphinview.h"
9
10 #include "dolphin_compactmodesettings.h"
11 #include "dolphin_detailsmodesettings.h"
12 #include "dolphin_iconsmodesettings.h"
13 #include "dolphin_generalsettings.h"
14 #include "dolphinitemlistview.h"
15 #include "dolphinnewfilemenuobserver.h"
16 #include "draganddrophelper.h"
17 #include "kitemviews/kfileitemlistview.h"
18 #include "kitemviews/kfileitemmodel.h"
19 #include "kitemviews/kitemlistcontainer.h"
20 #include "kitemviews/kitemlistcontroller.h"
21 #include "kitemviews/kitemlistheader.h"
22 #include "kitemviews/kitemlistselectionmanager.h"
23 #include "kitemviews/private/kitemlistroleeditor.h"
24 #include "versioncontrol/versioncontrolobserver.h"
25 #include "viewproperties.h"
26 #include "views/tooltips/tooltipmanager.h"
27 #include "zoomlevelinfo.h"
28
29 #ifdef HAVE_BALOO
30 #include <Baloo/IndexerConfig>
31 #endif
32 #include <KColorScheme>
33 #include <KDesktopFile>
34 #include <KDirModel>
35 #include <KFileItemListProperties>
36 #include <KFormat>
37 #include <KIO/CopyJob>
38 #include <KIO/DeleteJob>
39 #include <KIO/DropJob>
40 #include <KIO/JobUiDelegate>
41 #include <KIO/Paste>
42 #include <KIO/PasteJob>
43 #include <KIO/PreviewJob>
44 #include <KIO/RenameFileDialog>
45 #include <KJobWidgets>
46 #include <KLocalizedString>
47 #include <KMessageBox>
48 #include <KProtocolManager>
49
50 #include <QAbstractItemView>
51 #include <QActionGroup>
52 #include <QApplication>
53 #include <QClipboard>
54 #include <QDropEvent>
55 #include <QGraphicsOpacityEffect>
56 #include <QGraphicsSceneDragDropEvent>
57 #include <QLabel>
58 #include <QMenu>
59 #include <QMimeDatabase>
60 #include <QPixmapCache>
61 #include <QScrollBar>
62 #include <QSize>
63 #include <QTimer>
64 #include <QVBoxLayout>
65
66 DolphinView::DolphinView(const QUrl& url, QWidget* parent) :
67 QWidget(parent),
68 m_active(true),
69 m_tabsForFiles(false),
70 m_assureVisibleCurrentIndex(false),
71 m_isFolderWritable(true),
72 m_dragging(false),
73 m_loading(false),
74 m_url(url),
75 m_viewPropertiesContext(),
76 m_mode(DolphinView::IconsView),
77 m_visibleRoles(),
78 m_topLayout(nullptr),
79 m_model(nullptr),
80 m_view(nullptr),
81 m_container(nullptr),
82 m_toolTipManager(nullptr),
83 m_selectionChangedTimer(nullptr),
84 m_currentItemUrl(),
85 m_scrollToCurrentItem(false),
86 m_restoredContentsPosition(),
87 m_selectedUrls(),
88 m_clearSelectionBeforeSelectingNewItems(false),
89 m_markFirstNewlySelectedItemAsCurrent(false),
90 m_versionControlObserver(nullptr),
91 m_twoClicksRenamingTimer(nullptr),
92 m_placeholderLabel(nullptr),
93 m_showLoadingPlaceholderTimer(nullptr)
94 {
95 m_topLayout = new QVBoxLayout(this);
96 m_topLayout->setSpacing(0);
97 m_topLayout->setContentsMargins(0, 0, 0, 0);
98
99 // When a new item has been created by the "Create New..." menu, the item should
100 // get selected and it must be assured that the item will get visible. As the
101 // creation is done asynchronously, several signals must be checked:
102 connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated,
103 this, &DolphinView::observeCreatedItem);
104
105 m_selectionChangedTimer = new QTimer(this);
106 m_selectionChangedTimer->setSingleShot(true);
107 m_selectionChangedTimer->setInterval(300);
108 connect(m_selectionChangedTimer, &QTimer::timeout,
109 this, &DolphinView::emitSelectionChangedSignal);
110
111 m_model = new KFileItemModel(this);
112 m_view = new DolphinItemListView();
113 m_view->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
114 m_view->setVisibleRoles({"text"});
115 applyModeToView();
116
117 KItemListController* controller = new KItemListController(m_model, m_view, this);
118 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
119 controller->setAutoActivationDelay(delay);
120
121 // The EnlargeSmallPreviews setting can only be changed after the model
122 // has been set in the view by KItemListController.
123 m_view->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
124
125 m_container = new KItemListContainer(controller, this);
126 m_container->installEventFilter(this);
127 setFocusProxy(m_container);
128 connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, [=] { hideToolTip(); });
129 connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] { hideToolTip(); });
130
131 m_showLoadingPlaceholderTimer = new QTimer(this);
132 m_showLoadingPlaceholderTimer->setInterval(500);
133 m_showLoadingPlaceholderTimer->setSingleShot(true);
134 connect(m_showLoadingPlaceholderTimer, &QTimer::timeout, this, &DolphinView::showLoadingPlaceholder);
135
136 // Show some placeholder text for empty folders
137 // This is made using a heavily-modified QLabel rather than a KTitleWidget
138 // because KTitleWidget can't be told to turn off mouse-selectable text
139 m_placeholderLabel = new QLabel(this);
140 QFont placeholderLabelFont;
141 // To match the size of a level 2 Heading/KTitleWidget
142 placeholderLabelFont.setPointSize(qRound(placeholderLabelFont.pointSize() * 1.3));
143 m_placeholderLabel->setFont(placeholderLabelFont);
144 m_placeholderLabel->setTextInteractionFlags(Qt::NoTextInteraction);
145 m_placeholderLabel->setWordWrap(true);
146 m_placeholderLabel->setAlignment(Qt::AlignCenter);
147 // Match opacity of QML placeholder label component
148 auto *effect = new QGraphicsOpacityEffect(m_placeholderLabel);
149 effect->setOpacity(0.5);
150 m_placeholderLabel->setGraphicsEffect(effect);
151 // Set initial text and visibility
152 updatePlaceholderLabel();
153
154 auto *centeringLayout = new QVBoxLayout(m_container);
155 centeringLayout->addWidget(m_placeholderLabel);
156 centeringLayout->setAlignment(m_placeholderLabel, Qt::AlignCenter);
157
158 controller->setSelectionBehavior(KItemListController::MultiSelection);
159 connect(controller, &KItemListController::itemActivated, this, &DolphinView::slotItemActivated);
160 connect(controller, &KItemListController::itemsActivated, this, &DolphinView::slotItemsActivated);
161 connect(controller, &KItemListController::itemMiddleClicked, this, &DolphinView::slotItemMiddleClicked);
162 connect(controller, &KItemListController::itemContextMenuRequested, this, &DolphinView::slotItemContextMenuRequested);
163 connect(controller, &KItemListController::viewContextMenuRequested, this, &DolphinView::slotViewContextMenuRequested);
164 connect(controller, &KItemListController::headerContextMenuRequested, this, &DolphinView::slotHeaderContextMenuRequested);
165 connect(controller, &KItemListController::mouseButtonPressed, this, &DolphinView::slotMouseButtonPressed);
166 connect(controller, &KItemListController::itemHovered, this, &DolphinView::slotItemHovered);
167 connect(controller, &KItemListController::itemUnhovered, this, &DolphinView::slotItemUnhovered);
168 connect(controller, &KItemListController::itemDropEvent, this, &DolphinView::slotItemDropEvent);
169 connect(controller, &KItemListController::escapePressed, this, &DolphinView::stopLoading);
170 connect(controller, &KItemListController::modelChanged, this, &DolphinView::slotModelChanged);
171 connect(controller, &KItemListController::selectedItemTextPressed, this, &DolphinView::slotSelectedItemTextPressed);
172 connect(controller, &KItemListController::increaseZoom, this, &DolphinView::slotIncreaseZoom);
173 connect(controller, &KItemListController::decreaseZoom, this, &DolphinView::slotDecreaseZoom);
174 connect(controller, &KItemListController::swipeUp, this, &DolphinView::slotSwipeUp);
175
176 connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted);
177 connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
178 connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::slotDirectoryLoadingCanceled);
179 connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress);
180 connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress);
181 connect(m_model, &KFileItemModel::itemsChanged,
182 this, &DolphinView::slotItemsChanged);
183 connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged);
184 connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged);
185 connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage);
186 connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage);
187 connect(m_model, &KFileItemModel::directoryRedirection, this, &DolphinView::slotDirectoryRedirection);
188 connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError);
189 connect(m_model, &KFileItemModel::fileItemsChanged, this, &DolphinView::fileItemsChanged);
190
191 connect(this, &DolphinView::itemCountChanged,
192 this, &DolphinView::updatePlaceholderLabel);
193
194 m_view->installEventFilter(this);
195 connect(m_view, &DolphinItemListView::sortOrderChanged,
196 this, &DolphinView::slotSortOrderChangedByHeader);
197 connect(m_view, &DolphinItemListView::sortRoleChanged,
198 this, &DolphinView::slotSortRoleChangedByHeader);
199 connect(m_view, &DolphinItemListView::visibleRolesChanged,
200 this, &DolphinView::slotVisibleRolesChangedByHeader);
201 connect(m_view, &DolphinItemListView::roleEditingCanceled,
202 this, &DolphinView::slotRoleEditingCanceled);
203 connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished,
204 this, &DolphinView::slotHeaderColumnWidthChangeFinished);
205
206 KItemListSelectionManager* selectionManager = controller->selectionManager();
207 connect(selectionManager, &KItemListSelectionManager::selectionChanged,
208 this, &DolphinView::slotSelectionChanged);
209
210 #ifdef HAVE_BALOO
211 m_toolTipManager = new ToolTipManager(this);
212 connect(m_toolTipManager, &ToolTipManager::urlActivated, this, &DolphinView::urlActivated);
213 #endif
214
215 m_versionControlObserver = new VersionControlObserver(this);
216 m_versionControlObserver->setView(this);
217 m_versionControlObserver->setModel(m_model);
218 connect(m_versionControlObserver, &VersionControlObserver::infoMessage, this, &DolphinView::infoMessage);
219 connect(m_versionControlObserver, &VersionControlObserver::errorMessage, this, &DolphinView::errorMessage);
220 connect(m_versionControlObserver, &VersionControlObserver::operationCompletedMessage, this, &DolphinView::operationCompletedMessage);
221
222 m_twoClicksRenamingTimer = new QTimer(this);
223 m_twoClicksRenamingTimer->setSingleShot(true);
224 connect(m_twoClicksRenamingTimer, &QTimer::timeout, this, &DolphinView::slotTwoClicksRenamingTimerTimeout);
225
226 applyViewProperties();
227 m_topLayout->addWidget(m_container);
228
229 loadDirectory(url);
230 }
231
232 DolphinView::~DolphinView()
233 {
234 }
235
236 QUrl DolphinView::url() const
237 {
238 return m_url;
239 }
240
241 void DolphinView::setActive(bool active)
242 {
243 if (active == m_active) {
244 return;
245 }
246
247 m_active = active;
248
249 updatePalette();
250
251 if (active) {
252 m_container->setFocus();
253 Q_EMIT activated();
254 Q_EMIT writeStateChanged(m_isFolderWritable);
255 }
256 }
257
258 bool DolphinView::isActive() const
259 {
260 return m_active;
261 }
262
263 void DolphinView::setMode(Mode mode)
264 {
265 if (mode != m_mode) {
266 ViewProperties props(viewPropertiesUrl());
267 props.setViewMode(mode);
268
269 // We pass the new ViewProperties to applyViewProperties, rather than
270 // storing them on disk and letting applyViewProperties() read them
271 // from there, to prevent that changing the view mode fails if the
272 // .directory file is not writable (see bug 318534).
273 applyViewProperties(props);
274 }
275 }
276
277 DolphinView::Mode DolphinView::mode() const
278 {
279 return m_mode;
280 }
281
282 void DolphinView::setPreviewsShown(bool show)
283 {
284 if (previewsShown() == show) {
285 return;
286 }
287
288 ViewProperties props(viewPropertiesUrl());
289 props.setPreviewsShown(show);
290
291 const int oldZoomLevel = m_view->zoomLevel();
292 m_view->setPreviewsShown(show);
293 Q_EMIT previewsShownChanged(show);
294
295 const int newZoomLevel = m_view->zoomLevel();
296 if (newZoomLevel != oldZoomLevel) {
297 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
298 }
299 }
300
301 bool DolphinView::previewsShown() const
302 {
303 return m_view->previewsShown();
304 }
305
306 void DolphinView::setHiddenFilesShown(bool show)
307 {
308 if (m_model->showHiddenFiles() == show) {
309 return;
310 }
311
312 const KFileItemList itemList = selectedItems();
313 m_selectedUrls.clear();
314 m_selectedUrls = itemList.urlList();
315
316 ViewProperties props(viewPropertiesUrl());
317 props.setHiddenFilesShown(show);
318
319 m_model->setShowHiddenFiles(show);
320 Q_EMIT hiddenFilesShownChanged(show);
321 }
322
323 bool DolphinView::hiddenFilesShown() const
324 {
325 return m_model->showHiddenFiles();
326 }
327
328 void DolphinView::setGroupedSorting(bool grouped)
329 {
330 if (grouped == groupedSorting()) {
331 return;
332 }
333
334 ViewProperties props(viewPropertiesUrl());
335 props.setGroupedSorting(grouped);
336 props.save();
337
338 m_container->controller()->model()->setGroupedSorting(grouped);
339
340 Q_EMIT groupedSortingChanged(grouped);
341 }
342
343 bool DolphinView::groupedSorting() const
344 {
345 return m_model->groupedSorting();
346 }
347
348 KFileItemList DolphinView::items() const
349 {
350 KFileItemList list;
351 const int itemCount = m_model->count();
352 list.reserve(itemCount);
353
354 for (int i = 0; i < itemCount; ++i) {
355 list.append(m_model->fileItem(i));
356 }
357
358 return list;
359 }
360
361 int DolphinView::itemsCount() const
362 {
363 return m_model->count();
364 }
365
366 KFileItemList DolphinView::selectedItems() const
367 {
368 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
369
370 KFileItemList selectedItems;
371 const auto items = selectionManager->selectedItems();
372 selectedItems.reserve(items.count());
373 for (int index : items) {
374 selectedItems.append(m_model->fileItem(index));
375 }
376 return selectedItems;
377 }
378
379 int DolphinView::selectedItemsCount() const
380 {
381 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
382 return selectionManager->selectedItems().count();
383 }
384
385 void DolphinView::markUrlsAsSelected(const QList<QUrl>& urls)
386 {
387 m_selectedUrls = urls;
388 }
389
390 void DolphinView::markUrlAsCurrent(const QUrl &url)
391 {
392 m_currentItemUrl = url;
393 m_scrollToCurrentItem = true;
394 }
395
396 void DolphinView::selectItems(const QRegularExpression &regexp, bool enabled)
397 {
398 const KItemListSelectionManager::SelectionMode mode = enabled
399 ? KItemListSelectionManager::Select
400 : KItemListSelectionManager::Deselect;
401 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
402
403 for (int index = 0; index < m_model->count(); index++) {
404 const KFileItem item = m_model->fileItem(index);
405 if (regexp.match(item.text()).hasMatch()) {
406 // An alternative approach would be to store the matching items in a KItemSet and
407 // select them in one go after the loop, but we'd need a new function
408 // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode)
409 // for that.
410 selectionManager->setSelected(index, 1, mode);
411 }
412 }
413 }
414
415 void DolphinView::setZoomLevel(int level)
416 {
417 const int oldZoomLevel = zoomLevel();
418 m_view->setZoomLevel(level);
419 if (zoomLevel() != oldZoomLevel) {
420 hideToolTip();
421 Q_EMIT zoomLevelChanged(zoomLevel(), oldZoomLevel);
422 }
423 }
424
425 int DolphinView::zoomLevel() const
426 {
427 return m_view->zoomLevel();
428 }
429
430 void DolphinView::setSortRole(const QByteArray& role)
431 {
432 if (role != sortRole()) {
433 updateSortRole(role);
434 }
435 }
436
437 QByteArray DolphinView::sortRole() const
438 {
439 const KItemModelBase* model = m_container->controller()->model();
440 return model->sortRole();
441 }
442
443 void DolphinView::setSortOrder(Qt::SortOrder order)
444 {
445 if (sortOrder() != order) {
446 updateSortOrder(order);
447 }
448 }
449
450 Qt::SortOrder DolphinView::sortOrder() const
451 {
452 return m_model->sortOrder();
453 }
454
455 void DolphinView::setSortFoldersFirst(bool foldersFirst)
456 {
457 if (sortFoldersFirst() != foldersFirst) {
458 updateSortFoldersFirst(foldersFirst);
459 }
460 }
461
462 bool DolphinView::sortFoldersFirst() const
463 {
464 return m_model->sortDirectoriesFirst();
465 }
466
467 void DolphinView::setSortHiddenLast(bool hiddenLast)
468 {
469 if (sortHiddenLast() != hiddenLast) {
470 updateSortHiddenLast(hiddenLast);
471 }
472 }
473
474 bool DolphinView::sortHiddenLast() const
475 {
476 return m_model->sortHiddenLast();
477 }
478
479 void DolphinView::setVisibleRoles(const QList<QByteArray>& roles)
480 {
481 const QList<QByteArray> previousRoles = roles;
482
483 ViewProperties props(viewPropertiesUrl());
484 props.setVisibleRoles(roles);
485
486 m_visibleRoles = roles;
487 m_view->setVisibleRoles(roles);
488
489 Q_EMIT visibleRolesChanged(m_visibleRoles, previousRoles);
490 }
491
492 QList<QByteArray> DolphinView::visibleRoles() const
493 {
494 return m_visibleRoles;
495 }
496
497 void DolphinView::reload()
498 {
499 QByteArray viewState;
500 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
501 saveState(saveStream);
502
503 setUrl(url());
504 loadDirectory(url(), true);
505
506 QDataStream restoreStream(viewState);
507 restoreState(restoreStream);
508 }
509
510 void DolphinView::readSettings()
511 {
512 const int oldZoomLevel = m_view->zoomLevel();
513
514 GeneralSettings::self()->load();
515 m_view->readSettings();
516 applyViewProperties();
517
518 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
519 m_container->controller()->setAutoActivationDelay(delay);
520
521 const int newZoomLevel = m_view->zoomLevel();
522 if (newZoomLevel != oldZoomLevel) {
523 Q_EMIT zoomLevelChanged(newZoomLevel, oldZoomLevel);
524 }
525 }
526
527 void DolphinView::writeSettings()
528 {
529 GeneralSettings::self()->save();
530 m_view->writeSettings();
531 }
532
533 void DolphinView::setNameFilter(const QString& nameFilter)
534 {
535 m_model->setNameFilter(nameFilter);
536 }
537
538 QString DolphinView::nameFilter() const
539 {
540 return m_model->nameFilter();
541 }
542
543 void DolphinView::setMimeTypeFilters(const QStringList& filters)
544 {
545 return m_model->setMimeTypeFilters(filters);
546 }
547
548 QStringList DolphinView::mimeTypeFilters() const
549 {
550 return m_model->mimeTypeFilters();
551 }
552
553 void DolphinView::requestStatusBarText()
554 {
555 if (m_statJobForStatusBarText) {
556 // Kill the pending request.
557 m_statJobForStatusBarText->kill();
558 }
559
560 if (m_container->controller()->selectionManager()->hasSelection()) {
561 int folderCount = 0;
562 int fileCount = 0;
563 KIO::filesize_t totalFileSize = 0;
564
565 // Give a summary of the status of the selected files
566 const KFileItemList list = selectedItems();
567 for (const KFileItem& item : list) {
568 if (item.isDir()) {
569 ++folderCount;
570 } else {
571 ++fileCount;
572 totalFileSize += item.size();
573 }
574 }
575
576 if (folderCount + fileCount == 1) {
577 // If only one item is selected, show info about it
578 Q_EMIT statusBarTextChanged(list.first().getStatusBarInfo());
579 } else {
580 // At least 2 items are selected
581 emitStatusBarText(folderCount, fileCount, totalFileSize, HasSelection);
582 }
583 } else { // has no selection
584 if (!m_model->rootItem().url().isValid()) {
585 return;
586 }
587
588 m_statJobForStatusBarText = KIO::statDetails(m_model->rootItem().url(),
589 KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
590 connect(m_statJobForStatusBarText, &KJob::result,
591 this, &DolphinView::slotStatJobResult);
592 m_statJobForStatusBarText->start();
593 }
594 }
595
596 void DolphinView::emitStatusBarText(const int folderCount, const int fileCount,
597 KIO::filesize_t totalFileSize, const Selection selection)
598 {
599 QString foldersText;
600 QString filesText;
601 QString summary;
602
603 if (selection == HasSelection) {
604 // At least 2 items are selected because the case of 1 selected item is handled in
605 // DolphinView::requestStatusBarText().
606 foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
607 filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
608 } else {
609 foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount);
610 filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount);
611 }
612
613 if (fileCount > 0 && folderCount > 0) {
614 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
615 foldersText, filesText,
616 KFormat().formatByteSize(totalFileSize));
617 } else if (fileCount > 0) {
618 summary = i18nc("@info:status files (size)", "%1 (%2)",
619 filesText,
620 KFormat().formatByteSize(totalFileSize));
621 } else if (folderCount > 0) {
622 summary = foldersText;
623 } else {
624 summary = i18nc("@info:status", "0 Folders, 0 Files");
625 }
626 Q_EMIT statusBarTextChanged(summary);
627 }
628
629 QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
630 {
631 QList<QAction*> actions;
632
633 if (items.isEmpty()) {
634 const KFileItem item = m_model->rootItem();
635 if (!item.isNull()) {
636 actions = m_versionControlObserver->actions(KFileItemList() << item);
637 }
638 } else {
639 actions = m_versionControlObserver->actions(items);
640 }
641
642 return actions;
643 }
644
645 void DolphinView::setUrl(const QUrl& url)
646 {
647 if (url == m_url) {
648 return;
649 }
650
651 clearSelection();
652
653 m_url = url;
654
655 hideToolTip();
656
657 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
658 this, &DolphinView::slotRoleEditingFinished);
659
660 // It is important to clear the items from the model before
661 // applying the view properties, otherwise expensive operations
662 // might be done on the existing items although they get cleared
663 // anyhow afterwards by loadDirectory().
664 m_model->clear();
665 applyViewProperties();
666 loadDirectory(url);
667
668 Q_EMIT urlChanged(url);
669 }
670
671 void DolphinView::selectAll()
672 {
673 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
674 selectionManager->setSelected(0, m_model->count());
675 }
676
677 void DolphinView::invertSelection()
678 {
679 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
680 selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
681 }
682
683 void DolphinView::clearSelection()
684 {
685 m_selectedUrls.clear();
686 m_container->controller()->selectionManager()->clearSelection();
687 }
688
689 void DolphinView::renameSelectedItems()
690 {
691 const KFileItemList items = selectedItems();
692 if (items.isEmpty()) {
693 return;
694 }
695
696 if (items.count() == 1 && GeneralSettings::renameInline()) {
697 const int index = m_model->index(items.first());
698
699 QMetaObject::Connection * const connection = new QMetaObject::Connection;
700 *connection = connect(m_view, &KItemListView::scrollingStopped, this, [=](){
701 QObject::disconnect(*connection);
702 delete connection;
703
704 m_view->editRole(index, "text");
705
706 hideToolTip();
707
708 connect(m_view, &DolphinItemListView::roleEditingFinished,
709 this, &DolphinView::slotRoleEditingFinished);
710 });
711 m_view->scrollToItem(index);
712
713 } else {
714 KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(items, this);
715 connect(dialog, &KIO::RenameFileDialog::renamingFinished,
716 this, &DolphinView::slotRenameDialogRenamingFinished);
717
718 dialog->open();
719 }
720
721 // Assure that the current index remains visible when KFileItemModel
722 // will notify the view about changed items (which might result in
723 // a changed sorting).
724 m_assureVisibleCurrentIndex = true;
725 }
726
727 void DolphinView::trashSelectedItems()
728 {
729 const QList<QUrl> list = simplifiedSelectedUrls();
730 KIO::JobUiDelegate uiDelegate;
731 uiDelegate.setWindow(window());
732 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) {
733 KIO::Job* job = KIO::trash(list);
734 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job);
735 KJobWidgets::setWindow(job, this);
736 connect(job, &KIO::Job::result,
737 this, &DolphinView::slotTrashFileFinished);
738 }
739 }
740
741 void DolphinView::deleteSelectedItems()
742 {
743 const QList<QUrl> list = simplifiedSelectedUrls();
744
745 KIO::JobUiDelegate uiDelegate;
746 uiDelegate.setWindow(window());
747 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) {
748 KIO::Job* job = KIO::del(list);
749 KJobWidgets::setWindow(job, this);
750 connect(job, &KIO::Job::result,
751 this, &DolphinView::slotDeleteFileFinished);
752 }
753 }
754
755 void DolphinView::cutSelectedItemsToClipboard()
756 {
757 QMimeData* mimeData = selectionMimeData();
758 KIO::setClipboardDataCut(mimeData, true);
759 QApplication::clipboard()->setMimeData(mimeData);
760 }
761
762 void DolphinView::copySelectedItemsToClipboard()
763 {
764 QMimeData* mimeData = selectionMimeData();
765 QApplication::clipboard()->setMimeData(mimeData);
766 }
767
768 void DolphinView::copySelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
769 {
770 KIO::CopyJob* job = KIO::copy(selection.urlList(), destinationUrl, KIO::DefaultFlags);
771 KJobWidgets::setWindow(job, this);
772
773 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
774 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
775 KIO::FileUndoManager::self()->recordCopyJob(job);
776 }
777
778 void DolphinView::moveSelectedItems(const KFileItemList &selection, const QUrl &destinationUrl)
779 {
780 KIO::CopyJob* job = KIO::move(selection.urlList(), destinationUrl, KIO::DefaultFlags);
781 KJobWidgets::setWindow(job, this);
782
783 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
784 connect(job, &KIO::CopyJob::copyingDone, this, &DolphinView::slotCopyingDone);
785 KIO::FileUndoManager::self()->recordCopyJob(job);
786
787 }
788
789 void DolphinView::paste()
790 {
791 pasteToUrl(url());
792 }
793
794 void DolphinView::pasteIntoFolder()
795 {
796 const KFileItemList items = selectedItems();
797 if ((items.count() == 1) && items.first().isDir()) {
798 pasteToUrl(items.first().url());
799 }
800 }
801
802 void DolphinView::duplicateSelectedItems()
803 {
804 const KFileItemList itemList = selectedItems();
805 if (itemList.isEmpty()) {
806 return;
807 }
808
809 const QMimeDatabase db;
810
811 // Duplicate all selected items and append "copy" to the end of the file name
812 // but before the filename extension, if present
813 QList<QUrl> newSelection;
814 for (const auto &item : itemList) {
815 const QUrl originalURL = item.url();
816 const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
817 const QString originalFileName = item.name();
818
819 QString extension = db.suffixForFileName(originalFileName);
820
821 QUrl duplicateURL = originalURL;
822
823 // No extension; new filename is "<oldfilename> copy"
824 if (extension.isEmpty()) {
825 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFileName));
826 // There's an extension; new filename is "<oldfilename> copy.<extension>"
827 } else {
828 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
829 extension = QLatin1String(".") + extension;
830 const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size());
831 // Preserve file's original filename extension in case the casing differs
832 // from what QMimeDatabase::suffixForFileName() returned
833 const QString originalExtension = originalFileName.right(extension.size());
834 duplicateURL.setPath(originalDirectoryPath + i18nc("<filename> copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension);
835 }
836
837 KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL);
838 KJobWidgets::setWindow(job, this);
839
840 if (job) {
841 newSelection << duplicateURL;
842 KIO::FileUndoManager::self()->recordCopyJob(job);
843 }
844 }
845
846 forceUrlsSelection(newSelection.first(), newSelection);
847 }
848
849 void DolphinView::stopLoading()
850 {
851 m_model->cancelDirectoryLoading();
852 }
853
854 void DolphinView::updatePalette()
855 {
856 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
857 if (!m_active) {
858 color.setAlpha(150);
859 }
860
861 QWidget* viewport = m_container->viewport();
862 if (viewport) {
863 QPalette palette;
864 palette.setColor(viewport->backgroundRole(), color);
865 viewport->setPalette(palette);
866 }
867
868 update();
869 }
870
871 void DolphinView::abortTwoClicksRenaming()
872 {
873 m_twoClicksRenamingItemUrl.clear();
874 m_twoClicksRenamingTimer->stop();
875 }
876
877 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
878 {
879 switch (event->type()) {
880 case QEvent::PaletteChange:
881 updatePalette();
882 QPixmapCache::clear();
883 break;
884
885 case QEvent::WindowActivate:
886 case QEvent::WindowDeactivate:
887 updatePalette();
888 break;
889
890 case QEvent::KeyPress:
891 hideToolTip(ToolTipManager::HideBehavior::Instantly);
892 if (GeneralSettings::useTabForSwitchingSplitView()) {
893 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
894 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
895 Q_EMIT toggleActiveViewRequested();
896 return true;
897 }
898 }
899 break;
900 case QEvent::FocusIn:
901 if (watched == m_container) {
902 setActive(true);
903 }
904 break;
905
906 case QEvent::GraphicsSceneDragEnter:
907 if (watched == m_view) {
908 m_dragging = true;
909 abortTwoClicksRenaming();
910 }
911 break;
912
913 case QEvent::GraphicsSceneDragLeave:
914 if (watched == m_view) {
915 m_dragging = false;
916 }
917 break;
918
919 case QEvent::GraphicsSceneDrop:
920 if (watched == m_view) {
921 m_dragging = false;
922 }
923 default:
924 break;
925 }
926
927 return QWidget::eventFilter(watched, event);
928 }
929
930 void DolphinView::wheelEvent(QWheelEvent* event)
931 {
932 if (event->modifiers().testFlag(Qt::ControlModifier)) {
933 const QPoint numDegrees = event->angleDelta() / 8;
934 const QPoint numSteps = numDegrees / 15;
935
936 setZoomLevel(zoomLevel() + numSteps.y());
937 event->accept();
938 } else {
939 event->ignore();
940 }
941 }
942
943 void DolphinView::hideEvent(QHideEvent* event)
944 {
945 hideToolTip();
946 QWidget::hideEvent(event);
947 }
948
949 bool DolphinView::event(QEvent* event)
950 {
951 if (event->type() == QEvent::WindowDeactivate) {
952 /* See Bug 297355
953 * Dolphin leaves file preview tooltips open even when is not visible.
954 *
955 * Hide tool-tip when Dolphin loses focus.
956 */
957 hideToolTip();
958 abortTwoClicksRenaming();
959 }
960
961 return QWidget::event(event);
962 }
963
964 void DolphinView::activate()
965 {
966 setActive(true);
967 }
968
969 void DolphinView::slotItemActivated(int index)
970 {
971 abortTwoClicksRenaming();
972
973 const KFileItem item = m_model->fileItem(index);
974 if (!item.isNull()) {
975 Q_EMIT itemActivated(item);
976 }
977 }
978
979 void DolphinView::slotItemsActivated(const KItemSet& indexes)
980 {
981 Q_ASSERT(indexes.count() >= 2);
982
983 abortTwoClicksRenaming();
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()) { // Open folders in new tabs
1001 Q_EMIT tabRequested(url);
1002 } else {
1003 items.append(item);
1004 }
1005 }
1006
1007 if (items.count() == 1) {
1008 Q_EMIT itemActivated(items.first());
1009 } else if (items.count() > 1) {
1010 Q_EMIT itemsActivated(items);
1011 }
1012 }
1013
1014 void DolphinView::slotItemMiddleClicked(int index)
1015 {
1016 const KFileItem& item = m_model->fileItem(index);
1017 const QUrl& url = openItemAsFolderUrl(item);
1018 if (!url.isEmpty()) {
1019 Q_EMIT tabRequested(url);
1020 } else if (isTabsForFilesEnabled()) {
1021 Q_EMIT tabRequested(item.url());
1022 }
1023 }
1024
1025 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
1026 {
1027 // Force emit of a selection changed signal before we request the
1028 // context menu, to update the edit-actions first. (See Bug 294013)
1029 if (m_selectionChangedTimer->isActive()) {
1030 emitSelectionChangedSignal();
1031 }
1032
1033 const KFileItem item = m_model->fileItem(index);
1034 Q_EMIT requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
1035 }
1036
1037 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
1038 {
1039 Q_EMIT requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
1040 }
1041
1042 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
1043 {
1044 ViewProperties props(viewPropertiesUrl());
1045
1046 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
1047
1048 KItemListView* view = m_container->controller()->view();
1049 const QList<QByteArray> visibleRolesSet = view->visibleRoles();
1050
1051 bool indexingEnabled = false;
1052 #ifdef HAVE_BALOO
1053 Baloo::IndexerConfig config;
1054 indexingEnabled = config.fileIndexingEnabled();
1055 #endif
1056
1057 QString groupName;
1058 QMenu* groupMenu = nullptr;
1059
1060 // Add all roles to the menu that can be shown or hidden by the user
1061 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
1062 for (const KFileItemModel::RoleInfo& info : rolesInfo) {
1063 if (info.role == "text") {
1064 // It should not be possible to hide the "text" role
1065 continue;
1066 }
1067
1068 const QString text = m_model->roleDescription(info.role);
1069 QAction* action = nullptr;
1070 if (info.group.isEmpty()) {
1071 action = menu->addAction(text);
1072 } else {
1073 if (!groupMenu || info.group != groupName) {
1074 groupName = info.group;
1075 groupMenu = menu->addMenu(groupName);
1076 }
1077
1078 action = groupMenu->addAction(text);
1079 }
1080
1081 action->setCheckable(true);
1082 action->setChecked(visibleRolesSet.contains(info.role));
1083 action->setData(info.role);
1084
1085 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
1086 (info.requiresBaloo) ||
1087 (info.requiresIndexer && indexingEnabled);
1088 action->setEnabled(enable);
1089 }
1090
1091 menu->addSeparator();
1092
1093 QActionGroup* widthsGroup = new QActionGroup(menu);
1094 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
1095
1096 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1097 autoAdjustWidthsAction->setCheckable(true);
1098 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1099 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1100
1101 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1102 customWidthsAction->setCheckable(true);
1103 customWidthsAction->setChecked(!autoColumnWidths);
1104 customWidthsAction->setActionGroup(widthsGroup);
1105
1106 QAction* action = menu->exec(pos.toPoint());
1107 if (menu && action) {
1108 KItemListHeader* header = view->header();
1109
1110 if (action == autoAdjustWidthsAction) {
1111 // Clear the column-widths from the viewproperties and turn on
1112 // the automatic resizing of the columns
1113 props.setHeaderColumnWidths(QList<int>());
1114 header->setAutomaticColumnResizing(true);
1115 } else if (action == customWidthsAction) {
1116 // Apply the current column-widths as custom column-widths and turn
1117 // off the automatic resizing of the columns
1118 QList<int> columnWidths;
1119 const auto visibleRoles = view->visibleRoles();
1120 columnWidths.reserve(visibleRoles.count());
1121 for (const QByteArray& role : visibleRoles) {
1122 columnWidths.append(header->columnWidth(role));
1123 }
1124 props.setHeaderColumnWidths(columnWidths);
1125 header->setAutomaticColumnResizing(false);
1126 } else {
1127 // Show or hide the selected role
1128 const QByteArray selectedRole = action->data().toByteArray();
1129
1130 QList<QByteArray> visibleRoles = view->visibleRoles();
1131 if (action->isChecked()) {
1132 visibleRoles.append(selectedRole);
1133 } else {
1134 visibleRoles.removeOne(selectedRole);
1135 }
1136
1137 view->setVisibleRoles(visibleRoles);
1138 props.setVisibleRoles(visibleRoles);
1139
1140 QList<int> columnWidths;
1141 if (!header->automaticColumnResizing()) {
1142 const auto visibleRoles = view->visibleRoles();
1143 columnWidths.reserve(visibleRoles.count());
1144 for (const QByteArray& role : visibleRoles) {
1145 columnWidths.append(header->columnWidth(role));
1146 }
1147 }
1148 props.setHeaderColumnWidths(columnWidths);
1149 }
1150 }
1151
1152 delete menu;
1153 }
1154
1155 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1156 {
1157 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1158
1159 ViewProperties props(viewPropertiesUrl());
1160 QList<int> columnWidths = props.headerColumnWidths();
1161 if (columnWidths.count() != visibleRoles.count()) {
1162 columnWidths.clear();
1163 columnWidths.reserve(visibleRoles.count());
1164 const KItemListHeader* header = m_view->header();
1165 for (const QByteArray& role : visibleRoles) {
1166 const int width = header->columnWidth(role);
1167 columnWidths.append(width);
1168 }
1169 }
1170
1171 const int roleIndex = visibleRoles.indexOf(role);
1172 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1173 columnWidths[roleIndex] = current;
1174
1175 props.setHeaderColumnWidths(columnWidths);
1176 }
1177
1178 void DolphinView::slotItemHovered(int index)
1179 {
1180 const KFileItem item = m_model->fileItem(index);
1181
1182 if (GeneralSettings::showToolTips() && !m_dragging) {
1183 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1184 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1185 itemRect.moveTo(pos);
1186
1187 #ifdef HAVE_BALOO
1188 m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle());
1189 #endif
1190 }
1191
1192 Q_EMIT requestItemInfo(item);
1193 }
1194
1195 void DolphinView::slotItemUnhovered(int index)
1196 {
1197 Q_UNUSED(index)
1198 hideToolTip();
1199 Q_EMIT requestItemInfo(KFileItem());
1200 }
1201
1202 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1203 {
1204 QUrl destUrl;
1205 KFileItem destItem = m_model->fileItem(index);
1206 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1207 // Use the URL of the view as drop target if the item is no directory
1208 // or desktop-file
1209 destItem = m_model->rootItem();
1210 destUrl = url();
1211 } else {
1212 // The item represents a directory or desktop-file
1213 destUrl = destItem.mostLocalUrl();
1214 }
1215
1216 QDropEvent dropEvent(event->pos().toPoint(),
1217 event->possibleActions(),
1218 event->mimeData(),
1219 event->buttons(),
1220 event->modifiers());
1221 dropUrls(destUrl, &dropEvent, this);
1222
1223 setActive(true);
1224 }
1225
1226 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1227 {
1228 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1229
1230 if (job) {
1231 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1232
1233 if (destUrl == url()) {
1234 // Mark the dropped urls as selected.
1235 m_clearSelectionBeforeSelectingNewItems = true;
1236 m_markFirstNewlySelectedItemAsCurrent = true;
1237 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1238 }
1239 }
1240 }
1241
1242 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1243 {
1244 if (previous != nullptr) {
1245 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1246 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1247 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1248 m_versionControlObserver->setModel(nullptr);
1249 }
1250
1251 if (current) {
1252 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1253 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1254 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1255 m_versionControlObserver->setModel(fileItemModel);
1256 }
1257 }
1258
1259 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1260 {
1261 Q_UNUSED(itemIndex)
1262
1263 hideToolTip();
1264
1265 if (buttons & Qt::BackButton) {
1266 Q_EMIT goBackRequested();
1267 } else if (buttons & Qt::ForwardButton) {
1268 Q_EMIT goForwardRequested();
1269 }
1270 }
1271
1272 void DolphinView::slotSelectedItemTextPressed(int index)
1273 {
1274 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1275 const KFileItem item = m_model->fileItem(index);
1276 const KFileItemListProperties capabilities(KFileItemList() << item);
1277 if (capabilities.supportsMoving()) {
1278 m_twoClicksRenamingItemUrl = item.url();
1279 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1280 }
1281 }
1282 }
1283
1284 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1285 {
1286 slotItemCreated(to);
1287 }
1288
1289 void DolphinView::slotItemCreated(const QUrl& url)
1290 {
1291 if (m_markFirstNewlySelectedItemAsCurrent) {
1292 markUrlAsCurrent(url);
1293 m_markFirstNewlySelectedItemAsCurrent = false;
1294 }
1295 m_selectedUrls << url;
1296 }
1297
1298 void DolphinView::slotJobResult(KJob *job)
1299 {
1300 if (job->error()) {
1301 Q_EMIT errorMessage(job->errorString());
1302 }
1303 if (!m_selectedUrls.isEmpty()) {
1304 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1305 }
1306 }
1307
1308 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1309 {
1310 const int currentCount = current.count();
1311 const int previousCount = previous.count();
1312 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1313 (currentCount > 0 && previousCount == 0);
1314
1315 // If nothing has been selected before and something got selected (or if something
1316 // was selected before and now nothing is selected) the selectionChangedSignal must
1317 // be emitted asynchronously as fast as possible to update the edit-actions.
1318 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1319 m_selectionChangedTimer->start();
1320 }
1321
1322 void DolphinView::emitSelectionChangedSignal()
1323 {
1324 m_selectionChangedTimer->stop();
1325 Q_EMIT selectionChanged(selectedItems());
1326 }
1327
1328 void DolphinView::slotStatJobResult(KJob *job)
1329 {
1330 int folderCount = 0;
1331 int fileCount = 0;
1332 KIO::filesize_t totalFileSize = 0;
1333 bool countFileSize = true;
1334
1335 const auto entry = static_cast<KIO::StatJob *>(job)->statResult();
1336 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1337 // We have a precomputed value.
1338 totalFileSize = static_cast<KIO::filesize_t>(
1339 entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1340 countFileSize = false;
1341 }
1342
1343 const int itemCount = m_model->count();
1344 for (int i = 0; i < itemCount; ++i) {
1345 const KFileItem item = m_model->fileItem(i);
1346 if (item.isDir()) {
1347 ++folderCount;
1348 } else {
1349 ++fileCount;
1350 if (countFileSize) {
1351 totalFileSize += item.size();
1352 }
1353 }
1354 }
1355 emitStatusBarText(folderCount, fileCount, totalFileSize, NoSelection);
1356 }
1357
1358 void DolphinView::updateSortRole(const QByteArray& role)
1359 {
1360 ViewProperties props(viewPropertiesUrl());
1361 props.setSortRole(role);
1362
1363 KItemModelBase* model = m_container->controller()->model();
1364 model->setSortRole(role);
1365
1366 Q_EMIT sortRoleChanged(role);
1367 }
1368
1369 void DolphinView::updateSortOrder(Qt::SortOrder order)
1370 {
1371 ViewProperties props(viewPropertiesUrl());
1372 props.setSortOrder(order);
1373
1374 m_model->setSortOrder(order);
1375
1376 Q_EMIT sortOrderChanged(order);
1377 }
1378
1379 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1380 {
1381 ViewProperties props(viewPropertiesUrl());
1382 props.setSortFoldersFirst(foldersFirst);
1383
1384 m_model->setSortDirectoriesFirst(foldersFirst);
1385
1386 Q_EMIT sortFoldersFirstChanged(foldersFirst);
1387 }
1388
1389 void DolphinView::updateSortHiddenLast(bool hiddenLast)
1390 {
1391 ViewProperties props(viewPropertiesUrl());
1392 props.setSortHiddenLast(hiddenLast);
1393
1394 m_model->setSortHiddenLast(hiddenLast);
1395
1396 Q_EMIT sortHiddenLastChanged(hiddenLast);
1397 }
1398
1399
1400 QPair<bool, QString> DolphinView::pasteInfo() const
1401 {
1402 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1403 QPair<bool, QString> info;
1404 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1405 return info;
1406 }
1407
1408 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1409 {
1410 m_tabsForFiles = tabsForFiles;
1411 }
1412
1413 bool DolphinView::isTabsForFilesEnabled() const
1414 {
1415 return m_tabsForFiles;
1416 }
1417
1418 bool DolphinView::itemsExpandable() const
1419 {
1420 return m_mode == DetailsView;
1421 }
1422
1423 void DolphinView::restoreState(QDataStream& stream)
1424 {
1425 // Read the version number of the view state and check if the version is supported.
1426 quint32 version = 0;
1427 stream >> version;
1428 if (version != 1) {
1429 // The version of the view state isn't supported, we can't restore it.
1430 return;
1431 }
1432
1433 // Restore the current item that had the keyboard focus
1434 stream >> m_currentItemUrl;
1435
1436 // Restore the previously selected items
1437 stream >> m_selectedUrls;
1438
1439 // Restore the view position
1440 stream >> m_restoredContentsPosition;
1441
1442 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1443 QSet<QUrl> urls;
1444 stream >> urls;
1445 m_model->restoreExpandedDirectories(urls);
1446 }
1447
1448 void DolphinView::saveState(QDataStream& stream)
1449 {
1450 stream << quint32(1); // View state version
1451
1452 // Save the current item that has the keyboard focus
1453 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1454 if (currentIndex != -1) {
1455 KFileItem item = m_model->fileItem(currentIndex);
1456 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1457 QUrl currentItemUrl = item.url();
1458 stream << currentItemUrl;
1459 } else {
1460 stream << QUrl();
1461 }
1462
1463 // Save the selected urls
1464 stream << selectedItems().urlList();
1465
1466 // Save view position
1467 const qreal x = m_container->horizontalScrollBar()->value();
1468 const qreal y = m_container->verticalScrollBar()->value();
1469 stream << QPoint(x, y);
1470
1471 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1472 stream << m_model->expandedDirectories();
1473 }
1474
1475 KFileItem DolphinView::rootItem() const
1476 {
1477 return m_model->rootItem();
1478 }
1479
1480 void DolphinView::setViewPropertiesContext(const QString& context)
1481 {
1482 m_viewPropertiesContext = context;
1483 }
1484
1485 QString DolphinView::viewPropertiesContext() const
1486 {
1487 return m_viewPropertiesContext;
1488 }
1489
1490 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1491 {
1492 if (item.isNull()) {
1493 return QUrl();
1494 }
1495
1496 QUrl url = item.targetUrl();
1497
1498 if (item.isDir()) {
1499 return url;
1500 }
1501
1502 if (item.isMimeTypeKnown()) {
1503 const QString& mimetype = item.mimetype();
1504
1505 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1506 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1507 // zip:/<path>/ when clicking on a zip file, etc.
1508 // The .protocol file specifies the mimetype that the kioslave handles.
1509 // Note that we don't use mimetype inheritance since we don't want to
1510 // open OpenDocument files as zip folders...
1511 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1512 if (!protocol.isEmpty()) {
1513 url.setScheme(protocol);
1514 return url;
1515 }
1516 }
1517
1518 if (mimetype == QLatin1String("application/x-desktop")) {
1519 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1520 KDesktopFile desktopFile(url.toLocalFile());
1521 if (desktopFile.hasLinkType()) {
1522 const QString linkUrl = desktopFile.readUrl();
1523 if (!linkUrl.startsWith(QLatin1String("http"))) {
1524 return QUrl::fromUserInput(linkUrl);
1525 }
1526 }
1527 }
1528 }
1529
1530 return QUrl();
1531 }
1532
1533 void DolphinView::resetZoomLevel()
1534 {
1535 // TODO : Switch to using ViewModeSettings after MR #256 is merged
1536 int defaultIconSize = KIconLoader::SizeSmall;
1537 switch (m_mode) {
1538 case IconsView:
1539 IconsModeSettings::self()->useDefaults(true);
1540 defaultIconSize = IconsModeSettings::iconSize();
1541 IconsModeSettings::self()->useDefaults(false);
1542 break;
1543 case DetailsView:
1544 DetailsModeSettings::self()->useDefaults(true);
1545 defaultIconSize = DetailsModeSettings::iconSize();
1546 DetailsModeSettings::self()->useDefaults(false);
1547 break;
1548 case CompactView:
1549 CompactModeSettings::self()->useDefaults(true);
1550 defaultIconSize = CompactModeSettings::iconSize();
1551 CompactModeSettings::self()->useDefaults(false);
1552 break;
1553 default:
1554 Q_ASSERT(false);
1555 break;
1556 }
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 }