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