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