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