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