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