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