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