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