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