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