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