]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
[DolphinView] Use correct color group
[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->setMargin(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, &DolphinView::hideToolTip);
132 connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, &DolphinView::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->show();
643 dialog->raise();
644 dialog->activateWindow();
645 }
646
647 // Assure that the current index remains visible when KFileItemModel
648 // will notify the view about changed items (which might result in
649 // a changed sorting).
650 m_assureVisibleCurrentIndex = true;
651 }
652
653 void DolphinView::trashSelectedItems()
654 {
655 const QList<QUrl> list = simplifiedSelectedUrls();
656 KIO::JobUiDelegate uiDelegate;
657 uiDelegate.setWindow(window());
658 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) {
659 KIO::Job* job = KIO::trash(list);
660 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job);
661 KJobWidgets::setWindow(job, this);
662 connect(job, &KIO::Job::result,
663 this, &DolphinView::slotTrashFileFinished);
664 }
665 }
666
667 void DolphinView::deleteSelectedItems()
668 {
669 const QList<QUrl> list = simplifiedSelectedUrls();
670
671 KIO::JobUiDelegate uiDelegate;
672 uiDelegate.setWindow(window());
673 if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) {
674 KIO::Job* job = KIO::del(list);
675 KJobWidgets::setWindow(job, this);
676 connect(job, &KIO::Job::result,
677 this, &DolphinView::slotDeleteFileFinished);
678 }
679 }
680
681 void DolphinView::cutSelectedItems()
682 {
683 QMimeData* mimeData = selectionMimeData();
684 KIO::setClipboardDataCut(mimeData, true);
685 QApplication::clipboard()->setMimeData(mimeData);
686 }
687
688 void DolphinView::copySelectedItems()
689 {
690 QMimeData* mimeData = selectionMimeData();
691 QApplication::clipboard()->setMimeData(mimeData);
692 }
693
694 void DolphinView::paste()
695 {
696 pasteToUrl(url());
697 }
698
699 void DolphinView::pasteIntoFolder()
700 {
701 const KFileItemList items = selectedItems();
702 if ((items.count() == 1) && items.first().isDir()) {
703 pasteToUrl(items.first().url());
704 }
705 }
706
707 void DolphinView::stopLoading()
708 {
709 m_model->cancelDirectoryLoading();
710 }
711
712 void DolphinView::updatePalette()
713 {
714 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
715 if (!m_active) {
716 color.setAlpha(150);
717 }
718
719 QWidget* viewport = m_container->viewport();
720 if (viewport) {
721 QPalette palette;
722 palette.setColor(viewport->backgroundRole(), color);
723 viewport->setPalette(palette);
724 }
725
726 update();
727 }
728
729 void DolphinView::abortTwoClicksRenaming()
730 {
731 m_twoClicksRenamingItemUrl.clear();
732 m_twoClicksRenamingTimer->stop();
733 }
734
735 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
736 {
737 switch (event->type()) {
738 case QEvent::PaletteChange:
739 updatePalette();
740 QPixmapCache::clear();
741 break;
742
743 case QEvent::WindowActivate:
744 case QEvent::WindowDeactivate:
745 updatePalette();
746 break;
747
748 case QEvent::KeyPress:
749 if (GeneralSettings::useTabForSwitchingSplitView()) {
750 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
751 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
752 emit toggleActiveViewRequested();
753 return true;
754 }
755 }
756 break;
757 case QEvent::FocusIn:
758 if (watched == m_container) {
759 setActive(true);
760 }
761 break;
762
763 case QEvent::GraphicsSceneDragEnter:
764 if (watched == m_view) {
765 m_dragging = true;
766 abortTwoClicksRenaming();
767 }
768 break;
769
770 case QEvent::GraphicsSceneDragLeave:
771 if (watched == m_view) {
772 m_dragging = false;
773 }
774 break;
775
776 case QEvent::GraphicsSceneDrop:
777 if (watched == m_view) {
778 m_dragging = false;
779 }
780 default:
781 break;
782 }
783
784 return QWidget::eventFilter(watched, event);
785 }
786
787 void DolphinView::wheelEvent(QWheelEvent* event)
788 {
789 if (event->modifiers().testFlag(Qt::ControlModifier)) {
790 const int numDegrees = event->delta() / 8;
791 const int numSteps = numDegrees / 15;
792
793 setZoomLevel(zoomLevel() + numSteps);
794 event->accept();
795 } else {
796 event->ignore();
797 }
798 }
799
800 void DolphinView::hideEvent(QHideEvent* event)
801 {
802 hideToolTip();
803 QWidget::hideEvent(event);
804 }
805
806 bool DolphinView::event(QEvent* event)
807 {
808 if (event->type() == QEvent::WindowDeactivate) {
809 /* See Bug 297355
810 * Dolphin leaves file preview tooltips open even when is not visible.
811 *
812 * Hide tool-tip when Dolphin loses focus.
813 */
814 hideToolTip();
815 abortTwoClicksRenaming();
816 }
817
818 return QWidget::event(event);
819 }
820
821 void DolphinView::activate()
822 {
823 setActive(true);
824 }
825
826 void DolphinView::slotItemActivated(int index)
827 {
828 abortTwoClicksRenaming();
829
830 const KFileItem item = m_model->fileItem(index);
831 if (!item.isNull()) {
832 emit itemActivated(item);
833 }
834 }
835
836 void DolphinView::slotItemsActivated(const KItemSet& indexes)
837 {
838 Q_ASSERT(indexes.count() >= 2);
839
840 abortTwoClicksRenaming();
841
842 if (indexes.count() > 5) {
843 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
844 const int answer = KMessageBox::warningYesNo(this, question);
845 if (answer != KMessageBox::Yes) {
846 return;
847 }
848 }
849
850 KFileItemList items;
851 items.reserve(indexes.count());
852
853 for (int index : indexes) {
854 KFileItem item = m_model->fileItem(index);
855 const QUrl& url = openItemAsFolderUrl(item);
856
857 if (!url.isEmpty()) { // Open folders in new tabs
858 emit tabRequested(url);
859 } else {
860 items.append(item);
861 }
862 }
863
864 if (items.count() == 1) {
865 emit itemActivated(items.first());
866 } else if (items.count() > 1) {
867 emit itemsActivated(items);
868 }
869 }
870
871 void DolphinView::slotItemMiddleClicked(int index)
872 {
873 const KFileItem& item = m_model->fileItem(index);
874 const QUrl& url = openItemAsFolderUrl(item);
875 if (!url.isEmpty()) {
876 emit tabRequested(url);
877 } else if (isTabsForFilesEnabled()) {
878 emit tabRequested(item.url());
879 }
880 }
881
882 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
883 {
884 // Force emit of a selection changed signal before we request the
885 // context menu, to update the edit-actions first. (See Bug 294013)
886 if (m_selectionChangedTimer->isActive()) {
887 emitSelectionChangedSignal();
888 }
889
890 const KFileItem item = m_model->fileItem(index);
891 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
892 }
893
894 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
895 {
896 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
897 }
898
899 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
900 {
901 ViewProperties props(viewPropertiesUrl());
902
903 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
904
905 KItemListView* view = m_container->controller()->view();
906 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
907
908 bool indexingEnabled = false;
909 #ifdef HAVE_BALOO
910 Baloo::IndexerConfig config;
911 indexingEnabled = config.fileIndexingEnabled();
912 #endif
913
914 QString groupName;
915 QMenu* groupMenu = nullptr;
916
917 // Add all roles to the menu that can be shown or hidden by the user
918 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
919 foreach (const KFileItemModel::RoleInfo& info, rolesInfo) {
920 if (info.role == "text") {
921 // It should not be possible to hide the "text" role
922 continue;
923 }
924
925 const QString text = m_model->roleDescription(info.role);
926 QAction* action = nullptr;
927 if (info.group.isEmpty()) {
928 action = menu->addAction(text);
929 } else {
930 if (!groupMenu || info.group != groupName) {
931 groupName = info.group;
932 groupMenu = menu->addMenu(groupName);
933 }
934
935 action = groupMenu->addAction(text);
936 }
937
938 action->setCheckable(true);
939 action->setChecked(visibleRolesSet.contains(info.role));
940 action->setData(info.role);
941
942 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
943 (info.requiresBaloo) ||
944 (info.requiresIndexer && indexingEnabled);
945 action->setEnabled(enable);
946 }
947
948 menu->addSeparator();
949
950 QActionGroup* widthsGroup = new QActionGroup(menu);
951 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
952
953 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
954 autoAdjustWidthsAction->setCheckable(true);
955 autoAdjustWidthsAction->setChecked(autoColumnWidths);
956 autoAdjustWidthsAction->setActionGroup(widthsGroup);
957
958 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
959 customWidthsAction->setCheckable(true);
960 customWidthsAction->setChecked(!autoColumnWidths);
961 customWidthsAction->setActionGroup(widthsGroup);
962
963 QAction* action = menu->exec(pos.toPoint());
964 if (menu && action) {
965 KItemListHeader* header = view->header();
966
967 if (action == autoAdjustWidthsAction) {
968 // Clear the column-widths from the viewproperties and turn on
969 // the automatic resizing of the columns
970 props.setHeaderColumnWidths(QList<int>());
971 header->setAutomaticColumnResizing(true);
972 } else if (action == customWidthsAction) {
973 // Apply the current column-widths as custom column-widths and turn
974 // off the automatic resizing of the columns
975 QList<int> columnWidths;
976 columnWidths.reserve(view->visibleRoles().count());
977 foreach (const QByteArray& role, view->visibleRoles()) {
978 columnWidths.append(header->columnWidth(role));
979 }
980 props.setHeaderColumnWidths(columnWidths);
981 header->setAutomaticColumnResizing(false);
982 } else {
983 // Show or hide the selected role
984 const QByteArray selectedRole = action->data().toByteArray();
985
986 QList<QByteArray> visibleRoles = view->visibleRoles();
987 if (action->isChecked()) {
988 visibleRoles.append(selectedRole);
989 } else {
990 visibleRoles.removeOne(selectedRole);
991 }
992
993 view->setVisibleRoles(visibleRoles);
994 props.setVisibleRoles(visibleRoles);
995
996 QList<int> columnWidths;
997 if (!header->automaticColumnResizing()) {
998 columnWidths.reserve(view->visibleRoles().count());
999 foreach (const QByteArray& role, view->visibleRoles()) {
1000 columnWidths.append(header->columnWidth(role));
1001 }
1002 }
1003 props.setHeaderColumnWidths(columnWidths);
1004 }
1005 }
1006
1007 delete menu;
1008 }
1009
1010 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1011 {
1012 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1013
1014 ViewProperties props(viewPropertiesUrl());
1015 QList<int> columnWidths = props.headerColumnWidths();
1016 if (columnWidths.count() != visibleRoles.count()) {
1017 columnWidths.clear();
1018 columnWidths.reserve(visibleRoles.count());
1019 const KItemListHeader* header = m_view->header();
1020 foreach (const QByteArray& role, visibleRoles) {
1021 const int width = header->columnWidth(role);
1022 columnWidths.append(width);
1023 }
1024 }
1025
1026 const int roleIndex = visibleRoles.indexOf(role);
1027 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1028 columnWidths[roleIndex] = current;
1029
1030 props.setHeaderColumnWidths(columnWidths);
1031 }
1032
1033 void DolphinView::slotItemHovered(int index)
1034 {
1035 const KFileItem item = m_model->fileItem(index);
1036
1037 if (GeneralSettings::showToolTips() && !m_dragging) {
1038 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1039 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1040 itemRect.moveTo(pos);
1041
1042 #ifdef HAVE_BALOO
1043 m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle());
1044 #endif
1045 }
1046
1047 emit requestItemInfo(item);
1048 }
1049
1050 void DolphinView::slotItemUnhovered(int index)
1051 {
1052 Q_UNUSED(index);
1053 hideToolTip();
1054 emit requestItemInfo(KFileItem());
1055 }
1056
1057 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1058 {
1059 QUrl destUrl;
1060 KFileItem destItem = m_model->fileItem(index);
1061 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1062 // Use the URL of the view as drop target if the item is no directory
1063 // or desktop-file
1064 destItem = m_model->rootItem();
1065 destUrl = url();
1066 } else {
1067 // The item represents a directory or desktop-file
1068 destUrl = destItem.mostLocalUrl();
1069 }
1070
1071 QDropEvent dropEvent(event->pos().toPoint(),
1072 event->possibleActions(),
1073 event->mimeData(),
1074 event->buttons(),
1075 event->modifiers());
1076 dropUrls(destUrl, &dropEvent, this);
1077
1078 setActive(true);
1079 }
1080
1081 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1082 {
1083 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1084
1085 if (job) {
1086 connect(job, &KIO::DropJob::result, this, &DolphinView::slotPasteJobResult);
1087
1088 if (destUrl == url()) {
1089 // Mark the dropped urls as selected.
1090 m_clearSelectionBeforeSelectingNewItems = true;
1091 m_markFirstNewlySelectedItemAsCurrent = true;
1092 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1093 }
1094 }
1095 }
1096
1097 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1098 {
1099 if (previous != nullptr) {
1100 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1101 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1102 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1103 m_versionControlObserver->setModel(nullptr);
1104 }
1105
1106 if (current) {
1107 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1108 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1109 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1110 m_versionControlObserver->setModel(fileItemModel);
1111 }
1112 }
1113
1114 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1115 {
1116 Q_UNUSED(itemIndex);
1117
1118 hideToolTip();
1119
1120 if (buttons & Qt::BackButton) {
1121 emit goBackRequested();
1122 } else if (buttons & Qt::ForwardButton) {
1123 emit goForwardRequested();
1124 }
1125 }
1126
1127 void DolphinView::slotSelectedItemTextPressed(int index)
1128 {
1129 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1130 const KFileItem item = m_model->fileItem(index);
1131 const KFileItemListProperties capabilities(KFileItemList() << item);
1132 if (capabilities.supportsMoving()) {
1133 m_twoClicksRenamingItemUrl = item.url();
1134 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1135 }
1136 }
1137 }
1138
1139 void DolphinView::slotItemCreated(const QUrl& url)
1140 {
1141 if (m_markFirstNewlySelectedItemAsCurrent) {
1142 markUrlAsCurrent(url);
1143 m_markFirstNewlySelectedItemAsCurrent = false;
1144 }
1145 m_selectedUrls << url;
1146 }
1147
1148 void DolphinView::slotPasteJobResult(KJob *job)
1149 {
1150 if (job->error()) {
1151 emit errorMessage(job->errorString());
1152 }
1153 if (!m_selectedUrls.isEmpty()) {
1154 m_selectedUrls << KDirModel::simplifiedUrlList(m_selectedUrls);
1155 }
1156 }
1157
1158 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1159 {
1160 const int currentCount = current.count();
1161 const int previousCount = previous.count();
1162 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1163 (currentCount > 0 && previousCount == 0);
1164
1165 // If nothing has been selected before and something got selected (or if something
1166 // was selected before and now nothing is selected) the selectionChangedSignal must
1167 // be emitted asynchronously as fast as possible to update the edit-actions.
1168 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1169 m_selectionChangedTimer->start();
1170 }
1171
1172 void DolphinView::emitSelectionChangedSignal()
1173 {
1174 m_selectionChangedTimer->stop();
1175 emit selectionChanged(selectedItems());
1176 }
1177
1178 void DolphinView::updateSortRole(const QByteArray& role)
1179 {
1180 ViewProperties props(viewPropertiesUrl());
1181 props.setSortRole(role);
1182
1183 KItemModelBase* model = m_container->controller()->model();
1184 model->setSortRole(role);
1185
1186 emit sortRoleChanged(role);
1187 }
1188
1189 void DolphinView::updateSortOrder(Qt::SortOrder order)
1190 {
1191 ViewProperties props(viewPropertiesUrl());
1192 props.setSortOrder(order);
1193
1194 m_model->setSortOrder(order);
1195
1196 emit sortOrderChanged(order);
1197 }
1198
1199 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1200 {
1201 ViewProperties props(viewPropertiesUrl());
1202 props.setSortFoldersFirst(foldersFirst);
1203
1204 m_model->setSortDirectoriesFirst(foldersFirst);
1205
1206 emit sortFoldersFirstChanged(foldersFirst);
1207 }
1208
1209 QPair<bool, QString> DolphinView::pasteInfo() const
1210 {
1211 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1212 QPair<bool, QString> info;
1213 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1214 return info;
1215 }
1216
1217 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1218 {
1219 m_tabsForFiles = tabsForFiles;
1220 }
1221
1222 bool DolphinView::isTabsForFilesEnabled() const
1223 {
1224 return m_tabsForFiles;
1225 }
1226
1227 bool DolphinView::itemsExpandable() const
1228 {
1229 return m_mode == DetailsView;
1230 }
1231
1232 void DolphinView::restoreState(QDataStream& stream)
1233 {
1234 // Read the version number of the view state and check if the version is supported.
1235 quint32 version = 0;
1236 stream >> version;
1237 if (version != 1) {
1238 // The version of the view state isn't supported, we can't restore it.
1239 return;
1240 }
1241
1242 // Restore the current item that had the keyboard focus
1243 stream >> m_currentItemUrl;
1244
1245 // Restore the previously selected items
1246 stream >> m_selectedUrls;
1247
1248 // Restore the view position
1249 stream >> m_restoredContentsPosition;
1250
1251 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1252 QSet<QUrl> urls;
1253 stream >> urls;
1254 m_model->restoreExpandedDirectories(urls);
1255 }
1256
1257 void DolphinView::saveState(QDataStream& stream)
1258 {
1259 stream << quint32(1); // View state version
1260
1261 // Save the current item that has the keyboard focus
1262 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1263 if (currentIndex != -1) {
1264 KFileItem item = m_model->fileItem(currentIndex);
1265 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1266 QUrl currentItemUrl = item.url();
1267 stream << currentItemUrl;
1268 } else {
1269 stream << QUrl();
1270 }
1271
1272 // Save the selected urls
1273 stream << selectedItems().urlList();
1274
1275 // Save view position
1276 const qreal x = m_container->horizontalScrollBar()->value();
1277 const qreal y = m_container->verticalScrollBar()->value();
1278 stream << QPoint(x, y);
1279
1280 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1281 stream << m_model->expandedDirectories();
1282 }
1283
1284 KFileItem DolphinView::rootItem() const
1285 {
1286 return m_model->rootItem();
1287 }
1288
1289 void DolphinView::setViewPropertiesContext(const QString& context)
1290 {
1291 m_viewPropertiesContext = context;
1292 }
1293
1294 QString DolphinView::viewPropertiesContext() const
1295 {
1296 return m_viewPropertiesContext;
1297 }
1298
1299 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1300 {
1301 if (item.isNull()) {
1302 return QUrl();
1303 }
1304
1305 QUrl url = item.targetUrl();
1306
1307 if (item.isDir()) {
1308 return url;
1309 }
1310
1311 if (item.isMimeTypeKnown()) {
1312 const QString& mimetype = item.mimetype();
1313
1314 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1315 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1316 // zip:/<path>/ when clicking on a zip file, etc.
1317 // The .protocol file specifies the mimetype that the kioslave handles.
1318 // Note that we don't use mimetype inheritance since we don't want to
1319 // open OpenDocument files as zip folders...
1320 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1321 if (!protocol.isEmpty()) {
1322 url.setScheme(protocol);
1323 return url;
1324 }
1325 }
1326
1327 if (mimetype == QLatin1String("application/x-desktop")) {
1328 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1329 KDesktopFile desktopFile(url.toLocalFile());
1330 if (desktopFile.hasLinkType()) {
1331 const QString linkUrl = desktopFile.readUrl();
1332 if (!linkUrl.startsWith(QLatin1String("http"))) {
1333 return QUrl::fromUserInput(linkUrl);
1334 }
1335 }
1336 }
1337 }
1338
1339 return QUrl();
1340 }
1341
1342 void DolphinView::observeCreatedItem(const QUrl& url)
1343 {
1344 if (m_active) {
1345 forceUrlsSelection(url, {url});
1346 }
1347 }
1348
1349 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1350 {
1351 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1352 emit redirection(oldUrl, newUrl);
1353 m_url = newUrl; // #186947
1354 }
1355 }
1356
1357 void DolphinView::updateViewState()
1358 {
1359 if (m_currentItemUrl != QUrl()) {
1360 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1361
1362 // if there is a selection already, leave it that way
1363 if (!selectionManager->hasSelection()) {
1364 const int currentIndex = m_model->index(m_currentItemUrl);
1365 if (currentIndex != -1) {
1366 selectionManager->setCurrentItem(currentIndex);
1367
1368 // scroll to current item and reset the state
1369 if (m_scrollToCurrentItem) {
1370 m_view->scrollToItem(currentIndex);
1371 m_scrollToCurrentItem = false;
1372 }
1373 } else {
1374 selectionManager->setCurrentItem(0);
1375 }
1376 }
1377
1378 m_currentItemUrl = QUrl();
1379 }
1380
1381 if (!m_restoredContentsPosition.isNull()) {
1382 const int x = m_restoredContentsPosition.x();
1383 const int y = m_restoredContentsPosition.y();
1384 m_restoredContentsPosition = QPoint();
1385
1386 m_container->horizontalScrollBar()->setValue(x);
1387 m_container->verticalScrollBar()->setValue(y);
1388 }
1389
1390 if (!m_selectedUrls.isEmpty()) {
1391 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1392
1393 // if there is a selection already, leave it that way
1394 if (!selectionManager->hasSelection()) {
1395 if (m_clearSelectionBeforeSelectingNewItems) {
1396 selectionManager->clearSelection();
1397 m_clearSelectionBeforeSelectingNewItems = false;
1398 }
1399
1400 KItemSet selectedItems = selectionManager->selectedItems();
1401
1402 QList<QUrl>::iterator it = m_selectedUrls.begin();
1403 while (it != m_selectedUrls.end()) {
1404 const int index = m_model->index(*it);
1405 if (index >= 0) {
1406 selectedItems.insert(index);
1407 it = m_selectedUrls.erase(it);
1408 } else {
1409 ++it;
1410 }
1411 }
1412
1413 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1414 selectionManager->setSelectedItems(selectedItems);
1415 }
1416 }
1417 }
1418
1419 void DolphinView::hideToolTip()
1420 {
1421 #ifdef HAVE_BALOO
1422 if (GeneralSettings::showToolTips()) {
1423 m_toolTipManager->hideToolTip();
1424 }
1425 #endif
1426 }
1427
1428 void DolphinView::calculateItemCount(int& fileCount,
1429 int& folderCount,
1430 KIO::filesize_t& totalFileSize) const
1431 {
1432 const int itemCount = m_model->count();
1433 for (int i = 0; i < itemCount; ++i) {
1434 const KFileItem item = m_model->fileItem(i);
1435 if (item.isDir()) {
1436 ++folderCount;
1437 } else {
1438 ++fileCount;
1439 totalFileSize += item.size();
1440 }
1441 }
1442 }
1443
1444 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1445 {
1446 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1447
1448 // verify that only one item is selected
1449 if (selectionManager->selectedItems().count() == 1) {
1450 const int index = selectionManager->currentItem();
1451 const QUrl fileItemUrl = m_model->fileItem(index).url();
1452
1453 // check if the selected item was the same item that started the twoClicksRenaming
1454 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1455 renameSelectedItems();
1456 }
1457 }
1458 }
1459
1460 void DolphinView::slotTrashFileFinished(KJob* job)
1461 {
1462 if (job->error() == 0) {
1463 emit operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1464 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1465 emit errorMessage(job->errorString());
1466 }
1467 }
1468
1469 void DolphinView::slotDeleteFileFinished(KJob* job)
1470 {
1471 if (job->error() == 0) {
1472 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1473 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1474 emit errorMessage(job->errorString());
1475 }
1476 }
1477
1478 void DolphinView::slotRenamingResult(KJob* job)
1479 {
1480 if (job->error()) {
1481 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1482 Q_ASSERT(copyJob);
1483 const QUrl newUrl = copyJob->destUrl();
1484 const int index = m_model->index(newUrl);
1485 if (index >= 0) {
1486 QHash<QByteArray, QVariant> data;
1487 const QUrl oldUrl = copyJob->srcUrls().at(0);
1488 data.insert("text", oldUrl.fileName());
1489 m_model->setData(index, data);
1490 }
1491 }
1492 }
1493
1494 void DolphinView::slotDirectoryLoadingStarted()
1495 {
1496 // Disable the writestate temporary until it can be determined in a fast way
1497 // in DolphinView::slotDirectoryLoadingCompleted()
1498 if (m_isFolderWritable) {
1499 m_isFolderWritable = false;
1500 emit writeStateChanged(m_isFolderWritable);
1501 }
1502
1503 emit directoryLoadingStarted();
1504 }
1505
1506 void DolphinView::slotDirectoryLoadingCompleted()
1507 {
1508 // Update the view-state. This has to be done asynchronously
1509 // because the view might not be in its final state yet.
1510 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1511
1512 emit directoryLoadingCompleted();
1513
1514 updateWritableState();
1515 }
1516
1517 void DolphinView::slotItemsChanged()
1518 {
1519 m_assureVisibleCurrentIndex = false;
1520 }
1521
1522 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1523 {
1524 Q_UNUSED(previous);
1525 Q_ASSERT(m_model->sortOrder() == current);
1526
1527 ViewProperties props(viewPropertiesUrl());
1528 props.setSortOrder(current);
1529
1530 emit sortOrderChanged(current);
1531 }
1532
1533 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1534 {
1535 Q_UNUSED(previous);
1536 Q_ASSERT(m_model->sortRole() == current);
1537
1538 ViewProperties props(viewPropertiesUrl());
1539 props.setSortRole(current);
1540
1541 emit sortRoleChanged(current);
1542 }
1543
1544 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1545 const QList<QByteArray>& previous)
1546 {
1547 Q_UNUSED(previous);
1548 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1549
1550 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1551
1552 m_visibleRoles = current;
1553
1554 ViewProperties props(viewPropertiesUrl());
1555 props.setVisibleRoles(m_visibleRoles);
1556
1557 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1558 }
1559
1560 void DolphinView::slotRoleEditingCanceled()
1561 {
1562 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1563 this, &DolphinView::slotRoleEditingFinished);
1564 }
1565
1566 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1567 {
1568 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1569 this, &DolphinView::slotRoleEditingFinished);
1570
1571 if (index < 0 || index >= m_model->count()) {
1572 return;
1573 }
1574
1575 if (role == "text") {
1576 const KFileItem oldItem = m_model->fileItem(index);
1577 const QString newName = value.toString();
1578 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1579 const QUrl oldUrl = oldItem.url();
1580
1581 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1582 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1583
1584 #ifndef Q_OS_WIN
1585 //Confirm hiding file/directory by renaming inline
1586 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1587 KGuiItem yesGuiItem(KStandardGuiItem::yes());
1588 yesGuiItem.setText(i18nc("@action:button", "Rename and Hide"));
1589
1590 const auto code = KMessageBox::questionYesNo(this,
1591 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1592 "Do you still want to rename it?")
1593 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1594 "Do you still want to rename it?"),
1595 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1596 yesGuiItem,
1597 KStandardGuiItem::cancel(),
1598 QStringLiteral("ConfirmHide")
1599 );
1600
1601 if (code == KMessageBox::No) {
1602 return;
1603 }
1604 }
1605 #endif
1606
1607 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1608 if (!newNameExistsAlready) {
1609 // Only change the data in the model if no item with the new name
1610 // is in the model yet. If there is an item with the new name
1611 // already, calling KIO::CopyJob will open a dialog
1612 // asking for a new name, and KFileItemModel will update the
1613 // data when the dir lister signals that the file name has changed.
1614 QHash<QByteArray, QVariant> data;
1615 data.insert(role, value);
1616 m_model->setData(index, data);
1617 }
1618
1619 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1620 KJobWidgets::setWindow(job, this);
1621 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1622 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1623
1624 forceUrlsSelection(newUrl, {newUrl});
1625
1626 if (!newNameExistsAlready) {
1627 // Only connect the result signal if there is no item with the new name
1628 // in the model yet, see bug 328262.
1629 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1630 }
1631 }
1632 }
1633 }
1634
1635 void DolphinView::loadDirectory(const QUrl& url, bool reload)
1636 {
1637 if (!url.isValid()) {
1638 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1639 if (location.isEmpty()) {
1640 emit errorMessage(i18nc("@info:status", "The location is empty."));
1641 } else {
1642 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1643 }
1644 return;
1645 }
1646
1647 if (reload) {
1648 m_model->refreshDirectory(url);
1649 } else {
1650 m_model->loadDirectory(url);
1651 }
1652 }
1653
1654 void DolphinView::applyViewProperties()
1655 {
1656 const ViewProperties props(viewPropertiesUrl());
1657 applyViewProperties(props);
1658 }
1659
1660 void DolphinView::applyViewProperties(const ViewProperties& props)
1661 {
1662 m_view->beginTransaction();
1663
1664 const Mode mode = props.viewMode();
1665 if (m_mode != mode) {
1666 const Mode previousMode = m_mode;
1667 m_mode = mode;
1668
1669 // Changing the mode might result in changing
1670 // the zoom level. Remember the old zoom level so
1671 // that zoomLevelChanged() can get emitted.
1672 const int oldZoomLevel = m_view->zoomLevel();
1673 applyModeToView();
1674
1675 emit modeChanged(m_mode, previousMode);
1676
1677 if (m_view->zoomLevel() != oldZoomLevel) {
1678 emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1679 }
1680 }
1681
1682 const bool hiddenFilesShown = props.hiddenFilesShown();
1683 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1684 m_model->setShowHiddenFiles(hiddenFilesShown);
1685 emit hiddenFilesShownChanged(hiddenFilesShown);
1686 }
1687
1688 const bool groupedSorting = props.groupedSorting();
1689 if (groupedSorting != m_model->groupedSorting()) {
1690 m_model->setGroupedSorting(groupedSorting);
1691 emit groupedSortingChanged(groupedSorting);
1692 }
1693
1694 const QByteArray sortRole = props.sortRole();
1695 if (sortRole != m_model->sortRole()) {
1696 m_model->setSortRole(sortRole);
1697 emit sortRoleChanged(sortRole);
1698 }
1699
1700 const Qt::SortOrder sortOrder = props.sortOrder();
1701 if (sortOrder != m_model->sortOrder()) {
1702 m_model->setSortOrder(sortOrder);
1703 emit sortOrderChanged(sortOrder);
1704 }
1705
1706 const bool sortFoldersFirst = props.sortFoldersFirst();
1707 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1708 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1709 emit sortFoldersFirstChanged(sortFoldersFirst);
1710 }
1711
1712 const QList<QByteArray> visibleRoles = props.visibleRoles();
1713 if (visibleRoles != m_visibleRoles) {
1714 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1715 m_visibleRoles = visibleRoles;
1716 m_view->setVisibleRoles(visibleRoles);
1717 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1718 }
1719
1720 const bool previewsShown = props.previewsShown();
1721 if (previewsShown != m_view->previewsShown()) {
1722 const int oldZoomLevel = zoomLevel();
1723
1724 m_view->setPreviewsShown(previewsShown);
1725 emit previewsShownChanged(previewsShown);
1726
1727 // Changing the preview-state might result in a changed zoom-level
1728 if (oldZoomLevel != zoomLevel()) {
1729 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1730 }
1731 }
1732
1733 KItemListView* itemListView = m_container->controller()->view();
1734 if (itemListView->isHeaderVisible()) {
1735 KItemListHeader* header = itemListView->header();
1736 const QList<int> headerColumnWidths = props.headerColumnWidths();
1737 const int rolesCount = m_visibleRoles.count();
1738 if (headerColumnWidths.count() == rolesCount) {
1739 header->setAutomaticColumnResizing(false);
1740
1741 QHash<QByteArray, qreal> columnWidths;
1742 for (int i = 0; i < rolesCount; ++i) {
1743 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1744 }
1745 header->setColumnWidths(columnWidths);
1746 } else {
1747 header->setAutomaticColumnResizing(true);
1748 }
1749 }
1750
1751 m_view->endTransaction();
1752 }
1753
1754 void DolphinView::applyModeToView()
1755 {
1756 switch (m_mode) {
1757 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1758 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1759 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1760 default: Q_ASSERT(false); break;
1761 }
1762 }
1763
1764 void DolphinView::pasteToUrl(const QUrl& url)
1765 {
1766 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
1767 KJobWidgets::setWindow(job, this);
1768 m_clearSelectionBeforeSelectingNewItems = true;
1769 m_markFirstNewlySelectedItemAsCurrent = true;
1770 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
1771 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotPasteJobResult);
1772 }
1773
1774 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
1775 {
1776 QList<QUrl> urls;
1777
1778 const KFileItemList items = selectedItems();
1779 urls.reserve(items.count());
1780 foreach (const KFileItem& item, items) {
1781 urls.append(item.url());
1782 }
1783
1784 if (itemsExpandable()) {
1785 // TODO: Check if we still need KDirModel for this in KDE 5.0
1786 urls = KDirModel::simplifiedUrlList(urls);
1787 }
1788
1789 return urls;
1790 }
1791
1792 QMimeData* DolphinView::selectionMimeData() const
1793 {
1794 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1795 const KItemSet selectedIndexes = selectionManager->selectedItems();
1796
1797 return m_model->createMimeData(selectedIndexes);
1798 }
1799
1800 void DolphinView::updateWritableState()
1801 {
1802 const bool wasFolderWritable = m_isFolderWritable;
1803 m_isFolderWritable = false;
1804
1805 KFileItem item = m_model->rootItem();
1806 if (item.isNull()) {
1807 // Try to find out if the URL is writable even if the "root item" is
1808 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1809 item = KFileItem(url());
1810 item.setDelayedMimeTypes(true);
1811 }
1812
1813 KFileItemListProperties capabilities(KFileItemList() << item);
1814 m_isFolderWritable = capabilities.supportsWriting();
1815
1816 if (m_isFolderWritable != wasFolderWritable) {
1817 emit writeStateChanged(m_isFolderWritable);
1818 }
1819 }
1820
1821 QUrl DolphinView::viewPropertiesUrl() const
1822 {
1823 if (m_viewPropertiesContext.isEmpty()) {
1824 return m_url;
1825 }
1826
1827 QUrl url;
1828 url.setScheme(m_url.scheme());
1829 url.setPath(m_viewPropertiesContext);
1830 return url;
1831 }
1832
1833 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
1834 {
1835 forceUrlsSelection(urls.first(), urls);
1836 }
1837
1838 void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
1839 {
1840 clearSelection();
1841 m_clearSelectionBeforeSelectingNewItems = true;
1842 markUrlAsCurrent(current);
1843 markUrlsAsSelected(selected);
1844 }