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