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