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