X-Git-Url: https://cloud.milkyroute.net/gitweb/dolphin.git/blobdiff_plain/dfaff684d6d75143e1831b16bb24fde9ffe24862..5454283008f2:/src/views/dolphinview.cpp diff --git a/src/views/dolphinview.cpp b/src/views/dolphinview.cpp index 29f62f735..4485c1707 100644 --- a/src/views/dolphinview.cpp +++ b/src/views/dolphinview.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright (C) 2006-2009 by Peter Penz * + * Copyright (C) 2006-2009 by Peter Penz * * Copyright (C) 2006 by Gregor Kališnik * * * * This program is free software; you can redistribute it and/or modify * @@ -20,147 +20,195 @@ #include "dolphinview.h" +#include + #include #include #include -#include -#include -#include +#include +#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "additionalinfoaccessor.h" -#include "dolphinmodel.h" -#include "dolphincolumnviewcontainer.h" -#include "dolphinviewcontroller.h" -#include "dolphindetailsview.h" -#include "dolphinfileitemdelegate.h" #include "dolphinnewfilemenuobserver.h" -#include "dolphinsortfilterproxymodel.h" #include "dolphin_detailsmodesettings.h" -#include "dolphiniconsview.h" #include "dolphin_generalsettings.h" +#include "dolphinitemlistview.h" #include "draganddrophelper.h" #include "renamedialog.h" -#include "settings/dolphinsettings.h" +#include "versioncontrol/versioncontrolobserver.h" #include "viewmodecontroller.h" #include "viewproperties.h" +#include "views/tooltips/tooltipmanager.h" #include "zoomlevelinfo.h" -#include "dolphindetailsviewexpander.h" -DolphinView::DolphinView(QWidget* parent, - const KUrl& url, - DolphinSortFilterProxyModel* proxyModel) : +#ifdef HAVE_BALOO + #include +#endif +#include + +DolphinView::DolphinView(const QUrl& url, QWidget* parent) : QWidget(parent), m_active(true), - m_showPreview(false), - m_storedCategorizedSorting(false), m_tabsForFiles(false), - m_isContextMenuOpen(false), m_assureVisibleCurrentIndex(false), - m_expanderActive(false), m_isFolderWritable(true), + m_dragging(false), + m_url(url), + m_viewPropertiesContext(), m_mode(DolphinView::IconsView), + m_visibleRoles(), m_topLayout(0), - m_dolphinViewController(0), - m_viewModeController(0), - m_viewAccessor(proxyModel), + m_model(0), + m_view(0), + m_container(0), + m_toolTipManager(0), m_selectionChangedTimer(0), - m_activeItemUrl(), + m_currentItemUrl(), + m_scrollToCurrentItem(false), m_restoredContentsPosition(), - m_createdItemUrl(), - m_selectedItems(), - m_newFileNames() + m_selectedUrls(), + m_clearSelectionBeforeSelectingNewItems(false), + m_markFirstNewlySelectedItemAsCurrent(false), + m_versionControlObserver(0), + m_twoClicksRenamingTimer(nullptr) { m_topLayout = new QVBoxLayout(this); m_topLayout->setSpacing(0); m_topLayout->setMargin(0); - m_dolphinViewController = new DolphinViewController(this); - - m_viewModeController = new ViewModeController(this); - m_viewModeController->setUrl(url); - - connect(m_viewModeController, SIGNAL(urlChanged(const KUrl&)), - this, SIGNAL(urlChanged(const KUrl&))); - - connect(m_dolphinViewController, SIGNAL(requestContextMenu(const QPoint&, const QList&)), - this, SLOT(openContextMenu(const QPoint&, const QList&))); - connect(m_dolphinViewController, SIGNAL(urlsDropped(const KFileItem&, const KUrl&, QDropEvent*)), - this, SLOT(dropUrls(const KFileItem&, const KUrl&, QDropEvent*))); - connect(m_dolphinViewController, SIGNAL(sortingChanged(DolphinView::Sorting)), - this, SLOT(updateSorting(DolphinView::Sorting))); - connect(m_dolphinViewController, SIGNAL(sortOrderChanged(Qt::SortOrder)), - this, SLOT(updateSortOrder(Qt::SortOrder))); - connect(m_dolphinViewController, SIGNAL(sortFoldersFirstChanged(bool)), - this, SLOT(updateSortFoldersFirst(bool))); - connect(m_dolphinViewController, SIGNAL(additionalInfoChanged(const KFileItemDelegate::InformationList&)), - this, SLOT(updateAdditionalInfo(const KFileItemDelegate::InformationList&))); - connect(m_dolphinViewController, SIGNAL(itemTriggered(const KFileItem&)), - this, SLOT(triggerItem(const KFileItem&))); - connect(m_dolphinViewController, SIGNAL(tabRequested(const KUrl&)), - this, SIGNAL(tabRequested(const KUrl&))); - connect(m_dolphinViewController, SIGNAL(activated()), - this, SLOT(activate())); - connect(m_dolphinViewController, SIGNAL(itemEntered(const KFileItem&)), - this, SLOT(showHoverInformation(const KFileItem&))); - connect(m_dolphinViewController, SIGNAL(viewportEntered()), - this, SLOT(clearHoverInformation())); - connect(m_dolphinViewController, SIGNAL(urlChangeRequested(KUrl)), - this, SLOT(slotUrlChangeRequested(KUrl))); - // When a new item has been created by the "Create New..." menu, the item should // get selected and it must be assured that the item will get visible. As the // creation is done asynchronously, several signals must be checked: - connect(&DolphinNewFileMenuObserver::instance(), SIGNAL(itemCreated(const KUrl&)), - this, SLOT(observeCreatedItem(const KUrl&))); + connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::itemCreated, + this, &DolphinView::observeCreatedItem); m_selectionChangedTimer = new QTimer(this); m_selectionChangedTimer->setSingleShot(true); m_selectionChangedTimer->setInterval(300); - connect(m_selectionChangedTimer, SIGNAL(timeout()), - this, SLOT(emitSelectionChangedSignal())); + connect(m_selectionChangedTimer, &QTimer::timeout, + this, &DolphinView::emitSelectionChangedSignal); + + m_model = new KFileItemModel(this); + m_view = new DolphinItemListView(); + m_view->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle()); + m_view->setVisibleRoles({"text"}); + applyModeToView(); + + KItemListController* controller = new KItemListController(m_model, m_view, this); + const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1; + controller->setAutoActivationDelay(delay); + + // The EnlargeSmallPreviews setting can only be changed after the model + // has been set in the view by KItemListController. + m_view->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews()); + + m_container = new KItemListContainer(controller, this); + m_container->installEventFilter(this); + setFocusProxy(m_container); + connect(m_container->horizontalScrollBar(), &QScrollBar::valueChanged, this, &DolphinView::hideToolTip); + connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, &DolphinView::hideToolTip); + + controller->setSelectionBehavior(KItemListController::MultiSelection); + connect(controller, &KItemListController::itemActivated, this, &DolphinView::slotItemActivated); + connect(controller, &KItemListController::itemsActivated, this, &DolphinView::slotItemsActivated); + connect(controller, &KItemListController::itemMiddleClicked, this, &DolphinView::slotItemMiddleClicked); + connect(controller, &KItemListController::itemContextMenuRequested, this, &DolphinView::slotItemContextMenuRequested); + connect(controller, &KItemListController::viewContextMenuRequested, this, &DolphinView::slotViewContextMenuRequested); + connect(controller, &KItemListController::headerContextMenuRequested, this, &DolphinView::slotHeaderContextMenuRequested); + connect(controller, &KItemListController::mouseButtonPressed, this, &DolphinView::slotMouseButtonPressed); + connect(controller, &KItemListController::itemHovered, this, &DolphinView::slotItemHovered); + connect(controller, &KItemListController::itemUnhovered, this, &DolphinView::slotItemUnhovered); + connect(controller, &KItemListController::itemDropEvent, this, &DolphinView::slotItemDropEvent); + connect(controller, &KItemListController::escapePressed, this, &DolphinView::stopLoading); + connect(controller, &KItemListController::modelChanged, this, &DolphinView::slotModelChanged); + connect(controller, &KItemListController::selectedItemTextPressed, this, &DolphinView::slotSelectedItemTextPressed); + + connect(m_model, &KFileItemModel::directoryLoadingStarted, this, &DolphinView::slotDirectoryLoadingStarted); + connect(m_model, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); + connect(m_model, &KFileItemModel::directoryLoadingCanceled, this, &DolphinView::directoryLoadingCanceled); + connect(m_model, &KFileItemModel::directoryLoadingProgress, this, &DolphinView::directoryLoadingProgress); + connect(m_model, &KFileItemModel::directorySortingProgress, this, &DolphinView::directorySortingProgress); + connect(m_model, &KFileItemModel::itemsChanged, + this, &DolphinView::slotItemsChanged); + connect(m_model, &KFileItemModel::itemsRemoved, this, &DolphinView::itemCountChanged); + connect(m_model, &KFileItemModel::itemsInserted, this, &DolphinView::itemCountChanged); + connect(m_model, &KFileItemModel::infoMessage, this, &DolphinView::infoMessage); + connect(m_model, &KFileItemModel::errorMessage, this, &DolphinView::errorMessage); + connect(m_model, &KFileItemModel::directoryRedirection, this, &DolphinView::slotDirectoryRedirection); + connect(m_model, &KFileItemModel::urlIsFileError, this, &DolphinView::urlIsFileError); + + m_view->installEventFilter(this); + connect(m_view, &DolphinItemListView::sortOrderChanged, + this, &DolphinView::slotSortOrderChangedByHeader); + connect(m_view, &DolphinItemListView::sortRoleChanged, + this, &DolphinView::slotSortRoleChangedByHeader); + connect(m_view, &DolphinItemListView::visibleRolesChanged, + this, &DolphinView::slotVisibleRolesChangedByHeader); + connect(m_view, &DolphinItemListView::roleEditingCanceled, + this, &DolphinView::slotRoleEditingCanceled); + connect(m_view->header(), &KItemListHeader::columnWidthChangeFinished, + this, &DolphinView::slotHeaderColumnWidthChangeFinished); + + KItemListSelectionManager* selectionManager = controller->selectionManager(); + connect(selectionManager, &KItemListSelectionManager::selectionChanged, + this, &DolphinView::slotSelectionChanged); + + m_toolTipManager = new ToolTipManager(this); + connect(m_toolTipManager, &ToolTipManager::urlActivated, this, &DolphinView::urlActivated); + + m_versionControlObserver = new VersionControlObserver(this); + m_versionControlObserver->setModel(m_model); + connect(m_versionControlObserver, &VersionControlObserver::infoMessage, this, &DolphinView::infoMessage); + connect(m_versionControlObserver, &VersionControlObserver::errorMessage, this, &DolphinView::errorMessage); + connect(m_versionControlObserver, &VersionControlObserver::operationCompletedMessage, this, &DolphinView::operationCompletedMessage); + + m_twoClicksRenamingTimer = new QTimer(this); + m_twoClicksRenamingTimer->setSingleShot(true); + connect(m_twoClicksRenamingTimer, &QTimer::timeout, this, &DolphinView::slotTwoClicksRenamingTimerTimeout); applyViewProperties(); - m_topLayout->addWidget(m_viewAccessor.layoutTarget()); -} + m_topLayout->addWidget(m_container); -DolphinView::~DolphinView() -{ + loadDirectory(url); } -KUrl DolphinView::url() const +DolphinView::~DolphinView() { - return m_viewModeController->url(); } -KUrl DolphinView::rootUrl() const +QUrl DolphinView::url() const { - const KUrl viewUrl = url(); - const KUrl root = m_viewAccessor.rootUrl(); - if (root.isEmpty() || !root.isParentOf(viewUrl)) { - return viewUrl; - } - return root; + return m_url; } void DolphinView::setActive(bool active) @@ -171,26 +219,13 @@ void DolphinView::setActive(bool active) m_active = active; - QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color(); - if (!active) { - color.setAlpha(150); - } - - QWidget* viewport = m_viewAccessor.itemView()->viewport(); - QPalette palette; - palette.setColor(viewport->backgroundRole(), color); - viewport->setPalette(palette); - - update(); + updatePalette(); if (active) { - m_viewAccessor.itemView()->setFocus(); + m_container->setFocus(); emit activated(); - emitSelectionChangedSignal(); emit writeStateChanged(m_isFolderWritable); } - - m_viewModeController->indicateActivationChange(active); } bool DolphinView::isActive() const @@ -200,165 +235,182 @@ bool DolphinView::isActive() const void DolphinView::setMode(Mode mode) { - if (mode == m_mode) { - return; // the wished mode is already set + if (mode != m_mode) { + ViewProperties props(viewPropertiesUrl()); + props.setViewMode(mode); + + // We pass the new ViewProperties to applyViewProperties, rather than + // storing them on disk and letting applyViewProperties() read them + // from there, to prevent that changing the view mode fails if the + // .directory file is not writable (see bug 318534). + applyViewProperties(props); } +} - const int oldZoomLevel = m_viewModeController->zoomLevel(); - m_mode = mode; +DolphinView::Mode DolphinView::mode() const +{ + return m_mode; +} - // remember the currently selected items, so that they will - // be restored after reloading the directory - m_selectedItems = selectedItems(); +void DolphinView::setPreviewsShown(bool show) +{ + if (previewsShown() == show) { + return; + } - const bool hasFocus = m_viewAccessor.itemView()->hasFocus(); - deleteView(); + ViewProperties props(viewPropertiesUrl()); + props.setPreviewsShown(show); - const KUrl viewPropsUrl = rootUrl(); - ViewProperties props(viewPropsUrl); - props.setViewMode(m_mode); - createView(); + const int oldZoomLevel = m_view->zoomLevel(); + m_view->setPreviewsShown(show); + emit previewsShownChanged(show); - if (hasFocus) { - m_viewAccessor.itemView()->setFocus(); + const int newZoomLevel = m_view->zoomLevel(); + if (newZoomLevel != oldZoomLevel) { + emit zoomLevelChanged(newZoomLevel, oldZoomLevel); } +} - // the file item delegate has been recreated, apply the current - // additional information manually - const KFileItemDelegate::InformationList infoList = props.additionalInfo(); - m_viewAccessor.itemDelegate()->setShowInformation(infoList); - emit additionalInfoChanged(); +bool DolphinView::previewsShown() const +{ + return m_view->previewsShown(); +} - // Not all view modes support categorized sorting. Adjust the sorting model - // if changing the view mode results in a change of the categorized sorting - // capabilities. - m_storedCategorizedSorting = props.categorizedSorting(); - const bool categorized = m_storedCategorizedSorting && supportsCategorizedSorting(); - if (categorized != m_viewAccessor.proxyModel()->isCategorizedModel()) { - m_viewAccessor.proxyModel()->setCategorizedModel(categorized); - emit categorizedSortingChanged(); +void DolphinView::setHiddenFilesShown(bool show) +{ + if (m_model->showHiddenFiles() == show) { + return; } - emit modeChanged(); + const KFileItemList itemList = selectedItems(); + m_selectedUrls.clear(); + m_selectedUrls = itemList.urlList(); - updateZoomLevel(oldZoomLevel); - loadDirectory(viewPropsUrl); -} + ViewProperties props(viewPropertiesUrl()); + props.setHiddenFilesShown(show); -DolphinView::Mode DolphinView::mode() const -{ - return m_mode; + m_model->setShowHiddenFiles(show); + emit hiddenFilesShownChanged(show); } -bool DolphinView::showPreview() const +bool DolphinView::hiddenFilesShown() const { - return m_showPreview; + return m_model->showHiddenFiles(); } -bool DolphinView::showHiddenFiles() const +void DolphinView::setGroupedSorting(bool grouped) { - return m_viewAccessor.dirLister()->showingDotFiles(); + if (grouped == groupedSorting()) { + return; + } + + ViewProperties props(viewPropertiesUrl()); + props.setGroupedSorting(grouped); + props.save(); + + m_container->controller()->model()->setGroupedSorting(grouped); + + emit groupedSortingChanged(grouped); } -bool DolphinView::categorizedSorting() const +bool DolphinView::groupedSorting() const { - // If all view modes would support categorized sorting, returning - // m_viewAccessor.proxyModel()->isCategorizedModel() would be the way to go. As - // currently only the icons view supports caterized sorting, we remember - // the stored view properties state in m_storedCategorizedSorting and - // return this state. The application takes care to disable the corresponding - // checkbox by checking DolphinView::supportsCategorizedSorting() to indicate - // that this setting is not applied to the current view mode. - return m_storedCategorizedSorting; + return m_model->groupedSorting(); } -bool DolphinView::supportsCategorizedSorting() const +KFileItemList DolphinView::items() const { - return m_viewAccessor.supportsCategorizedSorting(); + KFileItemList list; + const int itemCount = m_model->count(); + list.reserve(itemCount); + + for (int i = 0; i < itemCount; ++i) { + list.append(m_model->fileItem(i)); + } + + return list; } -KFileItemList DolphinView::items() const +int DolphinView::itemsCount() const { - return m_viewAccessor.dirLister()->items(); + return m_model->count(); } KFileItemList DolphinView::selectedItems() const { - KFileItemList itemList; - const QAbstractItemView* view = m_viewAccessor.itemView(); - if (view == 0) { - return itemList; - } - - const QItemSelection selection = m_viewAccessor.proxyModel()->mapSelectionToSource(view->selectionModel()->selection()); + const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); - const QModelIndexList indexList = selection.indexes(); - foreach (const QModelIndex &index, indexList) { - KFileItem item = m_viewAccessor.dirModel()->itemForIndex(index); - if (!item.isNull()) { - itemList.append(item); - } + KFileItemList selectedItems; + const auto items = selectionManager->selectedItems(); + selectedItems.reserve(items.count()); + for (int index : items) { + selectedItems.append(m_model->fileItem(index)); } - - return itemList; + return selectedItems; } int DolphinView::selectedItemsCount() const { - const QAbstractItemView* view = m_viewAccessor.itemView(); - if (view == 0) { - return 0; - } - - return view->selectionModel()->selectedIndexes().count(); + const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + return selectionManager->selectedItems().count(); } -void DolphinView::markUrlsAsSelected(const QList& urls) +void DolphinView::markUrlsAsSelected(const QList& urls) { - foreach (const KUrl& url, urls) { - KFileItem item(KFileItem::Unknown, KFileItem::Unknown, url); - m_selectedItems.append(item); - } + m_selectedUrls = urls; } -void DolphinView::setItemSelectionEnabled(const QRegExp& pattern, bool enabled) +void DolphinView::markUrlAsCurrent(const QUrl &url) { - const QItemSelection matchingIndexes = childrenMatchingPattern(QModelIndex(), pattern); - const QItemSelectionModel::SelectionFlags command = enabled - ? QItemSelectionModel::Select - : QItemSelectionModel::Deselect; - m_viewAccessor.itemView()->selectionModel()->select(matchingIndexes, command); + m_currentItemUrl = url; + m_scrollToCurrentItem = true; } -void DolphinView::setZoomLevel(int level) +void DolphinView::selectItems(const QRegExp& pattern, bool enabled) { - if (level < ZoomLevelInfo::minimumLevel()) { - level = ZoomLevelInfo::minimumLevel(); - } else if (level > ZoomLevelInfo::maximumLevel()) { - level = ZoomLevelInfo::maximumLevel(); + const KItemListSelectionManager::SelectionMode mode = enabled + ? KItemListSelectionManager::Select + : KItemListSelectionManager::Deselect; + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + + for (int index = 0; index < m_model->count(); index++) { + const KFileItem item = m_model->fileItem(index); + if (pattern.exactMatch(item.text())) { + // An alternative approach would be to store the matching items in a KItemSet and + // select them in one go after the loop, but we'd need a new function + // KItemListSelectionManager::setSelected(KItemSet, SelectionMode mode) + // for that. + selectionManager->setSelected(index, 1, mode); + } } +} - if (level != zoomLevel()) { - m_viewModeController->setZoomLevel(level); - emit zoomLevelChanged(level); +void DolphinView::setZoomLevel(int level) +{ + const int oldZoomLevel = zoomLevel(); + m_view->setZoomLevel(level); + if (zoomLevel() != oldZoomLevel) { + hideToolTip(); + emit zoomLevelChanged(zoomLevel(), oldZoomLevel); } } int DolphinView::zoomLevel() const { - return m_viewModeController->zoomLevel(); + return m_view->zoomLevel(); } -void DolphinView::setSorting(Sorting sorting) +void DolphinView::setSortRole(const QByteArray& role) { - if (sorting != this->sorting()) { - updateSorting(sorting); + if (role != sortRole()) { + updateSortRole(role); } } -DolphinView::Sorting DolphinView::sorting() const +QByteArray DolphinView::sortRole() const { - return m_viewAccessor.proxyModel()->sorting(); + const KItemModelBase* model = m_container->controller()->model(); + return model->sortRole(); } void DolphinView::setSortOrder(Qt::SortOrder order) @@ -370,7 +422,7 @@ void DolphinView::setSortOrder(Qt::SortOrder order) Qt::SortOrder DolphinView::sortOrder() const { - return m_viewAccessor.proxyModel()->sortOrder(); + return m_model->sortOrder(); } void DolphinView::setSortFoldersFirst(bool foldersFirst) @@ -382,26 +434,25 @@ void DolphinView::setSortFoldersFirst(bool foldersFirst) bool DolphinView::sortFoldersFirst() const { - return m_viewAccessor.proxyModel()->sortFoldersFirst(); + return m_model->sortDirectoriesFirst(); } -void DolphinView::setAdditionalInfo(KFileItemDelegate::InformationList info) +void DolphinView::setVisibleRoles(const QList& roles) { - const KUrl viewPropsUrl = rootUrl(); - ViewProperties props(viewPropsUrl); - props.setAdditionalInfo(info); - m_viewAccessor.itemDelegate()->setShowInformation(info); + const QList previousRoles = roles; - emit additionalInfoChanged(); + ViewProperties props(viewPropertiesUrl()); + props.setVisibleRoles(roles); - if (m_viewAccessor.reloadOnAdditionalInfoChange()) { - loadDirectory(viewPropsUrl); - } + m_visibleRoles = roles; + m_view->setVisibleRoles(roles); + + emit visibleRolesChanged(m_visibleRoles, previousRoles); } -KFileItemDelegate::InformationList DolphinView::additionalInfo() const +QList DolphinView::visibleRoles() const { - return m_viewAccessor.itemDelegate()->showInformation(); + return m_visibleRoles; } void DolphinView::reload() @@ -409,7 +460,6 @@ void DolphinView::reload() QByteArray viewState; QDataStream saveStream(&viewState, QIODevice::WriteOnly); saveState(saveStream); - m_selectedItems= selectedItems(); setUrl(url()); loadDirectory(url(), true); @@ -418,207 +468,226 @@ void DolphinView::reload() restoreState(restoreStream); } -void DolphinView::stopLoading() +void DolphinView::readSettings() { - m_viewAccessor.dirLister()->stop(); + const int oldZoomLevel = m_view->zoomLevel(); + + GeneralSettings::self()->load(); + m_view->readSettings(); + applyViewProperties(); + + const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1; + m_container->controller()->setAutoActivationDelay(delay); + + const int newZoomLevel = m_view->zoomLevel(); + if (newZoomLevel != oldZoomLevel) { + emit zoomLevelChanged(newZoomLevel, oldZoomLevel); + } } -void DolphinView::refresh() +void DolphinView::writeSettings() { - const bool oldActivationState = m_active; - const int oldZoomLevel = m_viewModeController->zoomLevel(); - m_active = true; + GeneralSettings::self()->save(); + m_view->writeSettings(); +} - createView(); - applyViewProperties(); - reload(); +void DolphinView::setNameFilter(const QString& nameFilter) +{ + m_model->setNameFilter(nameFilter); +} - setActive(oldActivationState); - updateZoomLevel(oldZoomLevel); +QString DolphinView::nameFilter() const +{ + return m_model->nameFilter(); } -void DolphinView::setNameFilter(const QString& nameFilter) +void DolphinView::setMimeTypeFilters(const QStringList& filters) { - m_viewModeController->setNameFilter(nameFilter); + return m_model->setMimeTypeFilters(filters); } -void DolphinView::calculateItemCount(int& fileCount, - int& folderCount, - KIO::filesize_t& totalFileSize) const +QStringList DolphinView::mimeTypeFilters() const { - foreach (const KFileItem& item, m_viewAccessor.dirLister()->items()) { - if (item.isDir()) { - ++folderCount; - } else { - ++fileCount; - totalFileSize += item.size(); - } - } + return m_model->mimeTypeFilters(); } QString DolphinView::statusBarText() const { - QString text; + QString summary; + QString foldersText; + QString filesText; + int folderCount = 0; int fileCount = 0; KIO::filesize_t totalFileSize = 0; - if (hasSelection()) { - // give a summary of the status of the selected files + if (m_container->controller()->selectionManager()->hasSelection()) { + // Give a summary of the status of the selected files const KFileItemList list = selectedItems(); - if (list.isEmpty()) { - // when an item is triggered, it is temporary selected but selectedItems() - // will return an empty list - return text; - } - - KFileItemList::const_iterator it = list.begin(); - const KFileItemList::const_iterator end = list.end(); - while (it != end) { - const KFileItem& item = *it; + foreach (const KFileItem& item, list) { if (item.isDir()) { ++folderCount; } else { ++fileCount; totalFileSize += item.size(); } - ++it; } if (folderCount + fileCount == 1) { - // if only one item is selected, show the filename - const QString name = list.first().text(); - text = (folderCount == 1) ? i18nc("@info:status", "%1 selected", name) : - i18nc("@info:status", "%1 selected (%2)", - name, KIO::convertSize(totalFileSize)); + // If only one item is selected, show info about it + return list.first().getStatusBarInfo(); } else { - // at least 2 items are selected - const QString foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount); - const QString filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount); - if ((folderCount > 0) && (fileCount > 0)) { - text = i18nc("@info:status folders, files (size)", "%1, %2 (%3)", - foldersText, filesText, KIO::convertSize(totalFileSize)); - } else if (fileCount > 0) { - text = i18nc("@info:status files (size)", "%1 (%2)", filesText, KIO::convertSize(totalFileSize)); - } else { - Q_ASSERT(folderCount > 0); - text = foldersText; - } + // At least 2 items are selected + foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount); + filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount); } } else { calculateItemCount(fileCount, folderCount, totalFileSize); - text = KIO::itemsSummaryString(fileCount + folderCount, - fileCount, folderCount, - totalFileSize, true); + foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount); + filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount); + } + + if (fileCount > 0 && folderCount > 0) { + summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)", + foldersText, filesText, + KFormat().formatByteSize(totalFileSize)); + } else if (fileCount > 0) { + summary = i18nc("@info:status files (size)", "%1 (%2)", + filesText, + KFormat().formatByteSize(totalFileSize)); + } else if (folderCount > 0) { + summary = foldersText; + } else { + summary = i18nc("@info:status", "0 Folders, 0 Files"); } - return text; + return summary; } QList DolphinView::versionControlActions(const KFileItemList& items) const { - return m_dolphinViewController->versionControlActions(items); + QList actions; + + if (items.isEmpty()) { + const KFileItem item = m_model->rootItem(); + if (!item.isNull()) { + actions = m_versionControlObserver->actions(KFileItemList() << item); + } + } else { + actions = m_versionControlObserver->actions(items); + } + + return actions; } -void DolphinView::setUrl(const KUrl& url) +void DolphinView::setUrl(const QUrl& url) { - if (m_viewModeController->url() == url) { + if (url == m_url) { return; } - const bool hadSelection = hasSelection(); - - // The selection model and directory lister might change in the case of the column view: - disconnectViewAccessor(); + clearSelection(); - m_newFileNames.clear(); + m_url = url; - m_viewModeController->setUrl(url); // emits urlChanged, which we forward - m_viewAccessor.prepareUrlChange(url); - applyViewProperties(); + hideToolTip(); - // When changing the URL there is no need to keep the version - // data of the previous URL. - m_viewAccessor.dirModel()->clearVersionData(); + disconnect(m_view, &DolphinItemListView::roleEditingFinished, + this, &DolphinView::slotRoleEditingFinished); - // Reconnect to the (probably) new selection model and directory lister - connectViewAccessor(); + // It is important to clear the items from the model before + // applying the view properties, otherwise expensive operations + // might be done on the existing items although they get cleared + // anyhow afterwards by loadDirectory(). + m_model->clear(); + applyViewProperties(); loadDirectory(url); - if (hadSelection || hasSelection()) { - emitSelectionChangedSignal(); - } + emit urlChanged(url); } void DolphinView::selectAll() { - m_viewAccessor.itemView()->selectAll(); + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + selectionManager->setSelected(0, m_model->count()); } void DolphinView::invertSelection() { - QItemSelectionModel* selectionModel = m_viewAccessor.itemView()->selectionModel(); - const QAbstractItemModel* itemModel = selectionModel->model(); - - const QModelIndex topLeft = itemModel->index(0, 0); - const QModelIndex bottomRight = itemModel->index(itemModel->rowCount() - 1, - itemModel->columnCount() - 1); - - const QItemSelection selection(topLeft, bottomRight); - selectionModel->select(selection, QItemSelectionModel::Toggle); + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle); } void DolphinView::clearSelection() { - m_viewAccessor.itemView()->clearSelection(); + m_selectedUrls.clear(); + m_container->controller()->selectionManager()->clearSelection(); } void DolphinView::renameSelectedItems() { - KFileItemList items = selectedItems(); - const int itemCount = items.count(); - if (itemCount < 1) { + const KFileItemList items = selectedItems(); + if (items.isEmpty()) { return; } - if ((itemCount == 1) && DolphinSettings::instance().generalSettings()->renameInline()) { - const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForItem(items.first()); - const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex); - m_viewAccessor.itemView()->edit(proxyIndex); + if (items.count() == 1 && GeneralSettings::renameInline()) { + const int index = m_model->index(items.first()); + m_view->editRole(index, "text"); + + hideToolTip(); + + connect(m_view, &DolphinItemListView::roleEditingFinished, + this, &DolphinView::slotRoleEditingFinished); } else { RenameDialog* dialog = new RenameDialog(this, items); + + connect(dialog, &RenameDialog::renamingFinished, this, &DolphinView::slotRenameDialogRenamingFinished); + dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); dialog->raise(); dialog->activateWindow(); } + + // Assure that the current index remains visible when KFileItemModel + // will notify the view about changed items (which might result in + // a changed sorting). + m_assureVisibleCurrentIndex = true; } void DolphinView::trashSelectedItems() { - const KUrl::List list = simplifiedSelectedUrls(); - KonqOperations::del(this, KonqOperations::TRASH, list); + const QList list = simplifiedSelectedUrls(); + KIO::JobUiDelegate uiDelegate; + uiDelegate.setWindow(window()); + if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Trash, KIO::JobUiDelegate::DefaultConfirmation)) { + KIO::Job* job = KIO::trash(list); + KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Trash, list, QUrl(QStringLiteral("trash:/")), job); + KJobWidgets::setWindow(job, this); + connect(job, &KIO::Job::result, + this, &DolphinView::slotTrashFileFinished); + } } void DolphinView::deleteSelectedItems() { - const KUrl::List list = simplifiedSelectedUrls(); - const bool del = KonqOperations::askDeleteConfirmation(list, - KonqOperations::DEL, - KonqOperations::DEFAULT_CONFIRMATION, - this); + const QList list = simplifiedSelectedUrls(); - if (del) { + KIO::JobUiDelegate uiDelegate; + uiDelegate.setWindow(window()); + if (uiDelegate.askDeleteConfirmation(list, KIO::JobUiDelegate::Delete, KIO::JobUiDelegate::DefaultConfirmation)) { KIO::Job* job = KIO::del(list); - connect(job, SIGNAL(result(KJob*)), - this, SLOT(slotDeleteFileFinished(KJob*))); + KJobWidgets::setWindow(job, this); + connect(job, &KIO::Job::result, + this, &DolphinView::slotDeleteFileFinished); } } void DolphinView::cutSelectedItems() { QMimeData* mimeData = selectionMimeData(); - KonqMimeData::addIsCutSelection(mimeData, true); + KIO::setClipboardDataCut(mimeData, true); QApplication::clipboard()->setMimeData(mimeData); } @@ -641,109 +710,73 @@ void DolphinView::pasteIntoFolder() } } -void DolphinView::setShowPreview(bool show) +void DolphinView::stopLoading() { - if (m_showPreview == show) { - return; - } - - const KUrl viewPropsUrl = rootUrl(); - ViewProperties props(viewPropsUrl); - props.setShowPreview(show); - - m_showPreview = show; - const int oldZoomLevel = m_viewModeController->zoomLevel(); - emit showPreviewChanged(); - - // Enabling or disabling the preview might change the icon size of the view. - // As the view does not emit a signal when the icon size has been changed, - // the used zoom level of the controller must be adjusted manually: - updateZoomLevel(oldZoomLevel); + m_model->cancelDirectoryLoading(); } -void DolphinView::setShowHiddenFiles(bool show) +void DolphinView::updatePalette() { - if (m_viewAccessor.dirLister()->showingDotFiles() == show) { - return; + QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color(); + if (!m_active) { + color.setAlpha(150); } - const KUrl viewPropsUrl = rootUrl(); - ViewProperties props(viewPropsUrl); - props.setShowHiddenFiles(show); - - m_viewAccessor.dirLister()->setShowingDotFiles(show); - emit showHiddenFilesChanged(); -} - -void DolphinView::setCategorizedSorting(bool categorized) -{ - if (categorized == categorizedSorting()) { - return; + QWidget* viewport = m_container->viewport(); + if (viewport) { + QPalette palette; + palette.setColor(viewport->backgroundRole(), color); + viewport->setPalette(palette); } - // setCategorizedSorting(true) may only get invoked - // if the view supports categorized sorting - Q_ASSERT(!categorized || supportsCategorizedSorting()); - - ViewProperties props(rootUrl()); - props.setCategorizedSorting(categorized); - props.save(); - - m_storedCategorizedSorting = categorized; - m_viewAccessor.proxyModel()->setCategorizedModel(categorized); - - emit categorizedSortingChanged(); + update(); } -void DolphinView::mouseReleaseEvent(QMouseEvent* event) +void DolphinView::abortTwoClicksRenaming() { - QWidget::mouseReleaseEvent(event); - setActive(true); + m_twoClicksRenamingItemUrl.clear(); + m_twoClicksRenamingTimer->stop(); } bool DolphinView::eventFilter(QObject* watched, QEvent* event) { switch (event->type()) { - case QEvent::FocusIn: - if (watched == m_viewAccessor.itemView()) { - m_dolphinViewController->requestActivation(); - } + case QEvent::PaletteChange: + updatePalette(); + QPixmapCache::clear(); break; - case QEvent::DragEnter: - if (watched == m_viewAccessor.itemView()->viewport()) { + case QEvent::KeyPress: + if (GeneralSettings::useTabForSwitchingSplitView()) { + QKeyEvent* keyEvent = static_cast(event); + if (keyEvent->key() == Qt::Key_Tab && keyEvent->modifiers() == Qt::NoModifier) { + emit toggleActiveViewRequested(); + return true; + } + } + break; + case QEvent::FocusIn: + if (watched == m_container) { setActive(true); } break; - case QEvent::KeyPress: - if (watched == m_viewAccessor.itemView()) { - // clear the selection when Escape has been pressed - QKeyEvent* keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Escape) { - clearSelection(); - } + case QEvent::GraphicsSceneDragEnter: + if (watched == m_view) { + m_dragging = true; } break; - case QEvent::Wheel: - if (watched == m_viewAccessor.itemView()->viewport()) { - // Ctrl+wheel events should cause icon zooming, but not if the left mouse button is pressed - // (the user is probably trying to scroll during a selection in that case) - QWheelEvent* wheelEvent = static_cast(event); - if (wheelEvent->modifiers() & Qt::ControlModifier && !(wheelEvent->buttons() & Qt::LeftButton)) { - const int delta = wheelEvent->delta(); - const int level = zoomLevel(); - if (delta > 0) { - setZoomLevel(level + 1); - } else if (delta < 0) { - setZoomLevel(level - 1); - } - return true; - } + case QEvent::GraphicsSceneDragLeave: + if (watched == m_view) { + m_dragging = false; } break; + case QEvent::GraphicsSceneDrop: + if (watched == m_view) { + m_dragging = false; + } default: break; } @@ -751,823 +784,1023 @@ bool DolphinView::eventFilter(QObject* watched, QEvent* event) return QWidget::eventFilter(watched, event); } -void DolphinView::activate() +void DolphinView::wheelEvent(QWheelEvent* event) { - setActive(true); + if (event->modifiers().testFlag(Qt::ControlModifier)) { + const int numDegrees = event->delta() / 8; + const int numSteps = numDegrees / 15; + + setZoomLevel(zoomLevel() + numSteps); + event->accept(); + } else { + event->ignore(); + } } -void DolphinView::triggerItem(const KFileItem& item) +void DolphinView::hideEvent(QHideEvent* event) { - const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers(); - if ((modifier & Qt::ShiftModifier) || (modifier & Qt::ControlModifier)) { - // items are selected by the user, hence don't trigger the - // item specified by 'index' - return; - } + hideToolTip(); + QWidget::hideEvent(event); +} - // TODO: the m_isContextMenuOpen check is a workaround for Qt-issue 207192 - if (item.isNull() || m_isContextMenuOpen) { - return; +bool DolphinView::event(QEvent* event) +{ + if (event->type() == QEvent::WindowDeactivate) { + /* See Bug 297355 + * Dolphin leaves file preview tooltips open even when is not visible. + * + * Hide tool-tip when Dolphin loses focus. + */ + hideToolTip(); + abortTwoClicksRenaming(); } - emit itemTriggered(item); // caught by DolphinViewContainer or DolphinPart + return QWidget::event(event); } -void DolphinView::slotSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) +void DolphinView::activate() { - const int count = selectedItemsCount(); - const bool selectionStateChanged = ((count > 0) && (selected.count() == count)) || - ((count == 0) && !deselected.isEmpty()); - - // If nothing has been selected before and something got selected (or if something - // was selected before and now nothing is selected) the selectionChangedSignal must - // be emitted asynchronously as fast as possible to update the edit-actions. - m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300); - m_selectionChangedTimer->start(); + setActive(true); } -void DolphinView::emitSelectionChangedSignal() +void DolphinView::slotItemActivated(int index) { - m_selectionChangedTimer->stop(); - emit selectionChanged(selectedItems()); + abortTwoClicksRenaming(); + + const KFileItem item = m_model->fileItem(index); + if (!item.isNull()) { + emit itemActivated(item); + } } -void DolphinView::openContextMenu(const QPoint& pos, - const QList& customActions) +void DolphinView::slotItemsActivated(const KItemSet& indexes) { - KFileItem item; - const QModelIndex index = m_viewAccessor.itemView()->indexAt(pos); - if (index.isValid() && (index.column() == DolphinModel::Name)) { - const QModelIndex dolphinModelIndex = m_viewAccessor.proxyModel()->mapToSource(index); - item = m_viewAccessor.dirModel()->itemForIndex(dolphinModelIndex); + Q_ASSERT(indexes.count() >= 2); + + abortTwoClicksRenaming(); + + if (indexes.count() > 5) { + QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count()); + const int answer = KMessageBox::warningYesNo(this, question); + if (answer != KMessageBox::Yes) { + return; + } + } + + KFileItemList items; + items.reserve(indexes.count()); + + for (int index : indexes) { + KFileItem item = m_model->fileItem(index); + const QUrl& url = openItemAsFolderUrl(item); + + if (!url.isEmpty()) { // Open folders in new tabs + emit tabRequested(url); + } else { + items.append(item); + } } - m_isContextMenuOpen = true; // TODO: workaround for Qt-issue 207192 - emit requestContextMenu(item, url(), customActions); - m_isContextMenuOpen = false; + if (items.count() == 1) { + emit itemActivated(items.first()); + } else if (items.count() > 1) { + emit itemsActivated(items); + } } -void DolphinView::dropUrls(const KFileItem& destItem, - const KUrl& destPath, - QDropEvent* event) +void DolphinView::slotItemMiddleClicked(int index) { - addNewFileNames(event->mimeData()); - DragAndDropHelper::instance().dropUrls(destItem, destPath, event, this); + const KFileItem& item = m_model->fileItem(index); + const QUrl& url = openItemAsFolderUrl(item); + if (!url.isEmpty()) { + emit tabRequested(url); + } else if (isTabsForFilesEnabled()) { + emit tabRequested(item.url()); + } } -void DolphinView::updateSorting(DolphinView::Sorting sorting) +void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos) { - ViewProperties props(rootUrl()); - props.setSorting(sorting); - - m_viewAccessor.proxyModel()->setSorting(sorting); + // Force emit of a selection changed signal before we request the + // context menu, to update the edit-actions first. (See Bug 294013) + if (m_selectionChangedTimer->isActive()) { + emitSelectionChangedSignal(); + } - emit sortingChanged(sorting); + const KFileItem item = m_model->fileItem(index); + emit requestContextMenu(pos.toPoint(), item, url(), QList()); } -void DolphinView::updateSortOrder(Qt::SortOrder order) +void DolphinView::slotViewContextMenuRequested(const QPointF& pos) { - ViewProperties props(rootUrl()); - props.setSortOrder(order); - - m_viewAccessor.proxyModel()->setSortOrder(order); - - emit sortOrderChanged(order); + emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList()); } -void DolphinView::updateSortFoldersFirst(bool foldersFirst) +void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos) { - ViewProperties props(rootUrl()); - props.setSortFoldersFirst(foldersFirst); + ViewProperties props(viewPropertiesUrl()); - m_viewAccessor.proxyModel()->setSortFoldersFirst(foldersFirst); + QPointer menu = new QMenu(QApplication::activeWindow()); - emit sortFoldersFirstChanged(foldersFirst); -} + KItemListView* view = m_container->controller()->view(); + const QSet visibleRolesSet = view->visibleRoles().toSet(); -void DolphinView::updateAdditionalInfo(const KFileItemDelegate::InformationList& info) -{ - ViewProperties props(rootUrl()); - props.setAdditionalInfo(info); - props.save(); + bool indexingEnabled = false; +#ifdef HAVE_BALOO + Baloo::IndexerConfig config; + indexingEnabled = config.fileIndexingEnabled(); +#endif - m_viewAccessor.itemDelegate()->setShowInformation(info); + QString groupName; + QMenu* groupMenu = 0; - emit additionalInfoChanged(); -} + // Add all roles to the menu that can be shown or hidden by the user + const QList rolesInfo = KFileItemModel::rolesInformation(); + foreach (const KFileItemModel::RoleInfo& info, rolesInfo) { + if (info.role == "text") { + // It should not be possible to hide the "text" role + continue; + } -void DolphinView::updateAdditionalInfoActions(KActionCollection* collection) -{ - const AdditionalInfoAccessor& infoAccessor = AdditionalInfoAccessor::instance(); + const QString text = m_model->roleDescription(info.role); + QAction* action = 0; + if (info.group.isEmpty()) { + action = menu->addAction(text); + } else { + if (!groupMenu || info.group != groupName) { + groupName = info.group; + groupMenu = menu->addMenu(groupName); + } - const KFileItemDelegate::InformationList checkedInfo = m_viewAccessor.itemDelegate()->showInformation(); - const KFileItemDelegate::InformationList infoKeys = infoAccessor.keys(); + action = groupMenu->addAction(text); + } - const bool enable = (m_mode == DolphinView::DetailsView) || - (m_mode == DolphinView::IconsView); + action->setCheckable(true); + action->setChecked(visibleRolesSet.contains(info.role)); + action->setData(info.role); - foreach (const KFileItemDelegate::Information& info, infoKeys) { - const QString name = infoAccessor.actionCollectionName(info, AdditionalInfoAccessor::AdditionalInfoType); - QAction* action = collection->action(name); - Q_ASSERT(action != 0); + const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || + (info.requiresBaloo) || + (info.requiresIndexer && indexingEnabled); action->setEnabled(enable); - action->setChecked(checkedInfo.contains(info)); } + + menu->addSeparator(); + + QActionGroup* widthsGroup = new QActionGroup(menu); + const bool autoColumnWidths = props.headerColumnWidths().isEmpty(); + + QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths")); + autoAdjustWidthsAction->setCheckable(true); + autoAdjustWidthsAction->setChecked(autoColumnWidths); + autoAdjustWidthsAction->setActionGroup(widthsGroup); + + QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths")); + customWidthsAction->setCheckable(true); + customWidthsAction->setChecked(!autoColumnWidths); + customWidthsAction->setActionGroup(widthsGroup); + + QAction* action = menu->exec(pos.toPoint()); + if (menu && action) { + KItemListHeader* header = view->header(); + + if (action == autoAdjustWidthsAction) { + // Clear the column-widths from the viewproperties and turn on + // the automatic resizing of the columns + props.setHeaderColumnWidths(QList()); + header->setAutomaticColumnResizing(true); + } else if (action == customWidthsAction) { + // Apply the current column-widths as custom column-widths and turn + // off the automatic resizing of the columns + QList columnWidths; + columnWidths.reserve(view->visibleRoles().count()); + foreach (const QByteArray& role, view->visibleRoles()) { + columnWidths.append(header->columnWidth(role)); + } + props.setHeaderColumnWidths(columnWidths); + header->setAutomaticColumnResizing(false); + } else { + // Show or hide the selected role + const QByteArray selectedRole = action->data().toByteArray(); + + QList visibleRoles = view->visibleRoles(); + if (action->isChecked()) { + visibleRoles.append(selectedRole); + } else { + visibleRoles.removeOne(selectedRole); + } + + view->setVisibleRoles(visibleRoles); + props.setVisibleRoles(visibleRoles); + + QList columnWidths; + if (!header->automaticColumnResizing()) { + columnWidths.reserve(view->visibleRoles().count()); + foreach (const QByteArray& role, view->visibleRoles()) { + columnWidths.append(header->columnWidth(role)); + } + } + props.setHeaderColumnWidths(columnWidths); + } + } + + delete menu; } -QPair DolphinView::pasteInfo() const +void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current) { - return KonqOperations::pasteInfo(url()); + const QList visibleRoles = m_view->visibleRoles(); + + ViewProperties props(viewPropertiesUrl()); + QList columnWidths = props.headerColumnWidths(); + if (columnWidths.count() != visibleRoles.count()) { + columnWidths.clear(); + columnWidths.reserve(visibleRoles.count()); + const KItemListHeader* header = m_view->header(); + foreach (const QByteArray& role, visibleRoles) { + const int width = header->columnWidth(role); + columnWidths.append(width); + } + } + + const int roleIndex = visibleRoles.indexOf(role); + Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count()); + columnWidths[roleIndex] = current; + + props.setHeaderColumnWidths(columnWidths); } -void DolphinView::setTabsForFilesEnabled(bool tabsForFiles) +void DolphinView::slotItemHovered(int index) { - m_tabsForFiles = tabsForFiles; + const KFileItem item = m_model->fileItem(index); + + if (GeneralSettings::showToolTips() && !m_dragging) { + QRectF itemRect = m_container->controller()->view()->itemContextRect(index); + const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint()); + itemRect.moveTo(pos); + + m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle()); + } + + emit requestItemInfo(item); } -bool DolphinView::isTabsForFilesEnabled() const +void DolphinView::slotItemUnhovered(int index) { - return m_tabsForFiles; + Q_UNUSED(index); + hideToolTip(); + emit requestItemInfo(KFileItem()); } -bool DolphinView::itemsExpandable() const +void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event) { - return m_viewAccessor.itemsExpandable(); + QUrl destUrl; + KFileItem destItem = m_model->fileItem(index); + if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) { + // Use the URL of the view as drop target if the item is no directory + // or desktop-file + destItem = m_model->rootItem(); + destUrl = url(); + } else { + // The item represents a directory or desktop-file + destUrl = destItem.mostLocalUrl(); + } + + QDropEvent dropEvent(event->pos().toPoint(), + event->possibleActions(), + event->mimeData(), + event->buttons(), + event->modifiers()); + dropUrls(destUrl, &dropEvent, this); + + setActive(true); } -void DolphinView::restoreState(QDataStream& stream) +void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget) { - // Restore the URL of the current item that had the keyboard focus - stream >> m_activeItemUrl; + KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget); - // Restore the root URL - KUrl rootUrl; - stream >> rootUrl; - m_viewAccessor.setRootUrl(rootUrl); - - // Restore the view position - stream >> m_restoredContentsPosition; + if (job) { + connect(job, &KIO::DropJob::result, this, &DolphinView::slotPasteJobResult); - // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes) - QSet urlsToExpand; - stream >> urlsToExpand; - const DolphinDetailsViewExpander* expander = m_viewAccessor.setExpandedUrls(urlsToExpand); - if (expander != 0) { - m_expanderActive = true; - connect (expander, SIGNAL(completed()), this, SLOT(slotLoadingCompleted())); - } - else { - m_expanderActive = false; + if (destUrl == url()) { + // Mark the dropped urls as selected. + m_clearSelectionBeforeSelectingNewItems = true; + m_markFirstNewlySelectedItemAsCurrent = true; + connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated); + } } } -void DolphinView::saveState(QDataStream& stream) +void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous) { - // Save the URL of the current item that has the keyboard focus - KFileItem currentItem; - const QAbstractItemView* view = m_viewAccessor.itemView(); - - if (view != 0) { - const QModelIndex proxyIndex = view->currentIndex(); - const QModelIndex dirModelIndex = m_viewAccessor.proxyModel()->mapToSource(proxyIndex); - currentItem = m_viewAccessor.dirModel()->itemForIndex(dirModelIndex); + if (previous != 0) { + Q_ASSERT(qobject_cast(previous)); + KFileItemModel* fileItemModel = static_cast(previous); + disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); + m_versionControlObserver->setModel(0); } - KUrl currentItemUrl; - if (!currentItem.isNull()) { - currentItemUrl = currentItem.url(); + if (current) { + Q_ASSERT(qobject_cast(current)); + KFileItemModel* fileItemModel = static_cast(current); + connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); + m_versionControlObserver->setModel(fileItemModel); } +} - stream << currentItemUrl; - - // Save the root URL - stream << m_viewAccessor.rootUrl(); +void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons) +{ + Q_UNUSED(itemIndex); - // Save view position - const int x = view->horizontalScrollBar()->value(); - const int y = view->verticalScrollBar()->value(); - stream << QPoint(x, y); + hideToolTip(); - // Save expanded folders (only relevant for the details view - the set will be empty in other view modes) - stream << m_viewAccessor.expandedUrls(); + if (buttons & Qt::BackButton) { + emit goBackRequested(); + } else if (buttons & Qt::ForwardButton) { + emit goForwardRequested(); + } } -bool DolphinView::hasSelection() const +void DolphinView::slotSelectedItemTextPressed(int index) { - const QAbstractItemView* view = m_viewAccessor.itemView(); - return (view != 0) && view->selectionModel()->hasSelection(); + if (GeneralSettings::renameInline()) { + m_twoClicksRenamingItemUrl = m_model->fileItem(index).url(); + m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval()); + } } -void DolphinView::observeCreatedItem(const KUrl& url) +void DolphinView::slotItemCreated(const QUrl& url) { - m_createdItemUrl = url; - connect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)), - this, SLOT(selectAndScrollToCreatedItem())); + if (m_markFirstNewlySelectedItemAsCurrent) { + markUrlAsCurrent(url); + m_markFirstNewlySelectedItemAsCurrent = false; + } + m_selectedUrls << url; } -void DolphinView::selectAndScrollToCreatedItem() +void DolphinView::slotPasteJobResult(KJob *job) { - const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForUrl(m_createdItemUrl); - if (dirIndex.isValid()) { - const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex); - m_viewAccessor.itemView()->setCurrentIndex(proxyIndex); + if (job->error()) { + emit errorMessage(job->errorString()); } + if (!m_selectedUrls.isEmpty()) { + m_selectedUrls << KDirModel::simplifiedUrlList(m_selectedUrls); + } +} - disconnect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)), - this, SLOT(selectAndScrollToCreatedItem())); - m_createdItemUrl = KUrl(); +void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous) +{ + const int currentCount = current.count(); + const int previousCount = previous.count(); + const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || + (currentCount > 0 && previousCount == 0); + + // If nothing has been selected before and something got selected (or if something + // was selected before and now nothing is selected) the selectionChangedSignal must + // be emitted asynchronously as fast as possible to update the edit-actions. + m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300); + m_selectionChangedTimer->start(); } -void DolphinView::slotRedirection(const KUrl& oldUrl, const KUrl& newUrl) +void DolphinView::emitSelectionChangedSignal() { - if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) { - emit redirection(oldUrl, newUrl); - m_viewModeController->redirectToUrl(newUrl); // #186947 - } + m_selectionChangedTimer->stop(); + emit selectionChanged(selectedItems()); } -void DolphinView::restoreContentsPosition() +void DolphinView::updateSortRole(const QByteArray& role) { - if (!m_restoredContentsPosition.isNull()) { - const int x = m_restoredContentsPosition.x(); - const int y = m_restoredContentsPosition.y(); - m_restoredContentsPosition = QPoint(); + ViewProperties props(viewPropertiesUrl()); + props.setSortRole(role); - QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT(view != 0); - view->horizontalScrollBar()->setValue(x); - view->verticalScrollBar()->setValue(y); - } + KItemModelBase* model = m_container->controller()->model(); + model->setSortRole(role); + + emit sortRoleChanged(role); } -void DolphinView::slotUrlChangeRequested(const KUrl& url) +void DolphinView::updateSortOrder(Qt::SortOrder order) { - m_viewModeController->setUrl(url); - updateWritableState(); + ViewProperties props(viewPropertiesUrl()); + props.setSortOrder(order); + + m_model->setSortOrder(order); + + emit sortOrderChanged(order); } -void DolphinView::showHoverInformation(const KFileItem& item) +void DolphinView::updateSortFoldersFirst(bool foldersFirst) { - emit requestItemInfo(item); + ViewProperties props(viewPropertiesUrl()); + props.setSortFoldersFirst(foldersFirst); + + m_model->setSortDirectoriesFirst(foldersFirst); + + emit sortFoldersFirstChanged(foldersFirst); } -void DolphinView::clearHoverInformation() +QPair DolphinView::pasteInfo() const { - emit requestItemInfo(KFileItem()); + const QMimeData *mimeData = QApplication::clipboard()->mimeData(); + QPair info; + info.second = KIO::pasteActionText(mimeData, &info.first, rootItem()); + return info; } -void DolphinView::slotDeleteFileFinished(KJob* job) +void DolphinView::setTabsForFilesEnabled(bool tabsForFiles) { - if (job->error() == 0) { - emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed.")); - } else if (job->error() != KIO::ERR_USER_CANCELED) { - emit errorMessage(job->errorString()); - } + m_tabsForFiles = tabsForFiles; } -void DolphinView::slotDirListerStarted(const KUrl& url) +bool DolphinView::isTabsForFilesEnabled() const { - // Disable the writestate temporary until it can be determined in a fast way - // in DolphinView::slotDirListerCompleted() - if (m_isFolderWritable) { - m_isFolderWritable = false; - emit writeStateChanged(m_isFolderWritable); - } + return m_tabsForFiles; +} - emit startedPathLoading(url); +bool DolphinView::itemsExpandable() const +{ + return m_mode == DetailsView; } -void DolphinView::slotDirListerCompleted() +void DolphinView::restoreState(QDataStream& stream) { - if (!m_expanderActive) { - slotLoadingCompleted(); + // Read the version number of the view state and check if the version is supported. + quint32 version = 0; + stream >> version; + if (version != 1) { + // The version of the view state isn't supported, we can't restore it. + return; } - if (!m_newFileNames.isEmpty()) { - // select all newly added items created by a paste operation or - // a drag & drop operation, and clear the previous selection - m_viewAccessor.itemView()->clearSelection(); - const int rowCount = m_viewAccessor.proxyModel()->rowCount(); - QItemSelection selection; - for (int row = 0; row < rowCount; ++row) { - const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->index(row, 0); - const QModelIndex dirIndex = m_viewAccessor.proxyModel()->mapToSource(proxyIndex); - const KUrl url = m_viewAccessor.dirModel()->itemForIndex(dirIndex).url(); - if (m_newFileNames.contains(url.fileName())) { - selection.merge(QItemSelection(proxyIndex, proxyIndex), QItemSelectionModel::Select); - } - } - m_viewAccessor.itemView()->selectionModel()->select(selection, QItemSelectionModel::Select); + // Restore the current item that had the keyboard focus + stream >> m_currentItemUrl; - m_newFileNames.clear(); - } + // Restore the previously selected items + stream >> m_selectedUrls; - updateWritableState(); + // Restore the view position + stream >> m_restoredContentsPosition; + + // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes) + QSet urls; + stream >> urls; + m_model->restoreExpandedDirectories(urls); } -void DolphinView::slotLoadingCompleted() +void DolphinView::saveState(QDataStream& stream) { - m_expanderActive = false; + stream << quint32(1); // View state version - if (!m_activeItemUrl.isEmpty()) { - // assure that the current item remains visible - const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForUrl(m_activeItemUrl); - if (dirIndex.isValid()) { - const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex); - QAbstractItemView* view = m_viewAccessor.itemView(); - const bool clearSelection = !hasSelection(); - view->setCurrentIndex(proxyIndex); - if (clearSelection) { - view->clearSelection(); - } - m_activeItemUrl.clear(); - } + // Save the current item that has the keyboard focus + const int currentIndex = m_container->controller()->selectionManager()->currentItem(); + if (currentIndex != -1) { + KFileItem item = m_model->fileItem(currentIndex); + Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist + QUrl currentItemUrl = item.url(); + stream << currentItemUrl; + } else { + stream << QUrl(); } - if (!m_selectedItems.isEmpty()) { - const KUrl& baseUrl = url(); - KUrl url; - QItemSelection newSelection; - foreach(const KFileItem& item, m_selectedItems) { - url = item.url().upUrl(); - if (baseUrl.equals(url, KUrl::CompareWithoutTrailingSlash)) { - QModelIndex index = m_viewAccessor.proxyModel()->mapFromSource(m_viewAccessor.dirModel()->indexForItem(item)); - newSelection.select(index, index); - } - } - m_viewAccessor.itemView()->selectionModel()->select(newSelection, - QItemSelectionModel::ClearAndSelect - | QItemSelectionModel::Current); - m_selectedItems.clear(); - } + // Save the selected urls + stream << selectedItems().urlList(); - // Restore the contents position. This has to be done using a Qt::QueuedConnection - // because the view might not be in its final state yet. - QMetaObject::invokeMethod(this, "restoreContentsPosition", Qt::QueuedConnection); + // Save view position + const qreal x = m_container->horizontalScrollBar()->value(); + const qreal y = m_container->verticalScrollBar()->value(); + stream << QPoint(x, y); - emit finishedPathLoading(url()); + // Save expanded folders (only relevant for the details view - the set will be empty in other view modes) + stream << m_model->expandedDirectories(); } -void DolphinView::slotRefreshItems() +KFileItem DolphinView::rootItem() const { - if (m_assureVisibleCurrentIndex) { - m_assureVisibleCurrentIndex = false; - m_viewAccessor.itemView()->scrollTo(m_viewAccessor.itemView()->currentIndex()); - } + return m_model->rootItem(); } -void DolphinView::loadDirectory(const KUrl& url, bool reload) +void DolphinView::setViewPropertiesContext(const QString& context) { - if (!url.isValid()) { - const QString location(url.pathOrUrl()); - if (location.isEmpty()) { - emit errorMessage(i18nc("@info:status", "The location is empty.")); - } else { - emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location)); - } - return; - } - - KDirLister* dirLister = m_viewAccessor.dirLister(); - dirLister->openUrl(url, reload ? KDirLister::Reload : KDirLister::NoFlags); + m_viewPropertiesContext = context; } -void DolphinView::applyViewProperties() +QString DolphinView::viewPropertiesContext() const { - const ViewProperties props(rootUrl()); + return m_viewPropertiesContext; +} - const Mode mode = props.viewMode(); - if (m_mode != mode) { - const int oldZoomLevel = m_viewModeController->zoomLevel(); +QUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives) +{ + if (item.isNull()) { + return QUrl(); + } - m_mode = mode; - createView(); - emit modeChanged(); + QUrl url = item.targetUrl(); - updateZoomLevel(oldZoomLevel); - } - if (m_viewAccessor.itemView() == 0) { - createView(); + if (item.isDir()) { + return url; } - Q_ASSERT(m_viewAccessor.itemView() != 0); - Q_ASSERT(m_viewAccessor.itemDelegate() != 0); + if (item.isMimeTypeKnown()) { + const QString& mimetype = item.mimetype(); - const bool showHiddenFiles = props.showHiddenFiles(); - if (showHiddenFiles != m_viewAccessor.dirLister()->showingDotFiles()) { - m_viewAccessor.dirLister()->setShowingDotFiles(showHiddenFiles); - emit showHiddenFilesChanged(); - } + if (browseThroughArchives && item.isFile() && url.isLocalFile()) { + // Generic mechanism for redirecting to tar:// when clicking on a tar file, + // zip:// when clicking on a zip file, etc. + // The .protocol file specifies the mimetype that the kioslave handles. + // Note that we don't use mimetype inheritance since we don't want to + // open OpenDocument files as zip folders... + const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype); + if (!protocol.isEmpty()) { + url.setScheme(protocol); + return url; + } + } - m_storedCategorizedSorting = props.categorizedSorting(); - const bool categorized = m_storedCategorizedSorting && supportsCategorizedSorting(); - if (categorized != m_viewAccessor.proxyModel()->isCategorizedModel()) { - m_viewAccessor.proxyModel()->setCategorizedModel(categorized); - emit categorizedSortingChanged(); + if (mimetype == QLatin1String("application/x-desktop")) { + // Redirect to the URL in Type=Link desktop files, unless it is a http(s) URL. + KDesktopFile desktopFile(url.toLocalFile()); + if (desktopFile.hasLinkType()) { + const QString linkUrl = desktopFile.readUrl(); + if (!linkUrl.startsWith(QLatin1String("http"))) { + return QUrl::fromUserInput(linkUrl); + } + } + } } - const DolphinView::Sorting sorting = props.sorting(); - if (sorting != m_viewAccessor.proxyModel()->sorting()) { - m_viewAccessor.proxyModel()->setSorting(sorting); - emit sortingChanged(sorting); - } + return QUrl(); +} - const Qt::SortOrder sortOrder = props.sortOrder(); - if (sortOrder != m_viewAccessor.proxyModel()->sortOrder()) { - m_viewAccessor.proxyModel()->setSortOrder(sortOrder); - emit sortOrderChanged(sortOrder); +void DolphinView::observeCreatedItem(const QUrl& url) +{ + if (m_active) { + forceUrlsSelection(url, {url}); } +} - const bool sortFoldersFirst = props.sortFoldersFirst(); - if (sortFoldersFirst != m_viewAccessor.proxyModel()->sortFoldersFirst()) { - m_viewAccessor.proxyModel()->setSortFoldersFirst(sortFoldersFirst); - emit sortFoldersFirstChanged(sortFoldersFirst); +void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl) +{ + if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) { + emit redirection(oldUrl, newUrl); + m_url = newUrl; // #186947 } +} - KFileItemDelegate::InformationList info = props.additionalInfo(); - if (info != m_viewAccessor.itemDelegate()->showInformation()) { - m_viewAccessor.itemDelegate()->setShowInformation(info); - emit additionalInfoChanged(); - } +void DolphinView::updateViewState() +{ + if (m_currentItemUrl != QUrl()) { + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const int currentIndex = m_model->index(m_currentItemUrl); + if (currentIndex != -1) { + selectionManager->setCurrentItem(currentIndex); - const bool showPreview = props.showPreview(); - if (showPreview != m_showPreview) { - m_showPreview = showPreview; - const int oldZoomLevel = m_viewModeController->zoomLevel(); - emit showPreviewChanged(); + // scroll to current item and reset the state + if (m_scrollToCurrentItem) { + m_view->scrollToItem(currentIndex); + m_scrollToCurrentItem = false; + } + } else { + selectionManager->setCurrentItem(0); + } - // Enabling or disabling the preview might change the icon size of the view. - // As the view does not emit a signal when the icon size has been changed, - // the used zoom level of the controller must be adjusted manually: - updateZoomLevel(oldZoomLevel); + m_currentItemUrl = QUrl(); } -} -void DolphinView::createView() -{ - deleteView(); + if (!m_restoredContentsPosition.isNull()) { + const int x = m_restoredContentsPosition.x(); + const int y = m_restoredContentsPosition.y(); + m_restoredContentsPosition = QPoint(); - Q_ASSERT(m_viewAccessor.itemView() == 0); - Q_ASSERT(m_dolphinViewController->itemView() == 0); - m_viewAccessor.createView(this, m_dolphinViewController, m_viewModeController, m_mode); + m_container->horizontalScrollBar()->setValue(x); + m_container->verticalScrollBar()->setValue(y); + } - QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT(view != 0); - view->installEventFilter(this); - view->viewport()->installEventFilter(this); + if (!m_selectedUrls.isEmpty()) { + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); - m_dolphinViewController->setItemView(view); + if (m_clearSelectionBeforeSelectingNewItems) { + selectionManager->clearSelection(); + m_clearSelectionBeforeSelectingNewItems = false; + } - const int zoomLevel = ZoomLevelInfo::zoomLevelForIconSize(view->iconSize()); - m_viewModeController->setZoomLevel(zoomLevel); + KItemSet selectedItems = selectionManager->selectedItems(); - connectViewAccessor(); + QList::iterator it = m_selectedUrls.begin(); + while (it != m_selectedUrls.end()) { + const int index = m_model->index(*it); + if (index >= 0) { + selectedItems.insert(index); + it = m_selectedUrls.erase(it); + } else { + ++it; + } + } - setFocusProxy(m_viewAccessor.layoutTarget()); - m_topLayout->insertWidget(1, m_viewAccessor.layoutTarget()); + selectionManager->beginAnchoredSelection(selectionManager->currentItem()); + selectionManager->setSelectedItems(selectedItems); + } } -void DolphinView::deleteView() +void DolphinView::hideToolTip() { - QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT((m_dolphinViewController->itemView() == 0) || (m_dolphinViewController->itemView() == view)); - m_dolphinViewController->setItemView(0); - - if (view != 0) { - disconnectViewAccessor(); + if (GeneralSettings::showToolTips()) { + m_toolTipManager->hideToolTip(); + } +} - if (hasFocus()) { - // It's important to set the keyboard focus to the parent - // before deleting the view: Otherwise when having a split - // view the other view will get the focus and will request - // an activation (see DolphinView::eventFilter()). - setFocusProxy(0); - setFocus(); +void DolphinView::calculateItemCount(int& fileCount, + int& folderCount, + KIO::filesize_t& totalFileSize) const +{ + const int itemCount = m_model->count(); + for (int i = 0; i < itemCount; ++i) { + const KFileItem item = m_model->fileItem(i); + if (item.isDir()) { + ++folderCount; + } else { + ++fileCount; + totalFileSize += item.size(); } + } +} + +void DolphinView::slotTwoClicksRenamingTimerTimeout() +{ + const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); - m_viewModeController->disconnect(view); + // verify that only one item is selected and that no item is dragged + if (selectionManager->selectedItems().count() == 1 && !m_dragging) { + const int index = selectionManager->currentItem(); + const QUrl fileItemUrl = m_model->fileItem(index).url(); - m_viewAccessor.deleteView(); + // check if the selected item was the same item that started the twoClicksRenaming + if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) { + renameSelectedItems(); + } } } -void DolphinView::pasteToUrl(const KUrl& url) +void DolphinView::slotTrashFileFinished(KJob* job) { - addNewFileNames(QApplication::clipboard()->mimeData()); - KonqOperations::doPaste(this, url); + if (job->error() == 0) { + emit operationCompletedMessage(i18nc("@info:status", "Trash operation completed.")); + } else if (job->error() != KIO::ERR_USER_CANCELED) { + emit errorMessage(job->errorString()); + } } -void DolphinView::updateZoomLevel(int oldZoomLevel) +void DolphinView::slotDeleteFileFinished(KJob* job) { - const int newZoomLevel = ZoomLevelInfo::zoomLevelForIconSize(m_viewAccessor.itemView()->iconSize()); - if (oldZoomLevel != newZoomLevel) { - m_viewModeController->setZoomLevel(newZoomLevel); - emit zoomLevelChanged(newZoomLevel); + if (job->error() == 0) { + emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed.")); + } else if (job->error() != KIO::ERR_USER_CANCELED) { + emit errorMessage(job->errorString()); } } -KUrl::List DolphinView::simplifiedSelectedUrls() const +void DolphinView::slotRenamingResult(KJob* job) { - KUrl::List urls; - - const KFileItemList items = selectedItems(); - foreach (const KFileItem &item, items) { - urls.append(item.url()); + if (job->error()) { + KIO::CopyJob *copyJob = qobject_cast(job); + Q_ASSERT(copyJob); + const QUrl newUrl = copyJob->destUrl(); + const int index = m_model->index(newUrl); + if (index >= 0) { + QHash data; + const QUrl oldUrl = copyJob->srcUrls().at(0); + data.insert("text", oldUrl.fileName()); + m_model->setData(index, data); + } } +} - - if (itemsExpandable()) { - urls = KDirModel::simplifiedUrlList(urls); +void DolphinView::slotDirectoryLoadingStarted() +{ + // Disable the writestate temporary until it can be determined in a fast way + // in DolphinView::slotLoadingCompleted() + if (m_isFolderWritable) { + m_isFolderWritable = false; + emit writeStateChanged(m_isFolderWritable); } - return urls; + emit directoryLoadingStarted(); } -QMimeData* DolphinView::selectionMimeData() const +void DolphinView::slotDirectoryLoadingCompleted() { - const QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT((view != 0) && (view->selectionModel() != 0)); - const QItemSelection selection = m_viewAccessor.proxyModel()->mapSelectionToSource(view->selectionModel()->selection()); - return m_viewAccessor.dirModel()->mimeData(selection.indexes()); + // Update the view-state. This has to be done asynchronously + // because the view might not be in its final state yet. + QTimer::singleShot(0, this, &DolphinView::updateViewState); + + emit directoryLoadingCompleted(); + + updateWritableState(); } -void DolphinView::addNewFileNames(const QMimeData* mimeData) +void DolphinView::slotItemsChanged() { - const KUrl::List urls = KUrl::List::fromMimeData(mimeData); - foreach (const KUrl& url, urls) { - m_newFileNames.insert(url.fileName()); - } + m_assureVisibleCurrentIndex = false; } -QItemSelection DolphinView::childrenMatchingPattern(const QModelIndex& parent, const QRegExp& pattern) const +void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous) { - QItemSelection matchingIndexes; - const DolphinSortFilterProxyModel* proxyModel = m_viewAccessor.proxyModel(); - const DolphinModel* dolphinModel = m_viewAccessor.dirModel(); + Q_UNUSED(previous); + Q_ASSERT(m_model->sortOrder() == current); - const int rowCount = proxyModel->rowCount(parent); + ViewProperties props(viewPropertiesUrl()); + props.setSortOrder(current); - for (int row = 0; row < rowCount; ++row) { - QModelIndex index = proxyModel->index(row, 0, parent); - QModelIndex sourceIndex = proxyModel->mapToSource(index); + emit sortOrderChanged(current); +} - if (sourceIndex.isValid() && pattern.exactMatch(dolphinModel->data(sourceIndex).toString())) { - matchingIndexes += QItemSelectionRange(index); - } +void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous) +{ + Q_UNUSED(previous); + Q_ASSERT(m_model->sortRole() == current); - if (proxyModel->hasChildren(index)) { - matchingIndexes += childrenMatchingPattern(index, pattern); - } - } + ViewProperties props(viewPropertiesUrl()); + props.setSortRole(current); - return matchingIndexes; + emit sortRoleChanged(current); } -void DolphinView::connectViewAccessor() +void DolphinView::slotVisibleRolesChangedByHeader(const QList& current, + const QList& previous) { - KDirLister* dirLister = m_viewAccessor.dirLister(); - connect(dirLister, SIGNAL(redirection(KUrl,KUrl)), - this, SLOT(slotRedirection(KUrl,KUrl))); - connect(dirLister, SIGNAL(started(KUrl)), - this, SLOT(slotDirListerStarted(KUrl))); - connect(dirLister, SIGNAL(completed()), - this, SLOT(slotDirListerCompleted())); - connect(dirLister, SIGNAL(refreshItems(const QList>&)), - this, SLOT(slotRefreshItems())); + Q_UNUSED(previous); + Q_ASSERT(m_container->controller()->view()->visibleRoles() == current); - QAbstractItemView* view = m_viewAccessor.itemView(); - connect(view->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), - this, SLOT(slotSelectionChanged(QItemSelection, QItemSelection))); + const QList previousVisibleRoles = m_visibleRoles; + + m_visibleRoles = current; + + ViewProperties props(viewPropertiesUrl()); + props.setVisibleRoles(m_visibleRoles); + + emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles); } -void DolphinView::disconnectViewAccessor() +void DolphinView::slotRoleEditingCanceled() { - KDirLister* dirLister = m_viewAccessor.dirLister(); - disconnect(dirLister, SIGNAL(redirection(KUrl,KUrl)), - this, SLOT(slotRedirection(KUrl,KUrl))); - disconnect(dirLister, SIGNAL(started(KUrl)), - this, SLOT(slotDirListerStarted(KUrl))); - disconnect(dirLister, SIGNAL(completed()), - this, SLOT(slotDirListerCompleted())); - disconnect(dirLister, SIGNAL(refreshItems(const QList>&)), - this, SLOT(slotRefreshItems())); - - QAbstractItemView* view = m_viewAccessor.itemView(); - disconnect(view->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), - this, SLOT(slotSelectionChanged(QItemSelection, QItemSelection))); + disconnect(m_view, &DolphinItemListView::roleEditingFinished, + this, &DolphinView::slotRoleEditingFinished); } -void DolphinView::updateWritableState() +void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value) { - const bool wasFolderWritable = m_isFolderWritable; - m_isFolderWritable = true; + disconnect(m_view, &DolphinItemListView::roleEditingFinished, + this, &DolphinView::slotRoleEditingFinished); - const KFileItem item = m_viewAccessor.dirLister()->rootItem(); - if (!item.isNull()) { - KFileItemListProperties capabilities(KFileItemList() << item); - m_isFolderWritable = capabilities.supportsWriting(); + if (index < 0 || index >= m_model->count()) { + return; } - if (m_isFolderWritable != wasFolderWritable) { - emit writeStateChanged(m_isFolderWritable); + + if (role == "text") { + const KFileItem oldItem = m_model->fileItem(index); + const QString newName = value.toString(); + if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1String(".") && newName != QLatin1String("..")) { + const QUrl oldUrl = oldItem.url(); + + QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename); + newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName)); + + const bool newNameExistsAlready = (m_model->index(newUrl) >= 0); + if (!newNameExistsAlready) { + // Only change the data in the model if no item with the new name + // is in the model yet. If there is an item with the new name + // already, calling KIO::CopyJob will open a dialog + // asking for a new name, and KFileItemModel will update the + // data when the dir lister signals that the file name has changed. + QHash data; + data.insert(role, value); + m_model->setData(index, data); + } + + KIO::Job * job = KIO::moveAs(oldUrl, newUrl); + KJobWidgets::setWindow(job, this); + KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Rename, {oldUrl}, newUrl, job); + job->uiDelegate()->setAutoErrorHandlingEnabled(true); + + forceUrlsSelection(newUrl, {newUrl}); + + if (!newNameExistsAlready) { + // Only connect the result signal if there is no item with the new name + // in the model yet, see bug 328262. + connect(job, &KJob::result, this, &DolphinView::slotRenamingResult); + } + } } } -DolphinView::ViewAccessor::ViewAccessor(DolphinSortFilterProxyModel* proxyModel) : - m_rootUrl(), - m_iconsView(0), - m_detailsView(0), - m_columnsContainer(0), - m_proxyModel(proxyModel), - m_dragSource(0) +void DolphinView::loadDirectory(const QUrl& url, bool reload) { + if (!url.isValid()) { + const QString location(url.toDisplayString(QUrl::PreferLocalFile)); + if (location.isEmpty()) { + emit errorMessage(i18nc("@info:status", "The location is empty.")); + } else { + emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location)); + } + return; + } + + if (reload) { + m_model->refreshDirectory(url); + } else { + m_model->loadDirectory(url); + } } -DolphinView::ViewAccessor::~ViewAccessor() +void DolphinView::applyViewProperties() { - delete m_dragSource; - m_dragSource = 0; + const ViewProperties props(viewPropertiesUrl()); + applyViewProperties(props); } -void DolphinView::ViewAccessor::createView(QWidget* parent, - DolphinViewController* dolphinViewController, - const ViewModeController* viewModeController, - Mode mode) +void DolphinView::applyViewProperties(const ViewProperties& props) { - Q_ASSERT(itemView() == 0); + m_view->beginTransaction(); - switch (mode) { - case IconsView: - m_iconsView = new DolphinIconsView(parent, - dolphinViewController, - viewModeController, - m_proxyModel); - break; + const Mode mode = props.viewMode(); + if (m_mode != mode) { + const Mode previousMode = m_mode; + m_mode = mode; - case DetailsView: - m_detailsView = new DolphinDetailsView(parent, - dolphinViewController, - viewModeController, - m_proxyModel); - break; + // Changing the mode might result in changing + // the zoom level. Remember the old zoom level so + // that zoomLevelChanged() can get emitted. + const int oldZoomLevel = m_view->zoomLevel(); + applyModeToView(); + + emit modeChanged(m_mode, previousMode); - case ColumnView: - m_columnsContainer = new DolphinColumnViewContainer(parent, - dolphinViewController, - viewModeController); - if (!m_rootUrl.isEmpty() && m_rootUrl.isParentOf(viewModeController->url())) { - // The column-view must show several columns starting with m_rootUrl as - // first column and viewModeController->url() as last column. - m_columnsContainer->showColumn(m_rootUrl); - m_columnsContainer->showColumn(viewModeController->url()); + if (m_view->zoomLevel() != oldZoomLevel) { + emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel); } - break; + } - default: - Q_ASSERT(false); + const bool hiddenFilesShown = props.hiddenFilesShown(); + if (hiddenFilesShown != m_model->showHiddenFiles()) { + m_model->setShowHiddenFiles(hiddenFilesShown); + emit hiddenFilesShownChanged(hiddenFilesShown); } -} -void DolphinView::ViewAccessor::deleteView() -{ - if (m_columnsContainer != 0) { - m_columnsContainer->close(); - m_columnsContainer->disconnect(); - m_columnsContainer->deleteLater(); - m_columnsContainer = 0; - } else { - QAbstractItemView* view = itemView(); - if (view != 0) { - view->close(); - view->disconnect(); - - if (DragAndDropHelper::instance().isDragSource(view)) { - // The view is a drag source (the feature "Open folders - // during drag operations" is used). Deleting the view - // during an ongoing drag operation is not allowed, so - // this will postponed. - if (m_dragSource != 0) { - // the old stored view is obviously not the drag source anymore - m_dragSource->deleteLater(); - m_dragSource = 0; - } - view->hide(); - m_dragSource = view; - } else { - view->deleteLater(); - view = 0; - } - } + const bool groupedSorting = props.groupedSorting(); + if (groupedSorting != m_model->groupedSorting()) { + m_model->setGroupedSorting(groupedSorting); + emit groupedSortingChanged(groupedSorting); + } - m_iconsView = 0; - m_detailsView = 0; + const QByteArray sortRole = props.sortRole(); + if (sortRole != m_model->sortRole()) { + m_model->setSortRole(sortRole); + emit sortRoleChanged(sortRole); } -} -void DolphinView::ViewAccessor::prepareUrlChange(const KUrl& url) -{ - if (m_columnsContainer != 0) { - m_columnsContainer->showColumn(url); + const Qt::SortOrder sortOrder = props.sortOrder(); + if (sortOrder != m_model->sortOrder()) { + m_model->setSortOrder(sortOrder); + emit sortOrderChanged(sortOrder); } -} -QAbstractItemView* DolphinView::ViewAccessor::itemView() const -{ - if (m_iconsView != 0) { - return m_iconsView; + const bool sortFoldersFirst = props.sortFoldersFirst(); + if (sortFoldersFirst != m_model->sortDirectoriesFirst()) { + m_model->setSortDirectoriesFirst(sortFoldersFirst); + emit sortFoldersFirstChanged(sortFoldersFirst); } - if (m_detailsView != 0) { - return m_detailsView; + const QList visibleRoles = props.visibleRoles(); + if (visibleRoles != m_visibleRoles) { + const QList previousVisibleRoles = m_visibleRoles; + m_visibleRoles = visibleRoles; + m_view->setVisibleRoles(visibleRoles); + emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles); } - if (m_columnsContainer != 0) { - return m_columnsContainer->activeColumn(); + const bool previewsShown = props.previewsShown(); + if (previewsShown != m_view->previewsShown()) { + const int oldZoomLevel = zoomLevel(); + + m_view->setPreviewsShown(previewsShown); + emit previewsShownChanged(previewsShown); + + // Changing the preview-state might result in a changed zoom-level + if (oldZoomLevel != zoomLevel()) { + emit zoomLevelChanged(zoomLevel(), oldZoomLevel); + } } - return 0; -} + KItemListView* itemListView = m_container->controller()->view(); + if (itemListView->isHeaderVisible()) { + KItemListHeader* header = itemListView->header(); + const QList headerColumnWidths = props.headerColumnWidths(); + const int rolesCount = m_visibleRoles.count(); + if (headerColumnWidths.count() == rolesCount) { + header->setAutomaticColumnResizing(false); -KFileItemDelegate* DolphinView::ViewAccessor::itemDelegate() const -{ - return static_cast(itemView()->itemDelegate()); + QHash columnWidths; + for (int i = 0; i < rolesCount; ++i) { + columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]); + } + header->setColumnWidths(columnWidths); + } else { + header->setAutomaticColumnResizing(true); + } + } + + m_view->endTransaction(); } -QWidget* DolphinView::ViewAccessor::layoutTarget() const +void DolphinView::applyModeToView() { - if (m_columnsContainer != 0) { - return m_columnsContainer; + switch (m_mode) { + case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break; + case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break; + case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break; + default: Q_ASSERT(false); break; } - return itemView(); } -void DolphinView::ViewAccessor::setRootUrl(const KUrl& rootUrl) +void DolphinView::pasteToUrl(const QUrl& url) { - m_rootUrl = rootUrl; + KIO::PasteJob *job = KIO::paste(QApplication::clipboard()->mimeData(), url); + KJobWidgets::setWindow(job, this); + m_clearSelectionBeforeSelectingNewItems = true; + m_markFirstNewlySelectedItemAsCurrent = true; + connect(job, &KIO::PasteJob::itemCreated, this, &DolphinView::slotItemCreated); + connect(job, &KIO::PasteJob::result, this, &DolphinView::slotPasteJobResult); } -KUrl DolphinView::ViewAccessor::rootUrl() const +QList DolphinView::simplifiedSelectedUrls() const { - return (m_columnsContainer != 0) ? m_columnsContainer->rootUrl() : m_rootUrl; -} + QList urls; -bool DolphinView::ViewAccessor::supportsCategorizedSorting() const -{ - return m_iconsView != 0; -} + const KFileItemList items = selectedItems(); + urls.reserve(items.count()); + foreach (const KFileItem& item, items) { + urls.append(item.url()); + } -bool DolphinView::ViewAccessor::itemsExpandable() const -{ - return (m_detailsView != 0) && m_detailsView->itemsExpandable(); + if (itemsExpandable()) { + // TODO: Check if we still need KDirModel for this in KDE 5.0 + urls = KDirModel::simplifiedUrlList(urls); + } + + return urls; } -QSet DolphinView::ViewAccessor::expandedUrls() const +QMimeData* DolphinView::selectionMimeData() const { - if (m_detailsView != 0) { - return m_detailsView->expandedUrls(); - } + const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + const KItemSet selectedIndexes = selectionManager->selectedItems(); - return QSet(); + return m_model->createMimeData(selectedIndexes); } -const DolphinDetailsViewExpander* DolphinView::ViewAccessor::setExpandedUrls(const QSet& urlsToExpand) +void DolphinView::updateWritableState() { - if ((m_detailsView != 0) && m_detailsView->itemsExpandable() && !urlsToExpand.isEmpty()) { - // Check if another expander is already active and stop it if necessary. - if(!m_detailsViewExpander.isNull()) { - m_detailsViewExpander->stop(); - } + const bool wasFolderWritable = m_isFolderWritable; + m_isFolderWritable = false; - m_detailsViewExpander = new DolphinDetailsViewExpander(m_detailsView, urlsToExpand); - return m_detailsViewExpander; + KFileItem item = m_model->rootItem(); + if (item.isNull()) { + // Try to find out if the URL is writable even if the "root item" is + // null, see https://bugs.kde.org/show_bug.cgi?id=330001 + item = KFileItem(url()); + item.setDelayedMimeTypes(true); } - else { - return 0; + + KFileItemListProperties capabilities(KFileItemList() << item); + m_isFolderWritable = capabilities.supportsWriting(); + + if (m_isFolderWritable != wasFolderWritable) { + emit writeStateChanged(m_isFolderWritable); } } -bool DolphinView::ViewAccessor::reloadOnAdditionalInfoChange() const +QUrl DolphinView::viewPropertiesUrl() const { - // the details view requires no reloading of the directory, as it maps - // the file item delegate info to its columns internally - return m_detailsView != 0; -} + if (m_viewPropertiesContext.isEmpty()) { + return m_url; + } -DolphinModel* DolphinView::ViewAccessor::dirModel() const -{ - return static_cast(proxyModel()->sourceModel()); + QUrl url; + url.setScheme(m_url.scheme()); + url.setPath(m_viewPropertiesContext); + return url; } -DolphinSortFilterProxyModel* DolphinView::ViewAccessor::proxyModel() const +void DolphinView::slotRenameDialogRenamingFinished(const QList& urls) { - if (m_columnsContainer != 0) { - return static_cast(m_columnsContainer->activeColumn()->model()); - } - return m_proxyModel; + forceUrlsSelection(urls.first(), urls); } -KDirLister* DolphinView::ViewAccessor::dirLister() const +void DolphinView::forceUrlsSelection(const QUrl& current, const QList& selected) { - return dirModel()->dirLister(); + clearSelection(); + m_clearSelectionBeforeSelectingNewItems = true; + markUrlAsCurrent(current); + markUrlsAsSelected(selected); } - -#include "dolphinview.moc"