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