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