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