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