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