]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Fix includes
[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 <KUrl>
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 KUrl& 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 KUrl 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 = KUrl::List(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<KUrl>& urls)
366 {
367 m_selectedUrls = urls;
368 }
369
370 void DolphinView::markUrlAsCurrent(const KUrl& 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 = KUrl::List(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 KUrl& 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 KUrl::List 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, KUrl("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 KUrl::List 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 KUrl& 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 KUrl& 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 KUrl 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 KUrl::List&)>(&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 KUrl::List& urls)
1089 {
1090 if (!urls.isEmpty()) {
1091 if (m_markFirstNewlySelectedItemAsCurrent) {
1092 markUrlAsCurrent(urls.first());
1093 m_markFirstNewlySelectedItemAsCurrent = false;
1094 }
1095 m_selectedUrls << KUrl::List(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 return KonqOperations::pasteInfo(url());
1153 }
1154
1155 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1156 {
1157 m_tabsForFiles = tabsForFiles;
1158 }
1159
1160 bool DolphinView::isTabsForFilesEnabled() const
1161 {
1162 return m_tabsForFiles;
1163 }
1164
1165 bool DolphinView::itemsExpandable() const
1166 {
1167 return m_mode == DetailsView;
1168 }
1169
1170 void DolphinView::restoreState(QDataStream& stream)
1171 {
1172 // Read the version number of the view state and check if the version is supported.
1173 quint32 version = 0;
1174 stream >> version;
1175 if (version != 1) {
1176 // The version of the view state isn't supported, we can't restore it.
1177 return;
1178 }
1179
1180 // Restore the current item that had the keyboard focus
1181 stream >> m_currentItemUrl;
1182
1183 // Restore the view position
1184 stream >> m_restoredContentsPosition;
1185
1186 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1187 QSet<KUrl> urls;
1188 stream >> urls;
1189 m_model->restoreExpandedDirectories(urls);
1190 }
1191
1192 void DolphinView::saveState(QDataStream& stream)
1193 {
1194 stream << quint32(1); // View state version
1195
1196 // Save the current item that has the keyboard focus
1197 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1198 if (currentIndex != -1) {
1199 KFileItem item = m_model->fileItem(currentIndex);
1200 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1201 KUrl currentItemUrl = item.url();
1202 stream << currentItemUrl;
1203 } else {
1204 stream << KUrl();
1205 }
1206
1207 // Save view position
1208 const qreal x = m_container->horizontalScrollBar()->value();
1209 const qreal y = m_container->verticalScrollBar()->value();
1210 stream << QPoint(x, y);
1211
1212 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1213 stream << m_model->expandedDirectories();
1214 }
1215
1216 KFileItem DolphinView::rootItem() const
1217 {
1218 return m_model->rootItem();
1219 }
1220
1221 void DolphinView::setViewPropertiesContext(const QString& context)
1222 {
1223 m_viewPropertiesContext = context;
1224 }
1225
1226 QString DolphinView::viewPropertiesContext() const
1227 {
1228 return m_viewPropertiesContext;
1229 }
1230
1231 KUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1232 {
1233 if (item.isNull()) {
1234 return KUrl();
1235 }
1236
1237 KUrl url = item.targetUrl();
1238
1239 if (item.isDir()) {
1240 return url;
1241 }
1242
1243 if (item.isMimeTypeKnown()) {
1244 const QString& mimetype = item.mimetype();
1245
1246 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1247 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1248 // zip:/<path>/ when clicking on a zip file, etc.
1249 // The .protocol file specifies the mimetype that the kioslave handles.
1250 // Note that we don't use mimetype inheritance since we don't want to
1251 // open OpenDocument files as zip folders...
1252 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1253 if (!protocol.isEmpty()) {
1254 url.setProtocol(protocol);
1255 return url;
1256 }
1257 }
1258
1259 if (mimetype == QLatin1String("application/x-desktop")) {
1260 // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL.
1261 KDesktopFile desktopFile(url.toLocalFile());
1262 if (desktopFile.hasLinkType()) {
1263 const QString linkUrl = desktopFile.readUrl();
1264 if (!linkUrl.startsWith(QLatin1String("http"))) {
1265 return linkUrl;
1266 }
1267 }
1268 }
1269 }
1270
1271 return KUrl();
1272 }
1273
1274 void DolphinView::observeCreatedItem(const KUrl& url)
1275 {
1276 if (m_active) {
1277 clearSelection();
1278 markUrlAsCurrent(url);
1279 markUrlsAsSelected(QList<KUrl>() << url);
1280 }
1281 }
1282
1283 void DolphinView::slotDirectoryRedirection(const KUrl& oldUrl, const KUrl& newUrl)
1284 {
1285 if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) {
1286 emit redirection(oldUrl, newUrl);
1287 m_url = newUrl; // #186947
1288 }
1289 }
1290
1291 void DolphinView::updateViewState()
1292 {
1293 if (m_currentItemUrl != KUrl()) {
1294 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1295 const int currentIndex = m_model->index(m_currentItemUrl);
1296 if (currentIndex != -1) {
1297 selectionManager->setCurrentItem(currentIndex);
1298
1299 // scroll to current item and reset the state
1300 if (m_scrollToCurrentItem) {
1301 m_view->scrollToItem(currentIndex);
1302 m_scrollToCurrentItem = false;
1303 }
1304 } else {
1305 selectionManager->setCurrentItem(0);
1306 }
1307
1308 m_currentItemUrl = KUrl();
1309 }
1310
1311 if (!m_restoredContentsPosition.isNull()) {
1312 const int x = m_restoredContentsPosition.x();
1313 const int y = m_restoredContentsPosition.y();
1314 m_restoredContentsPosition = QPoint();
1315
1316 m_container->horizontalScrollBar()->setValue(x);
1317 m_container->verticalScrollBar()->setValue(y);
1318 }
1319
1320 if (!m_selectedUrls.isEmpty()) {
1321 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1322
1323 if (m_clearSelectionBeforeSelectingNewItems) {
1324 selectionManager->clearSelection();
1325 m_clearSelectionBeforeSelectingNewItems = false;
1326 }
1327
1328 KItemSet selectedItems = selectionManager->selectedItems();
1329
1330 QList<KUrl>::iterator it = m_selectedUrls.begin();
1331 while (it != m_selectedUrls.end()) {
1332 const int index = m_model->index(*it);
1333 if (index >= 0) {
1334 selectedItems.insert(index);
1335 it = m_selectedUrls.erase(it);
1336 } else {
1337 ++it;
1338 }
1339 }
1340
1341 selectionManager->setSelectedItems(selectedItems);
1342 }
1343 }
1344
1345 void DolphinView::hideToolTip()
1346 {
1347 if (GeneralSettings::showToolTips()) {
1348 m_toolTipManager->hideToolTip();
1349 }
1350 }
1351
1352 void DolphinView::calculateItemCount(int& fileCount,
1353 int& folderCount,
1354 KIO::filesize_t& totalFileSize) const
1355 {
1356 const int itemCount = m_model->count();
1357 for (int i = 0; i < itemCount; ++i) {
1358 const KFileItem item = m_model->fileItem(i);
1359 if (item.isDir()) {
1360 ++folderCount;
1361 } else {
1362 ++fileCount;
1363 totalFileSize += item.size();
1364 }
1365 }
1366 }
1367
1368 void DolphinView::slotTrashFileFinished(KJob* job)
1369 {
1370 if (job->error() == 0) {
1371 emit operationCompletedMessage(i18nc("@info:status", "Trash operation completed."));
1372 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1373 emit errorMessage(job->errorString());
1374 }
1375 }
1376
1377 void DolphinView::slotDeleteFileFinished(KJob* job)
1378 {
1379 if (job->error() == 0) {
1380 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1381 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1382 emit errorMessage(job->errorString());
1383 }
1384 }
1385
1386 void DolphinView::slotRenamingResult(KJob* job)
1387 {
1388 if (job->error()) {
1389 KIO::CopyJob *copyJob = qobject_cast<KIO::CopyJob *>(job);
1390 Q_ASSERT(copyJob);
1391 const QUrl newUrl = copyJob->destUrl();
1392 const int index = m_model->index(KUrl(newUrl));
1393 if (index >= 0) {
1394 QHash<QByteArray, QVariant> data;
1395 const QUrl oldUrl = copyJob->srcUrls().first();
1396 data.insert("text", oldUrl.fileName());
1397 m_model->setData(index, data);
1398 }
1399 }
1400 }
1401
1402 void DolphinView::slotDirectoryLoadingStarted()
1403 {
1404 // Disable the writestate temporary until it can be determined in a fast way
1405 // in DolphinView::slotLoadingCompleted()
1406 if (m_isFolderWritable) {
1407 m_isFolderWritable = false;
1408 emit writeStateChanged(m_isFolderWritable);
1409 }
1410
1411 emit directoryLoadingStarted();
1412 }
1413
1414 void DolphinView::slotDirectoryLoadingCompleted()
1415 {
1416 // Update the view-state. This has to be done asynchronously
1417 // because the view might not be in its final state yet.
1418 QTimer::singleShot(0, this, SLOT(updateViewState()));
1419
1420 emit directoryLoadingCompleted();
1421
1422 updateWritableState();
1423 }
1424
1425 void DolphinView::slotItemsChanged()
1426 {
1427 m_assureVisibleCurrentIndex = false;
1428 }
1429
1430 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1431 {
1432 Q_UNUSED(previous);
1433 Q_ASSERT(m_model->sortOrder() == current);
1434
1435 ViewProperties props(viewPropertiesUrl());
1436 props.setSortOrder(current);
1437
1438 emit sortOrderChanged(current);
1439 }
1440
1441 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1442 {
1443 Q_UNUSED(previous);
1444 Q_ASSERT(m_model->sortRole() == current);
1445
1446 ViewProperties props(viewPropertiesUrl());
1447 props.setSortRole(current);
1448
1449 emit sortRoleChanged(current);
1450 }
1451
1452 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1453 const QList<QByteArray>& previous)
1454 {
1455 Q_UNUSED(previous);
1456 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1457
1458 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1459
1460 m_visibleRoles = current;
1461
1462 ViewProperties props(viewPropertiesUrl());
1463 props.setVisibleRoles(m_visibleRoles);
1464
1465 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1466 }
1467
1468 void DolphinView::slotRoleEditingCanceled()
1469 {
1470 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1471 this, &DolphinView::slotRoleEditingFinished);
1472 }
1473
1474 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1475 {
1476 disconnect(m_view, &DolphinItemListView::roleEditingFinished,
1477 this, &DolphinView::slotRoleEditingFinished);
1478
1479 if (index < 0 || index >= m_model->count()) {
1480 return;
1481 }
1482
1483 if (role == "text") {
1484 const KFileItem oldItem = m_model->fileItem(index);
1485 const QString newName = value.toString();
1486 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1String(".") && newName != QLatin1String("..")) {
1487 const KUrl oldUrl = oldItem.url();
1488
1489 QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename);
1490 newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName));
1491
1492 const bool newNameExistsAlready = (m_model->index(KUrl(newUrl)) >= 0);
1493 if (!newNameExistsAlready) {
1494 // Only change the data in the model if no item with the new name
1495 // is in the model yet. If there is an item with the new name
1496 // already, calling KIO::CopyJob will open a dialog
1497 // asking for a new name, and KFileItemModel will update the
1498 // data when the dir lister signals that the file name has changed.
1499 QHash<QByteArray, QVariant> data;
1500 data.insert(role, value);
1501 m_model->setData(index, data);
1502 }
1503
1504 KIO::Job * job = KIO::moveAs(oldUrl, newUrl);
1505 KJobWidgets::setWindow(job, this);
1506 KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, QList<QUrl>() << oldUrl, newUrl, job);
1507 job->ui()->setAutoErrorHandlingEnabled(true);
1508
1509 if (!newNameExistsAlready) {
1510 // Only connect the result signal if there is no item with the new name
1511 // in the model yet, see bug 328262.
1512 connect(job, &KJob::result, this, &DolphinView::slotRenamingResult);
1513 }
1514 }
1515 }
1516 }
1517
1518 void DolphinView::loadDirectory(const KUrl& url, bool reload)
1519 {
1520 if (!url.isValid()) {
1521 const QString location(url.pathOrUrl());
1522 if (location.isEmpty()) {
1523 emit errorMessage(i18nc("@info:status", "The location is empty."));
1524 } else {
1525 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1526 }
1527 return;
1528 }
1529
1530 if (reload) {
1531 m_model->refreshDirectory(url);
1532 } else {
1533 m_model->loadDirectory(url);
1534 }
1535 }
1536
1537 void DolphinView::applyViewProperties()
1538 {
1539 const ViewProperties props(viewPropertiesUrl());
1540 applyViewProperties(props);
1541 }
1542
1543 void DolphinView::applyViewProperties(const ViewProperties& props)
1544 {
1545 m_view->beginTransaction();
1546
1547 const Mode mode = props.viewMode();
1548 if (m_mode != mode) {
1549 const Mode previousMode = m_mode;
1550 m_mode = mode;
1551
1552 // Changing the mode might result in changing
1553 // the zoom level. Remember the old zoom level so
1554 // that zoomLevelChanged() can get emitted.
1555 const int oldZoomLevel = m_view->zoomLevel();
1556 applyModeToView();
1557
1558 emit modeChanged(m_mode, previousMode);
1559
1560 if (m_view->zoomLevel() != oldZoomLevel) {
1561 emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1562 }
1563 }
1564
1565 const bool hiddenFilesShown = props.hiddenFilesShown();
1566 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1567 m_model->setShowHiddenFiles(hiddenFilesShown);
1568 emit hiddenFilesShownChanged(hiddenFilesShown);
1569 }
1570
1571 const bool groupedSorting = props.groupedSorting();
1572 if (groupedSorting != m_model->groupedSorting()) {
1573 m_model->setGroupedSorting(groupedSorting);
1574 emit groupedSortingChanged(groupedSorting);
1575 }
1576
1577 const QByteArray sortRole = props.sortRole();
1578 if (sortRole != m_model->sortRole()) {
1579 m_model->setSortRole(sortRole);
1580 emit sortRoleChanged(sortRole);
1581 }
1582
1583 const Qt::SortOrder sortOrder = props.sortOrder();
1584 if (sortOrder != m_model->sortOrder()) {
1585 m_model->setSortOrder(sortOrder);
1586 emit sortOrderChanged(sortOrder);
1587 }
1588
1589 const bool sortFoldersFirst = props.sortFoldersFirst();
1590 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1591 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1592 emit sortFoldersFirstChanged(sortFoldersFirst);
1593 }
1594
1595 const QList<QByteArray> visibleRoles = props.visibleRoles();
1596 if (visibleRoles != m_visibleRoles) {
1597 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1598 m_visibleRoles = visibleRoles;
1599 m_view->setVisibleRoles(visibleRoles);
1600 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1601 }
1602
1603 const bool previewsShown = props.previewsShown();
1604 if (previewsShown != m_view->previewsShown()) {
1605 const int oldZoomLevel = zoomLevel();
1606
1607 m_view->setPreviewsShown(previewsShown);
1608 emit previewsShownChanged(previewsShown);
1609
1610 // Changing the preview-state might result in a changed zoom-level
1611 if (oldZoomLevel != zoomLevel()) {
1612 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1613 }
1614 }
1615
1616 KItemListView* itemListView = m_container->controller()->view();
1617 if (itemListView->isHeaderVisible()) {
1618 KItemListHeader* header = itemListView->header();
1619 const QList<int> headerColumnWidths = props.headerColumnWidths();
1620 const int rolesCount = m_visibleRoles.count();
1621 if (headerColumnWidths.count() == rolesCount) {
1622 header->setAutomaticColumnResizing(false);
1623
1624 QHash<QByteArray, qreal> columnWidths;
1625 for (int i = 0; i < rolesCount; ++i) {
1626 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1627 }
1628 header->setColumnWidths(columnWidths);
1629 } else {
1630 header->setAutomaticColumnResizing(true);
1631 }
1632 }
1633
1634 m_view->endTransaction();
1635 }
1636
1637 void DolphinView::applyModeToView()
1638 {
1639 switch (m_mode) {
1640 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1641 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1642 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1643 default: Q_ASSERT(false); break;
1644 }
1645 }
1646
1647 void DolphinView::pasteToUrl(const KUrl& url)
1648 {
1649 KonqOperations* op = KonqOperations::doPasteV2(this, url);
1650 if (op) {
1651 m_clearSelectionBeforeSelectingNewItems = true;
1652 m_markFirstNewlySelectedItemAsCurrent = true;
1653 connect(op, static_cast<void(KonqOperations::*)(const KUrl::List&)>(&KonqOperations::aboutToCreate), this, &DolphinView::slotAboutToCreate);
1654 }
1655 }
1656
1657 KUrl::List DolphinView::simplifiedSelectedUrls() const
1658 {
1659 KUrl::List urls;
1660
1661 const KFileItemList items = selectedItems();
1662 foreach (const KFileItem& item, items) {
1663 urls.append(item.url());
1664 }
1665
1666 if (itemsExpandable()) {
1667 // TODO: Check if we still need KDirModel for this in KDE 5.0
1668 urls = KDirModel::simplifiedUrlList(urls);
1669 }
1670
1671 return urls;
1672 }
1673
1674 QMimeData* DolphinView::selectionMimeData() const
1675 {
1676 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1677 const KItemSet selectedIndexes = selectionManager->selectedItems();
1678
1679 return m_model->createMimeData(selectedIndexes);
1680 }
1681
1682 void DolphinView::updateWritableState()
1683 {
1684 const bool wasFolderWritable = m_isFolderWritable;
1685 m_isFolderWritable = false;
1686
1687 KFileItem item = m_model->rootItem();
1688 if (item.isNull()) {
1689 // Try to find out if the URL is writable even if the "root item" is
1690 // null, see https://bugs.kde.org/show_bug.cgi?id=330001
1691 item = KFileItem(KFileItem::Unknown, KFileItem::Unknown, url(), true);
1692 }
1693
1694 KFileItemListProperties capabilities(KFileItemList() << item);
1695 m_isFolderWritable = capabilities.supportsWriting();
1696
1697 if (m_isFolderWritable != wasFolderWritable) {
1698 emit writeStateChanged(m_isFolderWritable);
1699 }
1700 }
1701
1702 KUrl DolphinView::viewPropertiesUrl() const
1703 {
1704 if (m_viewPropertiesContext.isEmpty()) {
1705 return m_url;
1706 }
1707
1708 KUrl url;
1709 url.setProtocol(m_url.protocol());
1710 url.setPath(m_viewPropertiesContext);
1711 return url;
1712 }
1713