]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Add Duplicate feature
[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 originalFileName = item.name();
723 QString extension = db.suffixForFileName(originalFileName);
724
725 QUrl duplicateURL = originalURL;
726
727 // No extension; new filename is "<oldfilename> copy"
728 if (extension.isEmpty()) {
729 duplicateURL.setPath(i18nc("<file path> copy", "%1 copy", originalURL.path()));
730 // There's an extension; new filename is "<oldfilename> copy.<extension>"
731 } else {
732 // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it
733 extension = QLatin1String(".") + extension;
734 const QString directoryPath = originalURL.adjusted(QUrl::RemoveFilename).path();
735 const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size());
736 // Preserve file's original filename extension in case the casing differs
737 // from what QMimeDatabase::suffixForFileName() returned
738 const QString originalExtension = originalFileName.right(extension.size());
739 duplicateURL.setPath(i18nc("<file path><filename> copy.<extension>", "%1%2 copy%3", directoryPath, originalFilenameWithoutExtension, originalExtension));
740 }
741
742 KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL, KIO::HideProgressInfo);
743 KJobWidgets::setWindow(job, this);
744
745 if (job) {
746 newSelection << duplicateURL;
747 KIO::FileUndoManager::self()->recordCopyJob(job);
748 }
749 }
750 }
751
752 void DolphinView::stopLoading()
753 {
754 m_model->cancelDirectoryLoading();
755 }
756
757 void DolphinView::updatePalette()
758 {
759 QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color();
760 if (!m_active) {
761 color.setAlpha(150);
762 }
763
764 QWidget* viewport = m_container->viewport();
765 if (viewport) {
766 QPalette palette;
767 palette.setColor(viewport->backgroundRole(), color);
768 viewport->setPalette(palette);
769 }
770
771 update();
772 }
773
774 void DolphinView::abortTwoClicksRenaming()
775 {
776 m_twoClicksRenamingItemUrl.clear();
777 m_twoClicksRenamingTimer->stop();
778 }
779
780 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
781 {
782 switch (event->type()) {
783 case QEvent::PaletteChange:
784 updatePalette();
785 QPixmapCache::clear();
786 break;
787
788 case QEvent::WindowActivate:
789 case QEvent::WindowDeactivate:
790 updatePalette();
791 break;
792
793 case QEvent::KeyPress:
794 hideToolTip(ToolTipManager::HideBehavior::Instantly);
795 if (GeneralSettings::useTabForSwitchingSplitView()) {
796 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
797 if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) {
798 emit toggleActiveViewRequested();
799 return true;
800 }
801 }
802 break;
803 case QEvent::FocusIn:
804 if (watched == m_container) {
805 setActive(true);
806 }
807 break;
808
809 case QEvent::GraphicsSceneDragEnter:
810 if (watched == m_view) {
811 m_dragging = true;
812 abortTwoClicksRenaming();
813 }
814 break;
815
816 case QEvent::GraphicsSceneDragLeave:
817 if (watched == m_view) {
818 m_dragging = false;
819 }
820 break;
821
822 case QEvent::GraphicsSceneDrop:
823 if (watched == m_view) {
824 m_dragging = false;
825 }
826 default:
827 break;
828 }
829
830 return QWidget::eventFilter(watched, event);
831 }
832
833 void DolphinView::wheelEvent(QWheelEvent* event)
834 {
835 if (event->modifiers().testFlag(Qt::ControlModifier)) {
836 const int numDegrees = event->delta() / 8;
837 const int numSteps = numDegrees / 15;
838
839 setZoomLevel(zoomLevel() + numSteps);
840 event->accept();
841 } else {
842 event->ignore();
843 }
844 }
845
846 void DolphinView::hideEvent(QHideEvent* event)
847 {
848 hideToolTip();
849 QWidget::hideEvent(event);
850 }
851
852 bool DolphinView::event(QEvent* event)
853 {
854 if (event->type() == QEvent::WindowDeactivate) {
855 /* See Bug 297355
856 * Dolphin leaves file preview tooltips open even when is not visible.
857 *
858 * Hide tool-tip when Dolphin loses focus.
859 */
860 hideToolTip();
861 abortTwoClicksRenaming();
862 }
863
864 return QWidget::event(event);
865 }
866
867 void DolphinView::activate()
868 {
869 setActive(true);
870 }
871
872 void DolphinView::slotItemActivated(int index)
873 {
874 abortTwoClicksRenaming();
875
876 const KFileItem item = m_model->fileItem(index);
877 if (!item.isNull()) {
878 emit itemActivated(item);
879 }
880 }
881
882 void DolphinView::slotItemsActivated(const KItemSet& indexes)
883 {
884 Q_ASSERT(indexes.count() >= 2);
885
886 abortTwoClicksRenaming();
887
888 if (indexes.count() > 5) {
889 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
890 const int answer = KMessageBox::warningYesNo(this, question);
891 if (answer != KMessageBox::Yes) {
892 return;
893 }
894 }
895
896 KFileItemList items;
897 items.reserve(indexes.count());
898
899 for (int index : indexes) {
900 KFileItem item = m_model->fileItem(index);
901 const QUrl& url = openItemAsFolderUrl(item);
902
903 if (!url.isEmpty()) { // Open folders in new tabs
904 emit tabRequested(url, DolphinTabWidget::AfterLastTab);
905 } else {
906 items.append(item);
907 }
908 }
909
910 if (items.count() == 1) {
911 emit itemActivated(items.first());
912 } else if (items.count() > 1) {
913 emit itemsActivated(items);
914 }
915 }
916
917 void DolphinView::slotItemMiddleClicked(int index)
918 {
919 const KFileItem& item = m_model->fileItem(index);
920 const QUrl& url = openItemAsFolderUrl(item);
921 if (!url.isEmpty()) {
922 emit tabRequested(url, DolphinTabWidget::AfterCurrentTab);
923 } else if (isTabsForFilesEnabled()) {
924 emit tabRequested(item.url(), DolphinTabWidget::AfterCurrentTab);
925 }
926 }
927
928 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
929 {
930 // Force emit of a selection changed signal before we request the
931 // context menu, to update the edit-actions first. (See Bug 294013)
932 if (m_selectionChangedTimer->isActive()) {
933 emitSelectionChangedSignal();
934 }
935
936 const KFileItem item = m_model->fileItem(index);
937 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
938 }
939
940 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
941 {
942 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
943 }
944
945 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
946 {
947 ViewProperties props(viewPropertiesUrl());
948
949 QPointer<QMenu> menu = new QMenu(QApplication::activeWindow());
950
951 KItemListView* view = m_container->controller()->view();
952 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
953
954 bool indexingEnabled = false;
955 #ifdef HAVE_BALOO
956 Baloo::IndexerConfig config;
957 indexingEnabled = config.fileIndexingEnabled();
958 #endif
959
960 QString groupName;
961 QMenu* groupMenu = nullptr;
962
963 // Add all roles to the menu that can be shown or hidden by the user
964 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
965 foreach (const KFileItemModel::RoleInfo& info, rolesInfo) {
966 if (info.role == "text") {
967 // It should not be possible to hide the "text" role
968 continue;
969 }
970
971 const QString text = m_model->roleDescription(info.role);
972 QAction* action = nullptr;
973 if (info.group.isEmpty()) {
974 action = menu->addAction(text);
975 } else {
976 if (!groupMenu || info.group != groupName) {
977 groupName = info.group;
978 groupMenu = menu->addMenu(groupName);
979 }
980
981 action = groupMenu->addAction(text);
982 }
983
984 action->setCheckable(true);
985 action->setChecked(visibleRolesSet.contains(info.role));
986 action->setData(info.role);
987
988 const bool enable = (!info.requiresBaloo && !info.requiresIndexer) ||
989 (info.requiresBaloo) ||
990 (info.requiresIndexer && indexingEnabled);
991 action->setEnabled(enable);
992 }
993
994 menu->addSeparator();
995
996 QActionGroup* widthsGroup = new QActionGroup(menu);
997 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
998
999 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
1000 autoAdjustWidthsAction->setCheckable(true);
1001 autoAdjustWidthsAction->setChecked(autoColumnWidths);
1002 autoAdjustWidthsAction->setActionGroup(widthsGroup);
1003
1004 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
1005 customWidthsAction->setCheckable(true);
1006 customWidthsAction->setChecked(!autoColumnWidths);
1007 customWidthsAction->setActionGroup(widthsGroup);
1008
1009 QAction* action = menu->exec(pos.toPoint());
1010 if (menu && action) {
1011 KItemListHeader* header = view->header();
1012
1013 if (action == autoAdjustWidthsAction) {
1014 // Clear the column-widths from the viewproperties and turn on
1015 // the automatic resizing of the columns
1016 props.setHeaderColumnWidths(QList<int>());
1017 header->setAutomaticColumnResizing(true);
1018 } else if (action == customWidthsAction) {
1019 // Apply the current column-widths as custom column-widths and turn
1020 // off the automatic resizing of the columns
1021 QList<int> columnWidths;
1022 columnWidths.reserve(view->visibleRoles().count());
1023 foreach (const QByteArray& role, view->visibleRoles()) {
1024 columnWidths.append(header->columnWidth(role));
1025 }
1026 props.setHeaderColumnWidths(columnWidths);
1027 header->setAutomaticColumnResizing(false);
1028 } else {
1029 // Show or hide the selected role
1030 const QByteArray selectedRole = action->data().toByteArray();
1031
1032 QList<QByteArray> visibleRoles = view->visibleRoles();
1033 if (action->isChecked()) {
1034 visibleRoles.append(selectedRole);
1035 } else {
1036 visibleRoles.removeOne(selectedRole);
1037 }
1038
1039 view->setVisibleRoles(visibleRoles);
1040 props.setVisibleRoles(visibleRoles);
1041
1042 QList<int> columnWidths;
1043 if (!header->automaticColumnResizing()) {
1044 columnWidths.reserve(view->visibleRoles().count());
1045 foreach (const QByteArray& role, view->visibleRoles()) {
1046 columnWidths.append(header->columnWidth(role));
1047 }
1048 }
1049 props.setHeaderColumnWidths(columnWidths);
1050 }
1051 }
1052
1053 delete menu;
1054 }
1055
1056 void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current)
1057 {
1058 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
1059
1060 ViewProperties props(viewPropertiesUrl());
1061 QList<int> columnWidths = props.headerColumnWidths();
1062 if (columnWidths.count() != visibleRoles.count()) {
1063 columnWidths.clear();
1064 columnWidths.reserve(visibleRoles.count());
1065 const KItemListHeader* header = m_view->header();
1066 foreach (const QByteArray& role, visibleRoles) {
1067 const int width = header->columnWidth(role);
1068 columnWidths.append(width);
1069 }
1070 }
1071
1072 const int roleIndex = visibleRoles.indexOf(role);
1073 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
1074 columnWidths[roleIndex] = current;
1075
1076 props.setHeaderColumnWidths(columnWidths);
1077 }
1078
1079 void DolphinView::slotItemHovered(int index)
1080 {
1081 const KFileItem item = m_model->fileItem(index);
1082
1083 if (GeneralSettings::showToolTips() && !m_dragging) {
1084 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
1085 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
1086 itemRect.moveTo(pos);
1087
1088 #ifdef HAVE_BALOO
1089 m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle());
1090 #endif
1091 }
1092
1093 emit requestItemInfo(item);
1094 }
1095
1096 void DolphinView::slotItemUnhovered(int index)
1097 {
1098 Q_UNUSED(index)
1099 hideToolTip();
1100 emit requestItemInfo(KFileItem());
1101 }
1102
1103 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1104 {
1105 QUrl destUrl;
1106 KFileItem destItem = m_model->fileItem(index);
1107 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1108 // Use the URL of the view as drop target if the item is no directory
1109 // or desktop-file
1110 destItem = m_model->rootItem();
1111 destUrl = url();
1112 } else {
1113 // The item represents a directory or desktop-file
1114 destUrl = destItem.mostLocalUrl();
1115 }
1116
1117 QDropEvent dropEvent(event->pos().toPoint(),
1118 event->possibleActions(),
1119 event->mimeData(),
1120 event->buttons(),
1121 event->modifiers());
1122 dropUrls(destUrl, &dropEvent, this);
1123
1124 setActive(true);
1125 }
1126
1127 void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget)
1128 {
1129 KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget);
1130
1131 if (job) {
1132 connect(job, &KIO::DropJob::result, this, &DolphinView::slotPasteJobResult);
1133
1134 if (destUrl == url()) {
1135 // Mark the dropped urls as selected.
1136 m_clearSelectionBeforeSelectingNewItems = true;
1137 m_markFirstNewlySelectedItemAsCurrent = true;
1138 connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated);
1139 }
1140 }
1141 }
1142
1143 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1144 {
1145 if (previous != nullptr) {
1146 Q_ASSERT(qobject_cast<KFileItemModel*>(previous));
1147 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(previous);
1148 disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1149 m_versionControlObserver->setModel(nullptr);
1150 }
1151
1152 if (current) {
1153 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1154 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1155 connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted);
1156 m_versionControlObserver->setModel(fileItemModel);
1157 }
1158 }
1159
1160 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1161 {
1162 Q_UNUSED(itemIndex)
1163
1164 hideToolTip();
1165
1166 if (buttons & Qt::BackButton) {
1167 emit goBackRequested();
1168 } else if (buttons & Qt::ForwardButton) {
1169 emit goForwardRequested();
1170 }
1171 }
1172
1173 void DolphinView::slotSelectedItemTextPressed(int index)
1174 {
1175 if (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) {
1176 const KFileItem item = m_model->fileItem(index);
1177 const KFileItemListProperties capabilities(KFileItemList() << item);
1178 if (capabilities.supportsMoving()) {
1179 m_twoClicksRenamingItemUrl = item.url();
1180 m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval());
1181 }
1182 }
1183 }
1184
1185 void DolphinView::slotItemCreated(const QUrl& url)
1186 {
1187 if (m_markFirstNewlySelectedItemAsCurrent) {
1188 markUrlAsCurrent(url);
1189 m_markFirstNewlySelectedItemAsCurrent = false;
1190 }
1191 m_selectedUrls << url;
1192 }
1193
1194 void DolphinView::slotPasteJobResult(KJob *job)
1195 {
1196 if (job->error()) {
1197 emit errorMessage(job->errorString());
1198 }
1199 if (!m_selectedUrls.isEmpty()) {
1200 m_selectedUrls << KDirModel::simplifiedUrlList(m_selectedUrls);
1201 }
1202 }
1203
1204 void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous)
1205 {
1206 const int currentCount = current.count();
1207 const int previousCount = previous.count();
1208 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1209 (currentCount > 0 && previousCount == 0);
1210
1211 // If nothing has been selected before and something got selected (or if something
1212 // was selected before and now nothing is selected) the selectionChangedSignal must
1213 // be emitted asynchronously as fast as possible to update the edit-actions.
1214 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1215 m_selectionChangedTimer->start();
1216 }
1217
1218 void DolphinView::emitSelectionChangedSignal()
1219 {
1220 m_selectionChangedTimer->stop();
1221 emit selectionChanged(selectedItems());
1222 }
1223
1224 void DolphinView::updateSortRole(const QByteArray& role)
1225 {
1226 ViewProperties props(viewPropertiesUrl());
1227 props.setSortRole(role);
1228
1229 KItemModelBase* model = m_container->controller()->model();
1230 model->setSortRole(role);
1231
1232 emit sortRoleChanged(role);
1233 }
1234
1235 void DolphinView::updateSortOrder(Qt::SortOrder order)
1236 {
1237 ViewProperties props(viewPropertiesUrl());
1238 props.setSortOrder(order);
1239
1240 m_model->setSortOrder(order);
1241
1242 emit sortOrderChanged(order);
1243 }
1244
1245 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1246 {
1247 ViewProperties props(viewPropertiesUrl());
1248 props.setSortFoldersFirst(foldersFirst);
1249
1250 m_model->setSortDirectoriesFirst(foldersFirst);
1251
1252 emit sortFoldersFirstChanged(foldersFirst);
1253 }
1254
1255 QPair<bool, QString> DolphinView::pasteInfo() const
1256 {
1257 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
1258 QPair<bool, QString> info;
1259 info.second = KIO::pasteActionText(mimeData, &info.first, rootItem());
1260 return info;
1261 }
1262
1263 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1264 {
1265 m_tabsForFiles = tabsForFiles;
1266 }
1267
1268 bool DolphinView::isTabsForFilesEnabled() const
1269 {
1270 return m_tabsForFiles;
1271 }
1272
1273 bool DolphinView::itemsExpandable() const
1274 {
1275 return m_mode == DetailsView;
1276 }
1277
1278 void DolphinView::restoreState(QDataStream& stream)
1279 {
1280 // Read the version number of the view state and check if the version is supported.
1281 quint32 version = 0;
1282 stream >> version;
1283 if (version != 1) {
1284 // The version of the view state isn't supported, we can't restore it.
1285 return;
1286 }
1287
1288 // Restore the current item that had the keyboard focus
1289 stream >> m_currentItemUrl;
1290
1291 // Restore the previously selected items
1292 stream >> m_selectedUrls;
1293
1294 // Restore the view position
1295 stream >> m_restoredContentsPosition;
1296
1297 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1298 QSet<QUrl> urls;
1299 stream >> urls;
1300 m_model->restoreExpandedDirectories(urls);
1301 }
1302
1303 void DolphinView::saveState(QDataStream& stream)
1304 {
1305 stream << quint32(1); // View state version
1306
1307 // Save the current item that has the keyboard focus
1308 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1309 if (currentIndex != -1) {
1310 KFileItem item = m_model->fileItem(currentIndex);
1311 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1312 QUrl currentItemUrl = item.url();
1313 stream << currentItemUrl;
1314 } else {
1315 stream << QUrl();
1316 }
1317
1318 // Save the selected urls
1319 stream << selectedItems().urlList();
1320
1321 // Save view position
1322 const qreal x = m_container->horizontalScrollBar()->value();
1323 const qreal y = m_container->verticalScrollBar()->value();
1324 stream << QPoint(x, y);
1325
1326 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1327 stream << m_model->expandedDirectories();
1328 }
1329
1330 KFileItem DolphinView::rootItem() const
1331 {
1332 return m_model->rootItem();
1333 }
1334
1335 void DolphinView::setViewPropertiesContext(const QString& context)
1336 {
1337 m_viewPropertiesContext = context;
1338 }
1339
1340 QString DolphinView::viewPropertiesContext() const
1341 {
1342 return m_viewPropertiesContext;
1343 }
1344
1345 QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1346 {
1347 if (item.isNull()) {
1348 return QUrl();
1349 }
1350
1351 QUrl url = item.targetUrl();
1352
1353 if (item.isDir()) {
1354 return url;
1355 }
1356
1357 if (item.isMimeTypeKnown()) {
1358 const QString& mimetype = item.mimetype();
1359
1360 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1361 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1362 // zip:/<path>/ when clicking on a zip file, etc.
1363 // The .protocol file specifies the mimetype that the kioslave handles.
1364 // Note that we don't use mimetype inheritance since we don't want to
1365 // open OpenDocument files as zip folders...
1366 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1367 if (!protocol.isEmpty()) {
1368 url.setScheme(protocol);
1369 return url;
1370 }
1371 }
1372
1373 if (mimetype == QLatin1String("application/x-desktop")) {
1374 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1375 KDesktopFile desktopFile(url.toLocalFile());
1376 if (desktopFile.hasLinkType()) {
1377 const QString linkUrl = desktopFile.readUrl();
1378 if (!linkUrl.startsWith(QLatin1String("http"))) {
1379 return QUrl::fromUserInput(linkUrl);
1380 }
1381 }
1382 }
1383 }
1384
1385 return QUrl();
1386 }
1387
1388 void DolphinView::resetZoomLevel()
1389 {
1390 ViewModeSettings::ViewMode mode;
1391
1392 switch (m_mode) {
1393 case IconsView: mode = ViewModeSettings::IconsMode; break;
1394 case CompactView: mode = ViewModeSettings::CompactMode; break;
1395 case DetailsView: mode = ViewModeSettings::DetailsMode; break;
1396 }
1397 const ViewModeSettings settings(mode);
1398 const QSize iconSize = QSize(settings.iconSize(), settings.iconSize());
1399 setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize));
1400 }
1401
1402 void DolphinView::observeCreatedItem(const QUrl& url)
1403 {
1404 if (m_active) {
1405 forceUrlsSelection(url, {url});
1406 }
1407 }
1408
1409 void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl)
1410 {
1411 if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) {
1412 emit redirection(oldUrl, newUrl);
1413 m_url = newUrl; // #186947
1414 }
1415 }
1416
1417 void DolphinView::updateViewState()
1418 {
1419 if (m_currentItemUrl != QUrl()) {
1420 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1421
1422 // if there is a selection already, leave it that way
1423 if (!selectionManager->hasSelection()) {
1424 const int currentIndex = m_model->index(m_currentItemUrl);
1425 if (currentIndex != -1) {
1426 selectionManager->setCurrentItem(currentIndex);
1427
1428 // scroll to current item and reset the state
1429 if (m_scrollToCurrentItem) {
1430 m_view->scrollToItem(currentIndex);
1431 m_scrollToCurrentItem = false;
1432 }
1433 } else {
1434 selectionManager->setCurrentItem(0);
1435 }
1436 }
1437
1438 m_currentItemUrl = QUrl();
1439 }
1440
1441 if (!m_restoredContentsPosition.isNull()) {
1442 const int x = m_restoredContentsPosition.x();
1443 const int y = m_restoredContentsPosition.y();
1444 m_restoredContentsPosition = QPoint();
1445
1446 m_container->horizontalScrollBar()->setValue(x);
1447 m_container->verticalScrollBar()->setValue(y);
1448 }
1449
1450 if (!m_selectedUrls.isEmpty()) {
1451 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1452
1453 // if there is a selection already, leave it that way
1454 if (!selectionManager->hasSelection()) {
1455 if (m_clearSelectionBeforeSelectingNewItems) {
1456 selectionManager->clearSelection();
1457 m_clearSelectionBeforeSelectingNewItems = false;
1458 }
1459
1460 KItemSet selectedItems = selectionManager->selectedItems();
1461
1462 QList<QUrl>::iterator it = m_selectedUrls.begin();
1463 while (it != m_selectedUrls.end()) {
1464 const int index = m_model->index(*it);
1465 if (index >= 0) {
1466 selectedItems.insert(index);
1467 it = m_selectedUrls.erase(it);
1468 } else {
1469 ++it;
1470 }
1471 }
1472
1473 selectionManager->beginAnchoredSelection(selectionManager->currentItem());
1474 selectionManager->setSelectedItems(selectedItems);
1475 }
1476 }
1477 }
1478
1479 void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior)
1480 {
1481 #ifdef HAVE_BALOO
1482 if (GeneralSettings::showToolTips()) {
1483 m_toolTipManager->hideToolTip(behavior);
1484 }
1485 #endif
1486 }
1487
1488 void DolphinView::calculateItemCount(int& fileCount,
1489 int& folderCount,
1490 KIO::filesize_t& totalFileSize) const
1491 {
1492 const int itemCount = m_model->count();
1493 for (int i = 0; i < itemCount; ++i) {
1494 const KFileItem item = m_model->fileItem(i);
1495 if (item.isDir()) {
1496 ++folderCount;
1497 } else {
1498 ++fileCount;
1499 totalFileSize += item.size();
1500 }
1501 }
1502 }
1503
1504 void DolphinView::slotTwoClicksRenamingTimerTimeout()
1505 {
1506 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1507
1508 // verify that only one item is selected
1509 if (selectionManager->selectedItems().count() == 1) {
1510 const int index = selectionManager->currentItem();
1511 const QUrl fileItemUrl = m_model->fileItem(index).url();
1512
1513 // check if the selected item was the same item that started the twoClicksRenaming
1514 if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) {
1515 renameSelectedItems();
1516 }
1517 }
1518 }
1519
1520 void DolphinView::slotTrashFileFinished(KJob* job)
1521 {
1522 if (job->error() == 0) {
1523 emit operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1524 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1525 emit errorMessage(job->errorString());
1526 }
1527 }
1528
1529 void DolphinView::slotDeleteFileFinished(KJob* job)
1530 {
1531 if (job->error() == 0) {
1532 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1533 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1534 emit errorMessage(job->errorString());
1535 }
1536 }
1537
1538 void DolphinView::slotRenamingResult(KJob* job)
1539 {
1540 if (job->error()) {
1541 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1542 Q_ASSERT(copyJob);
1543 const QUrl newUrl = copyJob->destUrl();
1544 const int index = m_model->index(newUrl);
1545 if (index >= 0) {
1546 QHash<QByteArray, QVariant> data;
1547 const QUrl oldUrl = copyJob->srcUrls().at(0);
1548 data.insert("text", oldUrl.fileName());
1549 m_model->setData(index, data);
1550 }
1551 }
1552 }
1553
1554 void DolphinView::slotDirectoryLoadingStarted()
1555 {
1556 // Disable the writestate temporary until it can be determined in a fast way
1557 // in DolphinView::slotDirectoryLoadingCompleted()
1558 if (m_isFolderWritable) {
1559 m_isFolderWritable = false;
1560 emit writeStateChanged(m_isFolderWritable);
1561 }
1562
1563 emit directoryLoadingStarted();
1564 }
1565
1566 void DolphinView::slotDirectoryLoadingCompleted()
1567 {
1568 // Update the view-state. This has to be done asynchronously
1569 // because the view might not be in its final state yet.
1570 QTimer::singleShot(0, this, &DolphinView::updateViewState);
1571
1572 emit directoryLoadingCompleted();
1573
1574 updateWritableState();
1575 }
1576
1577 void DolphinView::slotItemsChanged()
1578 {
1579 m_assureVisibleCurrentIndex = false;
1580 }
1581
1582 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1583 {
1584 Q_UNUSED(previous)
1585 Q_ASSERT(m_model->sortOrder() == current);
1586
1587 ViewProperties props(viewPropertiesUrl());
1588 props.setSortOrder(current);
1589
1590 emit sortOrderChanged(current);
1591 }
1592
1593 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1594 {
1595 Q_UNUSED(previous)
1596 Q_ASSERT(m_model->sortRole() == current);
1597
1598 ViewProperties props(viewPropertiesUrl());
1599 props.setSortRole(current);
1600
1601 emit sortRoleChanged(current);
1602 }
1603
1604 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1605 const QList<QByteArray>& previous)
1606 {
1607 Q_UNUSED(previous)
1608 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1609
1610 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1611
1612 m_visibleRoles = current;
1613
1614 ViewProperties props(viewPropertiesUrl());
1615 props.setVisibleRoles(m_visibleRoles);
1616
1617 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1618 }
1619
1620 void DolphinView::slotRoleEditingCanceled()
1621 {
1622 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1623 this, &DolphinView::slotRoleEditingFinished);
1624 }
1625
1626 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1627 {
1628 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1629 this, &DolphinView::slotRoleEditingFinished);
1630
1631 if (index < 0 || index >= m_model->count()) {
1632 return;
1633 }
1634
1635 if (role == "text") {
1636 const KFileItem oldItem = m_model->fileItem(index);
1637 const QString newName = value.toString();
1638 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) {
1639 const QUrl oldUrl = oldItem.url();
1640
1641 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1642 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1643
1644 #ifndef Q_OS_WIN
1645 //Confirm hiding file/directory by renaming inline
1646 if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) {
1647 KGuiItem yesGuiItem(KStandardGuiItem::yes());
1648 yesGuiItem.setText(i18nc("@action:button", "Rename and Hide"));
1649
1650 const auto code = KMessageBox::questionYesNo(this,
1651 oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n"
1652 "Do you still want to rename it?")
1653 : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n"
1654 "Do you still want to rename it?"),
1655 oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"),
1656 yesGuiItem,
1657 KStandardGuiItem::cancel(),
1658 QStringLiteral("ConfirmHide")
1659 );
1660
1661 if (code == KMessageBox::No) {
1662 return;
1663 }
1664 }
1665 #endif
1666
1667 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1668 if (!newNameExistsAlready) {
1669 // Only change the data in the model if no item with the new name
1670 // is in the model yet. If there is an item with the new name
1671 // already, calling KIO::CopyJob will open a dialog
1672 // asking for a new name, and KFileItemModel will update the
1673 // data when the dir lister signals that the file name has changed.
1674 QHash<QByteArray, QVariant> data;
1675 data.insert(role, value);
1676 m_model->setData(index, data);
1677 }
1678
1679 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1680 KJobWidgets::setWindow(job, this);
1681 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job);
1682 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
1683
1684 forceUrlsSelection(newUrl, {newUrl});
1685
1686 if (!newNameExistsAlready) {
1687 // Only connect the result signal if there is no item with the new name
1688 // in the model yet, see bug 328262.
1689 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1690 }
1691 }
1692 }
1693 }
1694
1695 void DolphinView::loadDirectory(const QUrl& url, bool reload)
1696 {
1697 if (!url.isValid()) {
1698 const QString location(url.toDisplayString(QUrl::PreferLocalFile));
1699 if (location.isEmpty()) {
1700 emit errorMessage(i18nc("@info:status", "The location is empty."));
1701 } else {
1702 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1703 }
1704 return;
1705 }
1706
1707 if (reload) {
1708 m_model->refreshDirectory(url);
1709 } else {
1710 m_model->loadDirectory(url);
1711 }
1712 }
1713
1714 void DolphinView::applyViewProperties()
1715 {
1716 const ViewProperties props(viewPropertiesUrl());
1717 applyViewProperties(props);
1718 }
1719
1720 void DolphinView::applyViewProperties(const ViewProperties& props)
1721 {
1722 m_view->beginTransaction();
1723
1724 const Mode mode = props.viewMode();
1725 if (m_mode != mode) {
1726 const Mode previousMode = m_mode;
1727 m_mode = mode;
1728
1729 // Changing the mode might result in changing
1730 // the zoom level. Remember the old zoom level so
1731 // that zoomLevelChanged() can get emitted.
1732 const int oldZoomLevel = m_view->zoomLevel();
1733 applyModeToView();
1734
1735 emit modeChanged(m_mode, previousMode);
1736
1737 if (m_view->zoomLevel() != oldZoomLevel) {
1738 emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1739 }
1740 }
1741
1742 const bool hiddenFilesShown = props.hiddenFilesShown();
1743 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1744 m_model->setShowHiddenFiles(hiddenFilesShown);
1745 emit hiddenFilesShownChanged(hiddenFilesShown);
1746 }
1747
1748 const bool groupedSorting = props.groupedSorting();
1749 if (groupedSorting != m_model->groupedSorting()) {
1750 m_model->setGroupedSorting(groupedSorting);
1751 emit groupedSortingChanged(groupedSorting);
1752 }
1753
1754 const QByteArray sortRole = props.sortRole();
1755 if (sortRole != m_model->sortRole()) {
1756 m_model->setSortRole(sortRole);
1757 emit sortRoleChanged(sortRole);
1758 }
1759
1760 const Qt::SortOrder sortOrder = props.sortOrder();
1761 if (sortOrder != m_model->sortOrder()) {
1762 m_model->setSortOrder(sortOrder);
1763 emit sortOrderChanged(sortOrder);
1764 }
1765
1766 const bool sortFoldersFirst = props.sortFoldersFirst();
1767 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1768 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1769 emit sortFoldersFirstChanged(sortFoldersFirst);
1770 }
1771
1772 const QList<QByteArray> visibleRoles = props.visibleRoles();
1773 if (visibleRoles != m_visibleRoles) {
1774 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1775 m_visibleRoles = visibleRoles;
1776 m_view->setVisibleRoles(visibleRoles);
1777 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1778 }
1779
1780 const bool previewsShown = props.previewsShown();
1781 if (previewsShown != m_view->previewsShown()) {
1782 const int oldZoomLevel = zoomLevel();
1783
1784 m_view->setPreviewsShown(previewsShown);
1785 emit previewsShownChanged(previewsShown);
1786
1787 // Changing the preview-state might result in a changed zoom-level
1788 if (oldZoomLevel != zoomLevel()) {
1789 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1790 }
1791 }
1792
1793 KItemListView* itemListView = m_container->controller()->view();
1794 if (itemListView->isHeaderVisible()) {
1795 KItemListHeader* header = itemListView->header();
1796 const QList<int> headerColumnWidths = props.headerColumnWidths();
1797 const int rolesCount = m_visibleRoles.count();
1798 if (headerColumnWidths.count() == rolesCount) {
1799 header->setAutomaticColumnResizing(false);
1800
1801 QHash<QByteArray, qreal> columnWidths;
1802 for (int i = 0; i < rolesCount; ++i) {
1803 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1804 }
1805 header->setColumnWidths(columnWidths);
1806 } else {
1807 header->setAutomaticColumnResizing(true);
1808 }
1809 }
1810
1811 m_view->endTransaction();
1812 }
1813
1814 void DolphinView::applyModeToView()
1815 {
1816 switch (m_mode) {
1817 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1818 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1819 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1820 default: Q_ASSERT(false); break;
1821 }
1822 }
1823
1824 void DolphinView::pasteToUrl(const QUrl& url)
1825 {
1826 KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url);
1827 KJobWidgets::setWindow(job, this);
1828 m_clearSelectionBeforeSelectingNewItems = true;
1829 m_markFirstNewlySelectedItemAsCurrent = true;
1830 connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated);
1831 connect(job, &KIO::PasteJob::result, this, &DolphinView::slotPasteJobResult);
1832 }
1833
1834 QList<QUrl> DolphinView::simplifiedSelectedUrls() const
1835 {
1836 QList<QUrl> urls;
1837
1838 const KFileItemList items = selectedItems();
1839 urls.reserve(items.count());
1840 foreach (const KFileItem& item, items) {
1841 urls.append(item.url());
1842 }
1843
1844 if (itemsExpandable()) {
1845 // TODO: Check if we still need KDirModel for this in KDE 5.0
1846 urls = KDirModel::simplifiedUrlList(urls);
1847 }
1848
1849 return urls;
1850 }
1851
1852 QMimeData* DolphinView::selectionMimeData() const
1853 {
1854 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1855 const KItemSet selectedIndexes = selectionManager->selectedItems();
1856
1857 return m_model->createMimeData(selectedIndexes);
1858 }
1859
1860 void DolphinView::updateWritableState()
1861 {
1862 const bool wasFolderWritable = m_isFolderWritable;
1863 m_isFolderWritable = false;
1864
1865 KFileItem item = m_model->rootItem();
1866 if (item.isNull()) {
1867 // Try to find out if the URL is writable even if the "root item" is
1868 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1869 item = KFileItem(url());
1870 item.setDelayedMimeTypes(true);
1871 }
1872
1873 KFileItemListProperties capabilities(KFileItemList() << item);
1874 m_isFolderWritable = capabilities.supportsWriting();
1875
1876 if (m_isFolderWritable != wasFolderWritable) {
1877 emit writeStateChanged(m_isFolderWritable);
1878 }
1879 }
1880
1881 QUrl DolphinView::viewPropertiesUrl() const
1882 {
1883 if (m_viewPropertiesContext.isEmpty()) {
1884 return m_url;
1885 }
1886
1887 QUrl url;
1888 url.setScheme(m_url.scheme());
1889 url.setPath(m_viewPropertiesContext);
1890 return url;
1891 }
1892
1893 void DolphinView::slotRenameDialogRenamingFinished(const QList<QUrl>& urls)
1894 {
1895 forceUrlsSelection(urls.first(), urls);
1896 }
1897
1898 void DolphinView::forceUrlsSelection(const QUrl& current, const QList<QUrl>& selected)
1899 {
1900 clearSelection();
1901 m_clearSelectionBeforeSelectingNewItems = true;
1902 markUrlAsCurrent(current);
1903 markUrlsAsSelected(selected);
1904 }