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