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