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