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