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