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