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