]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Fix unused variable warning
[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 foreach (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 QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
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 foreach (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 columnWidths.reserve(view->visibleRoles().count());
1037 foreach (const QByteArray& role, view->visibleRoles()) {
1038 columnWidths.append(header->columnWidth(role));
1039 }
1040 props.setHeaderColumnWidths(columnWidths);
1041 header->setAutomaticColumnResizing(false);
1042 } else {
1043 // Show or hide the selected role
1044 const QByteArray selectedRole = action->data().toByteArray();
1045
1046 QList<QByteArray> visibleRoles = view->visibleRoles();
1047 if (action->isChecked()) {
1048 visibleRoles.append(selectedRole);
1049 } else {
1050 visibleRoles.removeOne(selectedRole);
1051 }
1052
1053 view->setVisibleRoles(visibleRoles);
1054 props.setVisibleRoles(visibleRoles);
1055
1056 QList<int> columnWidths;
1057 if (!header->automaticColumnResizing()) {
1058 columnWidths.reserve(view->visibleRoles().count());
1059 foreach (const QByteArray& role, view->visibleRoles()) {
1060 columnWidths.append(header->columnWidth(role));
1061 }
1062 }
1063 props.setHeaderColumnWidths(columnWidths);
1064 }
1065 }
1066
1067 delete menu;
1068 }
1069
1070 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1071 {
1072 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1073
1074 ViewProperties props(viewPropertiesUrl());
1075 QList<int> columnWidths = props.headerColumnWidths();
1076 if (columnWidths.count() != visibleRoles.count()) {
1077 columnWidths.clear();
1078 columnWidths.reserve(visibleRoles.count());
1079 const KItemListHeader* header = m_view->header();
1080 foreach (const QByteArray& role, visibleRoles) {
1081 const int width = header->columnWidth(role);
1082 columnWidths.append(width);
1083 }
1084 }
1085
1086 const int roleIndex = visibleRoles.indexOf(role);
1087 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1088 columnWidths[roleIndex] = current;
1089
1090 props.setHeaderColumnWidths(columnWidths);
1091 }
1092
1093 void DolphinView::slotItemHovered(int index)
1094 {
1095 const KFileItem item = m_model->fileItem(index);
1096
1097 if (GeneralSettings::showToolTips() && !m_dragging) {
1098 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1099 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1100 itemRect.moveTo(pos);
1101
1102 #ifdef HAVE_BALOO
1103 m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle());
1104 #endif
1105 }
1106
1107 emit requestItemInfo(item);
1108 }
1109
1110 void DolphinView::slotItemUnhovered(int index)
1111 {
1112 Q_UNUSED(index)
1113 hideToolTip();
1114 emit requestItemInfo(KFileItem());
1115 }
1116
1117 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1118 {
1119 QUrl destUrl;
1120 KFileItem destItem = m_model->fileItem(index);
1121 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1122 // Use the URL of the view as drop target if the item is no directory
1123 // or desktop-file
1124 destItem = m_model->rootItem();
1125 destUrl = url();
1126 } else {
1127 // The item represents a directory or desktop-file
1128 destUrl = destItem.mostLocalUrl();
1129 }
1130
1131 QDropEvent dropEvent(event->pos().toPoint(),
1132 event->possibleActions(),
1133 event->mimeData(),
1134 event->buttons(),
1135 event->modifiers());
1136 dropUrls(destUrl, &dropEvent, this);
1137
1138 setActive(true);
1139 }
1140
1141 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1142 {
1143 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1144
1145 if (job) {
1146 connect(job, &KIO::DropJob::result, this, &DolphinView::slotJobResult);
1147
1148 if (destUrl == url()) {
1149 // Mark the dropped urls as selected.
1150 m_clearSelectionBeforeSelectingNewItems = true;
1151 m_markFirstNewlySelectedItemAsCurrent = true;
1152 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1153 }
1154 }
1155 }
1156
1157 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1158 {
1159 if (previous != nullptr) {
1160 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1161 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1162 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1163 m_versionControlObserver->setModel(nullptr);
1164 }
1165
1166 if (current) {
1167 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1168 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1169 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1170 m_versionControlObserver->setModel(fileItemModel);
1171 }
1172 }
1173
1174 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1175 {
1176 Q_UNUSED(itemIndex)
1177
1178 hideToolTip();
1179
1180 if (buttons & Qt::BackButton) {
1181 emit goBackRequested();
1182 } else if (buttons & Qt::ForwardButton) {
1183 emit goForwardRequested();
1184 }
1185 }
1186
1187 void DolphinView::slotSelectedItemTextPressed(int index)
1188 {
1189 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1190 const KFileItem item = m_model->fileItem(index);
1191 const KFileItemListProperties capabilities(KFileItemList() << item);
1192 if (capabilities.supportsMoving()) {
1193 m_twoClicksRenamingItemUrl = item.url();
1194 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1195 }
1196 }
1197 }
1198
1199 void DolphinView::slotCopyingDone(KIO::Job *, const QUrl &, const QUrl &to)
1200 {
1201 slotItemCreated(to);
1202 }
1203
1204 void DolphinView::slotItemCreated(const QUrl& url)
1205 {
1206 if (m_markFirstNewlySelectedItemAsCurrent) {
1207 markUrlAsCurrent(url);
1208 m_markFirstNewlySelectedItemAsCurrent = false;
1209 }
1210 m_selectedUrls << url;
1211 }
1212
1213 void DolphinView::slotJobResult(KJob *job)
1214 {
1215 if (job->error()) {
1216 emit errorMessage(job->errorString());
1217 }
1218 if (!m_selectedUrls.isEmpty()) {
1219 m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls);
1220 }
1221 }
1222
1223 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1224 {
1225 const int currentCount = current.count();
1226 const int previousCount = previous.count();
1227 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1228 (currentCount > 0 && previousCount == 0);
1229
1230 // If nothing has been selected before and something got selected (or if something
1231 // was selected before and now nothing is selected) the selectionChangedSignal must
1232 // be emitted asynchronously as fast as possible to update the edit-actions.
1233 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1234 m_selectionChangedTimer->start();
1235 }
1236
1237 void DolphinView::emitSelectionChangedSignal()
1238 {
1239 m_selectionChangedTimer->stop();
1240 emit selectionChanged(selectedItems());
1241 }
1242
1243 void DolphinView::updateSortRole(const QByteArray& role)
1244 {
1245 ViewProperties props(viewPropertiesUrl());
1246 props.setSortRole(role);
1247
1248 KItemModelBase* model = m_container->controller()->model();
1249 model->setSortRole(role);
1250
1251 emit sortRoleChanged(role);
1252 }
1253
1254 void DolphinView::updateSortOrder(Qt::SortOrder order)
1255 {
1256 ViewProperties props(viewPropertiesUrl());
1257 props.setSortOrder(order);
1258
1259 m_model->setSortOrder(order);
1260
1261 emit sortOrderChanged(order);
1262 }
1263
1264 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1265 {
1266 ViewProperties props(viewPropertiesUrl());
1267 props.setSortFoldersFirst(foldersFirst);
1268
1269 m_model->setSortDirectoriesFirst(foldersFirst);
1270
1271 emit sortFoldersFirstChanged(foldersFirst);
1272 }
1273
1274 QPair<bool, QString> DolphinView::pasteInfo() const
1275 {
1276 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1277 QPair<bool, QString> info;
1278 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1279 return info;
1280 }
1281
1282 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1283 {
1284 m_tabsForFiles = tabsForFiles;
1285 }
1286
1287 bool DolphinView::isTabsForFilesEnabled() const
1288 {
1289 return m_tabsForFiles;
1290 }
1291
1292 bool DolphinView::itemsExpandable() const
1293 {
1294 return m_mode == DetailsView;
1295 }
1296
1297 void DolphinView::restoreState(QDataStream& stream)
1298 {
1299 // Read the version number of the view state and check if the version is supported.
1300 quint32 version = 0;
1301 stream >> version;
1302 if (version != 1) {
1303 // The version of the view state isn't supported, we can't restore it.
1304 return;
1305 }
1306
1307 // Restore the current item that had the keyboard focus
1308 stream >> m_currentItemUrl;
1309
1310 // Restore the previously selected items
1311 stream >> m_selectedUrls;
1312
1313 // Restore the view position
1314 stream >> m_restoredContentsPosition;
1315
1316 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1317 QSet<QUrl> urls;
1318 stream >> urls;
1319 m_model->restoreExpandedDirectories(urls);
1320 }
1321
1322 void DolphinView::saveState(QDataStream& stream)
1323 {
1324 stream << quint32(1); // View state version
1325
1326 // Save the current item that has the keyboard focus
1327 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1328 if (currentIndex != -1) {
1329 KFileItem item = m_model->fileItem(currentIndex);
1330 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1331 QUrl currentItemUrl = item.url();
1332 stream << currentItemUrl;
1333 } else {
1334 stream << QUrl();
1335 }
1336
1337 // Save the selected urls
1338 stream << selectedItems().urlList();
1339
1340 // Save view position
1341 const qreal x = m_container->horizontalScrollBar()->value();
1342 const qreal y = m_container->verticalScrollBar()->value();
1343 stream << QPoint(x, y);
1344
1345 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1346 stream << m_model->expandedDirectories();
1347 }
1348
1349 KFileItem DolphinView::rootItem() const
1350 {
1351 return m_model->rootItem();
1352 }
1353
1354 void DolphinView::setViewPropertiesContext(const QString& context)
1355 {
1356 m_viewPropertiesContext = context;
1357 }
1358
1359 QString DolphinView::viewPropertiesContext() const
1360 {
1361 return m_viewPropertiesContext;
1362 }
1363
1364 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1365 {
1366 if (item.isNull()) {
1367 return QUrl();
1368 }
1369
1370 QUrl url = item.targetUrl();
1371
1372 if (item.isDir()) {
1373 return url;
1374 }
1375
1376 if (item.isMimeTypeKnown()) {
1377 const QString& mimetype = item.mimetype();
1378
1379 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1380 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1381 // zip:/<path>/ when clicking on a zip file, etc.
1382 // The .protocol file specifies the mimetype that the kioslave handles.
1383 // Note that we don't use mimetype inheritance since we don't want to
1384 // open OpenDocument files as zip folders...
1385 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1386 if (!protocol.isEmpty()) {
1387 url.setScheme(protocol);
1388 return url;
1389 }
1390 }
1391
1392 if (mimetype == QLatin1String("application/x-desktop")) {
1393 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1394 KDesktopFile desktopFile(url.toLocalFile());
1395 if (desktopFile.hasLinkType()) {
1396 const QString linkUrl = desktopFile.readUrl();
1397 if (!linkUrl.startsWith(QLatin1String("http"))) {
1398 return QUrl::fromUserInput(linkUrl);
1399 }
1400 }
1401 }
1402 }
1403
1404 return QUrl();
1405 }
1406
1407 void DolphinView::resetZoomLevel()
1408 {
1409 ViewModeSettings::ViewMode mode;
1410
1411 switch (m_mode) {
1412 case IconsView: mode = ViewModeSettings::IconsMode; break;
1413 case CompactView: mode = ViewModeSettings::CompactMode; break;
1414 case DetailsView: mode = ViewModeSettings::DetailsMode; break;
1415 }
1416 const ViewModeSettings settings(mode);
1417 const QSize iconSize = QSize(settings.iconSize(), settings.iconSize());
1418 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize));
1419 }
1420
1421 void DolphinView::observeCreatedItem(const QUrl& url)
1422 {
1423 if (m_active) {
1424 forceUrlsSelection(url, {url});
1425 }
1426 }
1427
1428 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1429 {
1430 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1431 emit redirection(oldUrl, newUrl);
1432 m_url = newUrl; // #186947
1433 }
1434 }
1435
1436 void DolphinView::updateViewState()
1437 {
1438 if (m_currentItemUrl != QUrl()) {
1439 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1440
1441 // if there is a selection already, leave it that way
1442 if (!selectionManager->hasSelection()) {
1443 const int currentIndex = m_model->index(m_currentItemUrl);
1444 if (currentIndex != -1) {
1445 selectionManager->setCurrentItem(currentIndex);
1446
1447 // scroll to current item and reset the state
1448 if (m_scrollToCurrentItem) {
1449 m_view->scrollToItem(currentIndex);
1450 m_scrollToCurrentItem = false;
1451 }
1452 } else {
1453 selectionManager->setCurrentItem(0);
1454 }
1455 }
1456
1457 m_currentItemUrl = QUrl();
1458 }
1459
1460 if (!m_restoredContentsPosition.isNull()) {
1461 const int x = m_restoredContentsPosition.x();
1462 const int y = m_restoredContentsPosition.y();
1463 m_restoredContentsPosition = QPoint();
1464
1465 m_container->horizontalScrollBar()->setValue(x);
1466 m_container->verticalScrollBar()->setValue(y);
1467 }
1468
1469 if (!m_selectedUrls.isEmpty()) {
1470 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1471
1472 // if there is a selection already, leave it that way
1473 if (!selectionManager->hasSelection()) {
1474 if (m_clearSelectionBeforeSelectingNewItems) {
1475 selectionManager->clearSelection();
1476 m_clearSelectionBeforeSelectingNewItems = false;
1477 }
1478
1479 KItemSet selectedItems = selectionManager->selectedItems();
1480
1481 QList<QUrl>::iterator it = m_selectedUrls.begin();
1482 while (it != m_selectedUrls.end()) {
1483 const int index = m_model->index(*it);
1484 if (index >= 0) {
1485 selectedItems.insert(index);
1486 it = m_selectedUrls.erase(it);
1487 } else {
1488 ++it;
1489 }
1490 }
1491
1492 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1493 selectionManager->setSelectedItems(selectedItems);
1494 }
1495 }
1496 }
1497
1498 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1499 {
1500 #ifdef HAVE_BALOO
1501 if (GeneralSettings::showToolTips()) {
1502 m_toolTipManager->hideToolTip(behavior);
1503 }
1504 #else
1505 Q_UNUSED(behavior)
1506 #endif
1507 }
1508
1509 void DolphinView::calculateItemCount(int& fileCount,
1510 int& folderCount,
1511 KIO::filesize_t& totalFileSize) const
1512 {
1513 const int itemCount = m_model->count();
1514
1515 bool countFileSize = true;
1516
1517 if (!m_model->rootItem().url().isValid()) {
1518 return;
1519 }
1520
1521 // In case we have a precomputed value
1522 const auto job = KIO::statDetails(m_model->rootItem().url(), KIO::StatJob::SourceSide, KIO::StatRecursiveSize, KIO::HideProgressInfo);
1523 job->exec();
1524 const auto entry = job->statResult();
1525 if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) {
1526 totalFileSize = static_cast<KIO::filesize_t>(entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE));
1527 countFileSize = false;
1528 }
1529
1530 for (int i = 0; i < itemCount; ++i) {
1531 const KFileItem item = m_model->fileItem(i);
1532 if (item.isDir()) {
1533 ++folderCount;
1534 } else {
1535 ++fileCount;
1536 if (countFileSize) {
1537 totalFileSize += item.size();
1538 }
1539 }
1540 }
1541 }
1542
1543 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1544 {
1545 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1546
1547 // verify that only one item is selected
1548 if (selectionManager->selectedItems().count() == 1) {
1549 const int index = selectionManager->currentItem();
1550 const QUrl fileItemUrl = m_model->fileItem(index).url();
1551
1552 // check if the selected item was the same item that started the twoClicksRenaming
1553 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1554 renameSelectedItems();
1555 }
1556 }
1557 }
1558
1559 void DolphinView::slotTrashFileFinished(KJob* job)
1560 {
1561 if (job->error() == 0) {
1562 emit operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1563 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1564 emit errorMessage(job->errorString());
1565 }
1566 }
1567
1568 void DolphinView::slotDeleteFileFinished(KJob* job)
1569 {
1570 if (job->error() == 0) {
1571 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1572 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1573 emit errorMessage(job->errorString());
1574 }
1575 }
1576
1577 void DolphinView::slotRenamingResult(KJob* job)
1578 {
1579 if (job->error()) {
1580 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1581 Q_ASSERT(copyJob);
1582 const QUrl newUrl = copyJob->destUrl();
1583 const int index = m_model->index(newUrl);
1584 if (index >= 0) {
1585 QHash<QByteArray, QVariant> data;
1586 const QUrl oldUrl = copyJob->srcUrls().at(0);
1587 data.insert("text", oldUrl.fileName());
1588 m_model->setData(index, data);
1589 }
1590 }
1591 }
1592
1593 void DolphinView::slotDirectoryLoadingStarted()
1594 {
1595 // Disable the writestate temporary until it can be determined in a fast way
1596 // in DolphinView::slotDirectoryLoadingCompleted()
1597 if (m_isFolderWritable) {
1598 m_isFolderWritable = false;
1599 emit writeStateChanged(m_isFolderWritable);
1600 }
1601
1602 emit directoryLoadingStarted();
1603 }
1604
1605 void DolphinView::slotDirectoryLoadingCompleted()
1606 {
1607 // Update the view-state. This has to be done asynchronously
1608 // because the view might not be in its final state yet.
1609 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1610
1611 emit directoryLoadingCompleted();
1612
1613 updateWritableState();
1614 }
1615
1616 void DolphinView::slotItemsChanged()
1617 {
1618 m_assureVisibleCurrentIndex = false;
1619 }
1620
1621 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1622 {
1623 Q_UNUSED(previous)
1624 Q_ASSERT(m_model->sortOrder() == current);
1625
1626 ViewProperties props(viewPropertiesUrl());
1627 props.setSortOrder(current);
1628
1629 emit sortOrderChanged(current);
1630 }
1631
1632 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1633 {
1634 Q_UNUSED(previous)
1635 Q_ASSERT(m_model->sortRole() == current);
1636
1637 ViewProperties props(viewPropertiesUrl());
1638 props.setSortRole(current);
1639
1640 emit sortRoleChanged(current);
1641 }
1642
1643 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1644 const QList<QByteArray>& previous)
1645 {
1646 Q_UNUSED(previous)
1647 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1648
1649 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1650
1651 m_visibleRoles = current;
1652
1653 ViewProperties props(viewPropertiesUrl());
1654 props.setVisibleRoles(m_visibleRoles);
1655
1656 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1657 }
1658
1659 void DolphinView::slotRoleEditingCanceled()
1660 {
1661 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1662 this, &DolphinView::slotRoleEditingFinished);
1663 }
1664
1665 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1666 {
1667 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1668 this, &DolphinView::slotRoleEditingFinished);
1669
1670 if (index < 0 || index >= m_model->count()) {
1671 return;
1672 }
1673
1674 if (role == "text") {
1675 const KFileItem oldItem = m_model->fileItem(index);
1676 const QString newName = value.toString();
1677 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1678 const QUrl oldUrl = oldItem.url();
1679
1680 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1681 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1682
1683 #ifndef Q_OS_WIN
1684 //Confirm hiding file/directory by renaming inline
1685 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1686 KGuiItem yesGuiItem(KStandardGuiItem::yes());
1687 yesGuiItem.setText(i18nc("@action:button", "Rename and Hide"));
1688
1689 const auto code = KMessageBox::questionYesNo(this,
1690 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1691 "Do you still want to rename it?")
1692 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1693 "Do you still want to rename it?"),
1694 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1695 yesGuiItem,
1696 KStandardGuiItem::cancel(),
1697 QStringLiteral("ConfirmHide")
1698 );
1699
1700 if (code == KMessageBox::No) {
1701 return;
1702 }
1703 }
1704 #endif
1705
1706 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1707 if (!newNameExistsAlready) {
1708 // Only change the data in the model if no item with the new name
1709 // is in the model yet. If there is an item with the new name
1710 // already, calling KIO::CopyJob will open a dialog
1711 // asking for a new name, and KFileItemModel will update the
1712 // data when the dir lister signals that the file name has changed.
1713 QHash<QByteArray, QVariant> data;
1714 data.insert(role, value);
1715 m_model->setData(index, data);
1716 }
1717
1718 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1719 KJobWidgets::setWindow(job, this);
1720 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1721 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1722
1723 forceUrlsSelection(newUrl, {newUrl});
1724
1725 if (!newNameExistsAlready) {
1726 // Only connect the result signal if there is no item with the new name
1727 // in the model yet, see bug 328262.
1728 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1729 }
1730 }
1731 }
1732 }
1733
1734 void DolphinView::loadDirectory(const QUrl& url, bool reload)
1735 {
1736 if (!url.isValid()) {
1737 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1738 if (location.isEmpty()) {
1739 emit errorMessage(i18nc("@info:status", "The location is empty."));
1740 } else {
1741 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1742 }
1743 return;
1744 }
1745
1746 if (reload) {
1747 m_model->refreshDirectory(url);
1748 } else {
1749 m_model->loadDirectory(url);
1750 }
1751 }
1752
1753 void DolphinView::applyViewProperties()
1754 {
1755 const ViewProperties props(viewPropertiesUrl());
1756 applyViewProperties(props);
1757 }
1758
1759 void DolphinView::applyViewProperties(const ViewProperties& props)
1760 {
1761 m_view->beginTransaction();
1762
1763 const Mode mode = props.viewMode();
1764 if (m_mode != mode) {
1765 const Mode previousMode = m_mode;
1766 m_mode = mode;
1767
1768 // Changing the mode might result in changing
1769 // the zoom level. Remember the old zoom level so
1770 // that zoomLevelChanged() can get emitted.
1771 const int oldZoomLevel = m_view->zoomLevel();
1772 applyModeToView();
1773
1774 emit modeChanged(m_mode, previousMode);
1775
1776 if (m_view->zoomLevel() != oldZoomLevel) {
1777 emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1778 }
1779 }
1780
1781 const bool hiddenFilesShown = props.hiddenFilesShown();
1782 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1783 m_model->setShowHiddenFiles(hiddenFilesShown);
1784 emit hiddenFilesShownChanged(hiddenFilesShown);
1785 }
1786
1787 const bool groupedSorting = props.groupedSorting();
1788 if (groupedSorting != m_model->groupedSorting()) {
1789 m_model->setGroupedSorting(groupedSorting);
1790 emit groupedSortingChanged(groupedSorting);
1791 }
1792
1793 const QByteArray sortRole = props.sortRole();
1794 if (sortRole != m_model->sortRole()) {
1795 m_model->setSortRole(sortRole);
1796 emit sortRoleChanged(sortRole);
1797 }
1798
1799 const Qt::SortOrder sortOrder = props.sortOrder();
1800 if (sortOrder != m_model->sortOrder()) {
1801 m_model->setSortOrder(sortOrder);
1802 emit sortOrderChanged(sortOrder);
1803 }
1804
1805 const bool sortFoldersFirst = props.sortFoldersFirst();
1806 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1807 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1808 emit sortFoldersFirstChanged(sortFoldersFirst);
1809 }
1810
1811 const QList<QByteArray> visibleRoles = props.visibleRoles();
1812 if (visibleRoles != m_visibleRoles) {
1813 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1814 m_visibleRoles = visibleRoles;
1815 m_view->setVisibleRoles(visibleRoles);
1816 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1817 }
1818
1819 const bool previewsShown = props.previewsShown();
1820 if (previewsShown != m_view->previewsShown()) {
1821 const int oldZoomLevel = zoomLevel();
1822
1823 m_view->setPreviewsShown(previewsShown);
1824 emit previewsShownChanged(previewsShown);
1825
1826 // Changing the preview-state might result in a changed zoom-level
1827 if (oldZoomLevel != zoomLevel()) {
1828 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1829 }
1830 }
1831
1832 KItemListView* itemListView = m_container->controller()->view();
1833 if (itemListView->isHeaderVisible()) {
1834 KItemListHeader* header = itemListView->header();
1835 const QList<int> headerColumnWidths = props.headerColumnWidths();
1836 const int rolesCount = m_visibleRoles.count();
1837 if (headerColumnWidths.count() == rolesCount) {
1838 header->setAutomaticColumnResizing(false);
1839
1840 QHash<QByteArray, qreal> columnWidths;
1841 for (int i = 0; i < rolesCount; ++i) {
1842 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1843 }
1844 header->setColumnWidths(columnWidths);
1845 } else {
1846 header->setAutomaticColumnResizing(true);
1847 }
1848 }
1849
1850 m_view->endTransaction();
1851 }
1852
1853 void DolphinView::applyModeToView()
1854 {
1855 switch (m_mode) {
1856 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1857 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1858 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1859 default: Q_ASSERT(false); break;
1860 }
1861 }
1862
1863 void DolphinView::pasteToUrl(const QUrl& url)
1864 {
1865 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
1866 KJobWidgets::setWindow(job, this);
1867 m_clearSelectionBeforeSelectingNewItems = true;
1868 m_markFirstNewlySelectedItemAsCurrent = true;
1869 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
1870 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotJobResult);
1871 }
1872
1873 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
1874 {
1875 QList<QUrl> urls;
1876
1877 const KFileItemList items = selectedItems();
1878 urls.reserve(items.count());
1879 foreach (const KFileItem& item, items) {
1880 urls.append(item.url());
1881 }
1882
1883 if (itemsExpandable()) {
1884 // TODO: Check if we still need KDirModel for this in KDE 5.0
1885 urls = KDirModel::simplifiedUrlList(urls);
1886 }
1887
1888 return urls;
1889 }
1890
1891 QMimeData* DolphinView::selectionMimeData() const
1892 {
1893 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1894 const KItemSet selectedIndexes = selectionManager->selectedItems();
1895
1896 return m_model->createMimeData(selectedIndexes);
1897 }
1898
1899 void DolphinView::updateWritableState()
1900 {
1901 const bool wasFolderWritable = m_isFolderWritable;
1902 m_isFolderWritable = false;
1903
1904 KFileItem item = m_model->rootItem();
1905 if (item.isNull()) {
1906 // Try to find out if the URL is writable even if the "root item" is
1907 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1908 item = KFileItem(url());
1909 item.setDelayedMimeTypes(true);
1910 }
1911
1912 KFileItemListProperties capabilities(KFileItemList() << item);
1913 m_isFolderWritable = capabilities.supportsWriting();
1914
1915 if (m_isFolderWritable != wasFolderWritable) {
1916 emit writeStateChanged(m_isFolderWritable);
1917 }
1918 }
1919
1920 QUrl DolphinView::viewPropertiesUrl() const
1921 {
1922 if (m_viewPropertiesContext.isEmpty()) {
1923 return m_url;
1924 }
1925
1926 QUrl url;
1927 url.setScheme(m_url.scheme());
1928 url.setPath(m_viewPropertiesContext);
1929 return url;
1930 }
1931
1932 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
1933 {
1934 forceUrlsSelection(urls.first(), urls);
1935 }
1936
1937 void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
1938 {
1939 clearSelection();
1940 m_clearSelectionBeforeSelectingNewItems = true;
1941 markUrlAsCurrent(current);
1942 markUrlsAsSelected(selected);
1943 }
1944
1945 void DolphinView::copyPathToClipboard()
1946 {
1947 const KFileItemList list = selectedItems();
1948 if (list.isEmpty()) {
1949 return;
1950 }
1951 const KFileItem& item = list.at(0);
1952 QString path = item.localPath();
1953 if (path.isEmpty()) {
1954 path = item.url().toDisplayString();
1955 }
1956 QClipboard* clipboard = QApplication::clipboard();
1957 if (clipboard == nullptr) {
1958 return;
1959 }
1960 clipboard->setText(path);
1961 }
1962
1963 void DolphinView::slotIncreaseZoom()
1964 {
1965 setZoomLevel(zoomLevel() + 1);
1966 }
1967
1968 void DolphinView::slotDecreaseZoom()
1969 {
1970 setZoomLevel(zoomLevel() - 1);
1971 }
1972
1973 void DolphinView::slotSwipeUp()
1974 {
1975 emit goUpRequested();
1976 }