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