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