X-Git-Url: https://cloud.milkyroute.net/gitweb/dolphin.git/blobdiff_plain/d3496b12310d9fec0e52e537c341e87fcaa2f8b5..d1a70c0b629b:/src/views/dolphinview.cpp diff --git a/src/views/dolphinview.cpp b/src/views/dolphinview.cpp index 4ab16e052..c98929ead 100644 --- a/src/views/dolphinview.cpp +++ b/src/views/dolphinview.cpp @@ -20,146 +20,193 @@ #include "dolphinview.h" -#include -#include -#include -#include -#include -#include -#include -#include +#include "dolphin_detailsmodesettings.h" +#include "dolphin_generalsettings.h" +#include "dolphinitemlistview.h" +#include "dolphinnewfilemenuobserver.h" +#include "draganddrophelper.h" +#include "kitemviews/kfileitemlistview.h" +#include "kitemviews/kfileitemmodel.h" +#include "kitemviews/kitemlistcontainer.h" +#include "kitemviews/kitemlistcontroller.h" +#include "kitemviews/kitemlistheader.h" +#include "kitemviews/kitemlistselectionmanager.h" +#include "versioncontrol/versioncontrolobserver.h" +#include "viewproperties.h" +#include "views/tooltips/tooltipmanager.h" +#include "zoomlevelinfo.h" -#include +#ifdef HAVE_BALOO +#include +#endif #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 "dolphindirlister.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 "draganddrophelper.h" -#include "renamedialog.h" -#include "settings/dolphinsettings.h" -#include "viewmodecontroller.h" -#include "viewproperties.h" -#include "zoomlevelinfo.h" -#include "dolphindetailsviewexpander.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -DolphinView::DolphinView(const KUrl& url, QWidget* parent) : +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_topLayout(0), - m_dolphinViewController(0), - m_viewModeController(0), - m_viewAccessor(), - m_selectionChangedTimer(0), - m_activeItemUrl(), + m_visibleRoles(), + m_topLayout(nullptr), + m_model(nullptr), + m_view(nullptr), + m_container(nullptr), + m_toolTipManager(nullptr), + m_selectionChangedTimer(nullptr), + m_currentItemUrl(), + m_scrollToCurrentItem(false), m_restoredContentsPosition(), - m_createdItemUrl(), - m_selectedItems(), - m_newFileNames() + m_selectedUrls(), + m_clearSelectionBeforeSelectingNewItems(false), + m_markFirstNewlySelectedItemAsCurrent(false), + m_versionControlObserver(nullptr), + 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))); + m_topLayout->setContentsMargins(0, 0, 0, 0); // 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, [=] { hideToolTip(); }); + connect(m_container->verticalScrollBar(), &QScrollBar::valueChanged, this, [=] { 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); + +#ifdef HAVE_BALOO + m_toolTipManager = new ToolTipManager(this); + connect(m_toolTipManager, &ToolTipManager::urlActivated, this, &DolphinView::urlActivated); +#endif + + m_versionControlObserver = new VersionControlObserver(this); + m_versionControlObserver->setView(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) @@ -170,26 +217,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 @@ -199,170 +233,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; + } -bool DolphinView::categorizedSorting() 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; + ViewProperties props(viewPropertiesUrl()); + props.setGroupedSorting(grouped); + props.save(); + + m_container->controller()->model()->setGroupedSorting(grouped); + + emit groupedSortingChanged(grouped); } -bool DolphinView::supportsCategorizedSorting() const +bool DolphinView::groupedSorting() const { - return m_viewAccessor.supportsCategorizedSorting(); + return m_model->groupedSorting(); } -KFileItem DolphinView::rootItem() const +KFileItemList DolphinView::items() const { - return m_viewAccessor.dirLister()->rootItem(); + 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) { - return itemList; - } + const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); - const QItemSelection selection = m_viewAccessor.proxyModel()->mapSelectionToSource(view->selectionModel()->selection()); - - 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) { - 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 QRegularExpression ®exp, 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 (regexp.match(item.text()).hasMatch()) { + // 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) @@ -374,7 +420,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) @@ -386,26 +432,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() @@ -413,7 +458,6 @@ void DolphinView::reload() QByteArray viewState; QDataStream saveStream(&viewState, QIODevice::WriteOnly); saveState(saveStream); - m_selectedItems= selectedItems(); setUrl(url()); loadDirectory(url(), true); @@ -422,224 +466,227 @@ void DolphinView::reload() restoreState(restoreStream); } -void DolphinView::stopLoading() -{ - m_viewAccessor.dirLister()->stop(); -} - -void DolphinView::refresh() +void DolphinView::readSettings() { - const bool oldActivationState = m_active; - const int oldZoomLevel = m_viewModeController->zoomLevel(); - m_active = true; + const int oldZoomLevel = m_view->zoomLevel(); - createView(); + GeneralSettings::self()->load(); + m_view->readSettings(); applyViewProperties(); - reload(); - setActive(oldActivationState); - updateZoomLevel(oldZoomLevel); + 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::writeSettings() +{ + GeneralSettings::self()->save(); + m_view->writeSettings(); } void DolphinView::setNameFilter(const QString& nameFilter) { - m_viewModeController->setNameFilter(nameFilter); + m_model->setNameFilter(nameFilter); } QString DolphinView::nameFilter() const { - return m_viewModeController->nameFilter(); + return m_model->nameFilter(); } -void DolphinView::calculateItemCount(int& fileCount, - int& folderCount, - KIO::filesize_t& totalFileSize) const +void DolphinView::setMimeTypeFilters(const QStringList& filters) { - foreach (const KFileItem& item, m_viewAccessor.dirLister()->items()) { - if (item.isDir()) { - ++folderCount; - } else { - ++fileCount; - totalFileSize += item.size(); - } - } + return m_model->setMimeTypeFilters(filters); +} + +QStringList DolphinView::mimeTypeFilters() const +{ + 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() { - // Implementation note: Using selectionModel->select(selection, QItemSelectionModel::Toggle) does not - // work, as QItemSelectionModel::hasSelection() provides invalid values in this case. This might be a Qt-issue - - // when changing the implementation with an updated Qt-version don't forget to run the Dolphin-unit-tests that - // verify this usecase. - const KFileItemList selItems = selectedItems(); - clearSelection(); - - QItemSelection invertedSelection; - foreach (const KFileItem& item, items()) { - if (!selItems.contains(item)) { - const QModelIndex index = m_viewAccessor.proxyModel()->mapFromSource(m_viewAccessor.dirModel()->indexForItem(item)); - invertedSelection.select(index, index); - } - } - - QItemSelectionModel* selectionModel = m_viewAccessor.itemView()->selectionModel(); - selectionModel->select(invertedSelection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Current); + 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); - dialog->setAttribute(Qt::WA_DeleteOnClose); - dialog->show(); - dialog->raise(); - dialog->activateWindow(); + KIO::RenameFileDialog* dialog = new KIO::RenameFileDialog(items, this); + connect(dialog, &KIO::RenameFileDialog::renamingFinished, + this, &DolphinView::slotRenameDialogRenamingFinished); + + dialog->open(); } + + // 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); } -void DolphinView::copySelectedItems() +void DolphinView::copySelectedItemsToClipboard() { QMimeData* mimeData = selectionMimeData(); QApplication::clipboard()->setMimeData(mimeData); @@ -658,109 +705,127 @@ void DolphinView::pasteIntoFolder() } } -void DolphinView::setShowPreview(bool show) +void DolphinView::duplicateSelectedItems() { - if (m_showPreview == show) { + const KFileItemList itemList = selectedItems(); + if (itemList.isEmpty()) { return; } - const KUrl viewPropsUrl = rootUrl(); - ViewProperties props(viewPropsUrl); - props.setShowPreview(show); + const QMimeDatabase db; - m_showPreview = show; - const int oldZoomLevel = m_viewModeController->zoomLevel(); - emit showPreviewChanged(); + // Duplicate all selected items and append "copy" to the end of the file name + // but before the filename extension, if present + QList newSelection; + for (const auto &item : itemList) { + const QUrl originalURL = item.url(); + const QString originalDirectoryPath = originalURL.adjusted(QUrl::RemoveFilename).path(); + const QString originalFileName = item.name(); - // 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); -} + QString extension = db.suffixForFileName(originalFileName); -void DolphinView::setShowHiddenFiles(bool show) -{ - if (m_viewAccessor.dirLister()->showingDotFiles() == show) { - return; + QUrl duplicateURL = originalURL; + + // No extension; new filename is " copy" + if (extension.isEmpty()) { + duplicateURL.setPath(originalDirectoryPath + i18nc(" copy", "%1 copy", originalFileName)); + // There's an extension; new filename is " copy." + } else { + // Need to add a dot since QMimeDatabase::suffixForFileName() doesn't include it + extension = QLatin1String(".") + extension; + const QString originalFilenameWithoutExtension = originalFileName.chopped(extension.size()); + // Preserve file's original filename extension in case the casing differs + // from what QMimeDatabase::suffixForFileName() returned + const QString originalExtension = originalFileName.right(extension.size()); + duplicateURL.setPath(originalDirectoryPath + i18nc(" copy", "%1 copy", originalFilenameWithoutExtension) + originalExtension); + } + + KIO::CopyJob* job = KIO::copyAs(originalURL, duplicateURL, KIO::HideProgressInfo); + KJobWidgets::setWindow(job, this); + + if (job) { + newSelection << duplicateURL; + KIO::FileUndoManager::self()->recordCopyJob(job); + } } - const KUrl viewPropsUrl = rootUrl(); - ViewProperties props(viewPropsUrl); - props.setShowHiddenFiles(show); + forceUrlsSelection(newSelection.first(), newSelection); +} - m_viewAccessor.dirLister()->setShowingDotFiles(show); - emit showHiddenFilesChanged(); +void DolphinView::stopLoading() +{ + m_model->cancelDirectoryLoading(); } -void DolphinView::setCategorizedSorting(bool categorized) +void DolphinView::updatePalette() { - if (categorized == categorizedSorting()) { - return; + QColor color = KColorScheme(isActiveWindow() ? QPalette::Active : QPalette::Inactive, KColorScheme::View).background().color(); + if (!m_active) { + color.setAlpha(150); } - // 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); + QWidget* viewport = m_container->viewport(); + if (viewport) { + QPalette palette; + palette.setColor(viewport->backgroundRole(), color); + viewport->setPalette(palette); + } - 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()) { - setActive(true); - } + case QEvent::WindowActivate: + case QEvent::WindowDeactivate: + updatePalette(); break; case QEvent::KeyPress: - if (watched == m_viewAccessor.itemView()) { - // clear the selection when Escape has been pressed + hideToolTip(ToolTipManager::HideBehavior::Instantly); + if (GeneralSettings::useTabForSwitchingSplitView()) { QKeyEvent* keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Escape) { - clearSelection(); + 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::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::GraphicsSceneDragEnter: + if (watched == m_view) { + m_dragging = true; + abortTwoClicksRenaming(); + } + break; + + case QEvent::GraphicsSceneDragLeave: + if (watched == m_view) { + m_dragging = false; } break; + case QEvent::GraphicsSceneDrop: + if (watched == m_view) { + m_dragging = false; + } default: break; } @@ -768,851 +833,1089 @@ 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, DolphinTabWidget::AfterLastTab); + } 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, DolphinTabWidget::AfterCurrentTab); + } else if (isTabsForFilesEnabled()) { + emit tabRequested(item.url(), DolphinTabWidget::AfterCurrentTab); + } } -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 = nullptr; - 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 = nullptr; + 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); + const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || + (info.requiresBaloo) || + (info.requiresIndexer && indexingEnabled); action->setEnabled(enable); - action->setChecked(checkedInfo.contains(info)); } -} -QPair DolphinView::pasteInfo() const -{ - return KonqOperations::pasteInfo(url()); -} + 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(); -void DolphinView::setTabsForFilesEnabled(bool tabsForFiles) -{ - m_tabsForFiles = tabsForFiles; -} + QList visibleRoles = view->visibleRoles(); + if (action->isChecked()) { + visibleRoles.append(selectedRole); + } else { + visibleRoles.removeOne(selectedRole); + } -bool DolphinView::isTabsForFilesEnabled() const -{ - return m_tabsForFiles; -} + view->setVisibleRoles(visibleRoles); + props.setVisibleRoles(visibleRoles); -bool DolphinView::itemsExpandable() const -{ - return m_viewAccessor.itemsExpandable(); + 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; } -void DolphinView::restoreState(QDataStream& stream) +void DolphinView::slotHeaderColumnWidthChangeFinished(const QByteArray& role, qreal current) { - // Restore the URL of the current item that had the keyboard focus - stream >> m_activeItemUrl; + const QList visibleRoles = m_view->visibleRoles(); - // Restore the root URL - KUrl rootUrl; - stream >> rootUrl; - m_viewAccessor.setRootUrl(rootUrl); + 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); + } + } - // Restore the view position - stream >> m_restoredContentsPosition; + const int roleIndex = visibleRoles.indexOf(role); + Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count()); + columnWidths[roleIndex] = current; - // 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) { - m_expanderActive = true; - connect (expander, SIGNAL(completed()), this, SLOT(slotLoadingCompleted())); - } - else { - m_expanderActive = false; - } + props.setHeaderColumnWidths(columnWidths); } -void DolphinView::saveState(QDataStream& stream) +void DolphinView::slotItemHovered(int index) { - // Save the URL of the current item that has the keyboard focus - KFileItem currentItem; - const QAbstractItemView* view = m_viewAccessor.itemView(); + const KFileItem item = m_model->fileItem(index); - if (view) { - const QModelIndex proxyIndex = view->currentIndex(); - const QModelIndex dirModelIndex = m_viewAccessor.proxyModel()->mapToSource(proxyIndex); - currentItem = m_viewAccessor.dirModel()->itemForIndex(dirModelIndex); + 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); + +#ifdef HAVE_BALOO + m_toolTipManager->showToolTip(item, itemRect, nativeParentWidget()->windowHandle()); +#endif } - KUrl currentItemUrl; - if (!currentItem.isNull()) { - currentItemUrl = currentItem.url(); + emit requestItemInfo(item); +} + +void DolphinView::slotItemUnhovered(int index) +{ + Q_UNUSED(index) + hideToolTip(); + emit requestItemInfo(KFileItem()); +} + +void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event) +{ + 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(); } - stream << currentItemUrl; + QDropEvent dropEvent(event->pos().toPoint(), + event->possibleActions(), + event->mimeData(), + event->buttons(), + event->modifiers()); + dropUrls(destUrl, &dropEvent, this); - // Save the root URL - stream << m_viewAccessor.rootUrl(); + setActive(true); +} - // Save view position - const int x = view->horizontalScrollBar()->value(); - const int y = view->verticalScrollBar()->value(); - stream << QPoint(x, y); +void DolphinView::dropUrls(const QUrl &destUrl, QDropEvent *dropEvent, QWidget *dropWidget) +{ + KIO::DropJob* job = DragAndDropHelper::dropUrls(destUrl, dropEvent, dropWidget); - // Save expanded folders (only relevant for the details view - the set will be empty in other view modes) - stream << m_viewAccessor.expandedUrls(); + if (job) { + connect(job, &KIO::DropJob::result, this, &DolphinView::slotPasteJobResult); + + if (destUrl == url()) { + // Mark the dropped urls as selected. + m_clearSelectionBeforeSelectingNewItems = true; + m_markFirstNewlySelectedItemAsCurrent = true; + connect(job, &KIO::DropJob::itemCreated, this, &DolphinView::slotItemCreated); + } + } } -bool DolphinView::hasSelection() const +void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous) { - const QAbstractItemView* view = m_viewAccessor.itemView(); - return view && view->selectionModel()->hasSelection(); + if (previous != nullptr) { + Q_ASSERT(qobject_cast(previous)); + KFileItemModel* fileItemModel = static_cast(previous); + disconnect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); + m_versionControlObserver->setModel(nullptr); + } + + if (current) { + Q_ASSERT(qobject_cast(current)); + KFileItemModel* fileItemModel = static_cast(current); + connect(fileItemModel, &KFileItemModel::directoryLoadingCompleted, this, &DolphinView::slotDirectoryLoadingCompleted); + m_versionControlObserver->setModel(fileItemModel); + } } -void DolphinView::observeCreatedItem(const KUrl& url) +void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons) { - m_createdItemUrl = url; - connect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)), - this, SLOT(selectAndScrollToCreatedItem())); + Q_UNUSED(itemIndex) + + hideToolTip(); + + if (buttons & Qt::BackButton) { + emit goBackRequested(); + } else if (buttons & Qt::ForwardButton) { + emit goForwardRequested(); + } } -void DolphinView::selectAndScrollToCreatedItem() +void DolphinView::slotSelectedItemTextPressed(int index) { - 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 (GeneralSettings::renameInline() && !m_view->style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick)) { + const KFileItem item = m_model->fileItem(index); + const KFileItemListProperties capabilities(KFileItemList() << item); + if (capabilities.supportsMoving()) { + m_twoClicksRenamingItemUrl = item.url(); + m_twoClicksRenamingTimer->start(QApplication::doubleClickInterval()); + } } +} - disconnect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(const QModelIndex&, int, int)), - this, SLOT(selectAndScrollToCreatedItem())); - m_createdItemUrl = KUrl(); +void DolphinView::slotItemCreated(const QUrl& url) +{ + if (m_markFirstNewlySelectedItemAsCurrent) { + markUrlAsCurrent(url); + m_markFirstNewlySelectedItemAsCurrent = false; + } + m_selectedUrls << url; } -void DolphinView::slotRedirection(const KUrl& oldUrl, const KUrl& newUrl) +void DolphinView::slotPasteJobResult(KJob *job) { - if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) { - emit redirection(oldUrl, newUrl); - m_viewModeController->redirectToUrl(newUrl); // #186947 + if (job->error()) { + emit errorMessage(job->errorString()); + } + if (!m_selectedUrls.isEmpty()) { + m_selectedUrls = KDirModel::simplifiedUrlList(m_selectedUrls); } } -void DolphinView::restoreContentsPosition() +void DolphinView::slotSelectionChanged(const KItemSet& current, const KItemSet& previous) { - if (!m_restoredContentsPosition.isNull()) { - const int x = m_restoredContentsPosition.x(); - const int y = m_restoredContentsPosition.y(); - m_restoredContentsPosition = QPoint(); + const int currentCount = current.count(); + const int previousCount = previous.count(); + const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) || + (currentCount > 0 && previousCount == 0); - QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT(view); - view->horizontalScrollBar()->setValue(x); - view->verticalScrollBar()->setValue(y); - } + // 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::slotUrlChangeRequested(const KUrl& url) +void DolphinView::emitSelectionChangedSignal() { - m_viewModeController->setUrl(url); - updateWritableState(); + m_selectionChangedTimer->stop(); + emit selectionChanged(selectedItems()); } -void DolphinView::showHoverInformation(const KFileItem& item) +void DolphinView::updateSortRole(const QByteArray& role) { - emit requestItemInfo(item); + ViewProperties props(viewPropertiesUrl()); + props.setSortRole(role); + + KItemModelBase* model = m_container->controller()->model(); + model->setSortRole(role); + + emit sortRoleChanged(role); } -void DolphinView::clearHoverInformation() +void DolphinView::updateSortOrder(Qt::SortOrder order) { - emit requestItemInfo(KFileItem()); + ViewProperties props(viewPropertiesUrl()); + props.setSortOrder(order); + + m_model->setSortOrder(order); + + emit sortOrderChanged(order); } -void DolphinView::slotDeleteFileFinished(KJob* job) +void DolphinView::updateSortFoldersFirst(bool foldersFirst) { - if (job->error() == 0) { - emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed.")); - } else if (job->error() != KIO::ERR_USER_CANCELED) { - emit errorMessage(job->errorString()); - } + ViewProperties props(viewPropertiesUrl()); + props.setSortFoldersFirst(foldersFirst); + + m_model->setSortDirectoriesFirst(foldersFirst); + + emit sortFoldersFirstChanged(foldersFirst); } -void DolphinView::slotDirListerStarted(const KUrl& url) +QPair DolphinView::pasteInfo() 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); - } + const QMimeData *mimeData = QApplication::clipboard()->mimeData(); + QPair info; + info.second = KIO::pasteActionText(mimeData, &info.first, rootItem()); + return info; +} - emit startedPathLoading(url); +void DolphinView::setTabsForFilesEnabled(bool tabsForFiles) +{ + m_tabsForFiles = tabsForFiles; } -void DolphinView::slotDirListerCompleted() +bool DolphinView::isTabsForFilesEnabled() const { - if (!m_expanderActive) { - slotLoadingCompleted(); - } + return m_tabsForFiles; +} - 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); +bool DolphinView::itemsExpandable() const +{ + return m_mode == DetailsView; +} - m_newFileNames.clear(); +void DolphinView::restoreState(QDataStream& stream) +{ + // 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; } - updateWritableState(); + // Restore the current item that had the keyboard focus + stream >> m_currentItemUrl; + + // Restore the previously selected items + stream >> m_selectedUrls; + + // 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)) { - const 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()) { - createView(); + if (item.isDir()) { + return url; } - Q_ASSERT(m_viewAccessor.itemView()); - Q_ASSERT(m_viewAccessor.itemDelegate()); + 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::resetZoomLevel() +{ + ViewModeSettings::ViewMode mode; - const bool sortFoldersFirst = props.sortFoldersFirst(); - if (sortFoldersFirst != m_viewAccessor.proxyModel()->sortFoldersFirst()) { - m_viewAccessor.proxyModel()->setSortFoldersFirst(sortFoldersFirst); - emit sortFoldersFirstChanged(sortFoldersFirst); + switch (m_mode) { + case IconsView: mode = ViewModeSettings::IconsMode; break; + case CompactView: mode = ViewModeSettings::CompactMode; break; + case DetailsView: mode = ViewModeSettings::DetailsMode; break; } + const ViewModeSettings settings(mode); + const QSize iconSize = QSize(settings.iconSize(), settings.iconSize()); + setZoomLevel(ZoomLevelInfo::zoomLevelForIconSize(iconSize)); +} - KFileItemDelegate::InformationList info = props.additionalInfo(); - if (info != m_viewAccessor.itemDelegate()->showInformation()) { - m_viewAccessor.itemDelegate()->setShowInformation(info); - emit additionalInfoChanged(); +void DolphinView::observeCreatedItem(const QUrl& url) +{ + if (m_active) { + forceUrlsSelection(url, {url}); } +} - const bool showPreview = props.showPreview(); - if (showPreview != m_showPreview) { - m_showPreview = showPreview; - 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); +void DolphinView::slotDirectoryRedirection(const QUrl& oldUrl, const QUrl& newUrl) +{ + if (oldUrl.matches(url(), QUrl::StripTrailingSlash)) { + emit redirection(oldUrl, newUrl); + m_url = newUrl; // #186947 } } -void DolphinView::createView() +void DolphinView::updateViewState() { - deleteView(); + if (m_currentItemUrl != QUrl()) { + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); - Q_ASSERT(!m_viewAccessor.itemView()); - Q_ASSERT(!m_dolphinViewController->itemView()); - m_viewAccessor.createView(this, m_dolphinViewController, m_viewModeController, m_mode); + // if there is a selection already, leave it that way + if (!selectionManager->hasSelection()) { + const int currentIndex = m_model->index(m_currentItemUrl); + if (currentIndex != -1) { + selectionManager->setCurrentItem(currentIndex); - QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT(view); - view->installEventFilter(this); - view->viewport()->installEventFilter(this); - - m_dolphinViewController->setItemView(view); + // scroll to current item and reset the state + if (m_scrollToCurrentItem) { + m_view->scrollToItem(currentIndex); + m_scrollToCurrentItem = false; + } + } else { + selectionManager->setCurrentItem(0); + } + } - const int zoomLevel = ZoomLevelInfo::zoomLevelForIconSize(view->iconSize()); - m_viewModeController->setZoomLevel(zoomLevel); + m_currentItemUrl = QUrl(); + } - connectViewAccessor(); + if (!m_restoredContentsPosition.isNull()) { + const int x = m_restoredContentsPosition.x(); + const int y = m_restoredContentsPosition.y(); + m_restoredContentsPosition = QPoint(); - setFocusProxy(m_viewAccessor.layoutTarget()); - m_topLayout->insertWidget(1, m_viewAccessor.layoutTarget()); -} + m_container->horizontalScrollBar()->setValue(x); + m_container->verticalScrollBar()->setValue(y); + } -void DolphinView::deleteView() -{ - QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT(!m_dolphinViewController->itemView() || (m_dolphinViewController->itemView() == view)); - m_dolphinViewController->setItemView(0); + if (!m_selectedUrls.isEmpty()) { + KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); - if (view) { - disconnectViewAccessor(); + // if there is a selection already, leave it that way + if (!selectionManager->hasSelection()) { + if (m_clearSelectionBeforeSelectingNewItems) { + selectionManager->clearSelection(); + m_clearSelectionBeforeSelectingNewItems = false; + } - 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(); - } + KItemSet selectedItems = selectionManager->selectedItems(); - m_viewModeController->disconnect(view); + 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; + } + } - m_viewAccessor.deleteView(); + selectionManager->beginAnchoredSelection(selectionManager->currentItem()); + selectionManager->setSelectedItems(selectedItems); + } } } -void DolphinView::pasteToUrl(const KUrl& url) +void DolphinView::hideToolTip(const ToolTipManager::HideBehavior behavior) { - addNewFileNames(QApplication::clipboard()->mimeData()); - KonqOperations::doPaste(this, url); +#ifdef HAVE_BALOO + if (GeneralSettings::showToolTips()) { + m_toolTipManager->hideToolTip(behavior); + } +#endif } -void DolphinView::updateZoomLevel(int oldZoomLevel) +void DolphinView::calculateItemCount(int& fileCount, + int& folderCount, + KIO::filesize_t& totalFileSize) const { - const int newZoomLevel = ZoomLevelInfo::zoomLevelForIconSize(m_viewAccessor.itemView()->iconSize()); - if (oldZoomLevel != newZoomLevel) { - m_viewModeController->setZoomLevel(newZoomLevel); - emit zoomLevelChanged(newZoomLevel); + const int itemCount = m_model->count(); + + bool countFileSize = true; + + // In case we have a precomputed value + const auto job = KIO::statDetails(m_model->rootItem().url(), KIO::StatJob::SourceSide, KIO::StatRecursiveSize); + job->exec(); + const auto entry = job->statResult(); + if (entry.contains(KIO::UDSEntry::UDS_RECURSIVE_SIZE)) { + totalFileSize = static_cast(entry.numberValue(KIO::UDSEntry::UDS_RECURSIVE_SIZE)); + countFileSize = false; + } + + for (int i = 0; i < itemCount; ++i) { + const KFileItem item = m_model->fileItem(i); + if (item.isDir()) { + ++folderCount; + } else { + ++fileCount; + if (countFileSize) { + totalFileSize += item.size(); + } + } } } -KUrl::List DolphinView::simplifiedSelectedUrls() const +void DolphinView::slotTwoClicksRenamingTimerTimeout() { - KUrl::List urls; - - const KFileItemList items = selectedItems(); - foreach (const KFileItem &item, items) { - urls.append(item.url()); - } + const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager(); + // verify that only one item is selected + if (selectionManager->selectedItems().count() == 1) { + const int index = selectionManager->currentItem(); + const QUrl fileItemUrl = m_model->fileItem(index).url(); - if (itemsExpandable()) { - urls = KDirModel::simplifiedUrlList(urls); + // check if the selected item was the same item that started the twoClicksRenaming + if (fileItemUrl.isValid() && m_twoClicksRenamingItemUrl == fileItemUrl) { + renameSelectedItems(); + } } - - return urls; } -QMimeData* DolphinView::selectionMimeData() const +void DolphinView::slotTrashFileFinished(KJob* job) { - const QAbstractItemView* view = m_viewAccessor.itemView(); - Q_ASSERT((view) && (view->selectionModel())); - const QItemSelection selection = m_viewAccessor.proxyModel()->mapSelectionToSource(view->selectionModel()->selection()); - return m_viewAccessor.dirModel()->mimeData(selection.indexes()); + 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::addNewFileNames(const QMimeData* mimeData) +void DolphinView::slotDeleteFileFinished(KJob* job) { - const KUrl::List urls = KUrl::List::fromMimeData(mimeData); - foreach (const KUrl& url, urls) { - m_newFileNames.insert(url.fileName()); + if (job->error() == 0) { + emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed.")); + } else if (job->error() != KIO::ERR_USER_CANCELED) { + emit errorMessage(job->errorString()); } } -QItemSelection DolphinView::childrenMatchingPattern(const QModelIndex& parent, const QRegExp& pattern) const +void DolphinView::slotRenamingResult(KJob* job) { - QItemSelection matchingIndexes; - const DolphinSortFilterProxyModel* proxyModel = m_viewAccessor.proxyModel(); - const DolphinModel* dolphinModel = m_viewAccessor.dirModel(); - - const int rowCount = proxyModel->rowCount(parent); - - for (int row = 0; row < rowCount; ++row) { - QModelIndex index = proxyModel->index(row, 0, parent); - QModelIndex sourceIndex = proxyModel->mapToSource(index); - - if (sourceIndex.isValid() && pattern.exactMatch(dolphinModel->data(sourceIndex).toString())) { - matchingIndexes += QItemSelectionRange(index); + 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 (proxyModel->hasChildren(index)) { - matchingIndexes += childrenMatchingPattern(index, pattern); - } +void DolphinView::slotDirectoryLoadingStarted() +{ + // Disable the writestate temporary until it can be determined in a fast way + // in DolphinView::slotDirectoryLoadingCompleted() + if (m_isFolderWritable) { + m_isFolderWritable = false; + emit writeStateChanged(m_isFolderWritable); } - return matchingIndexes; + emit directoryLoadingStarted(); } -void DolphinView::connectViewAccessor() +void DolphinView::slotDirectoryLoadingCompleted() { - 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())); + // 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); - connect(dirLister, SIGNAL(clear()), this, SIGNAL(itemCountChanged())); - connect(dirLister, SIGNAL(newItems(KFileItemList)), this, SIGNAL(itemCountChanged())); - connect(dirLister, SIGNAL(infoMessage(const QString&)), this, SIGNAL(infoMessage(const QString&))); - connect(dirLister, SIGNAL(errorMessage(const QString&)), this, SIGNAL(infoMessage(const QString&))); - connect(dirLister, SIGNAL(percent(int)), this, SIGNAL(pathLoadingProgress(int))); - connect(dirLister, SIGNAL(urlIsFileError(const KUrl&)), this, SIGNAL(urlIsFileError(const KUrl&))); - connect(dirLister, SIGNAL(itemsDeleted(const KFileItemList&)), this, SIGNAL(itemCountChanged())); + emit directoryLoadingCompleted(); - QAbstractItemView* view = m_viewAccessor.itemView(); - connect(view->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), - this, SLOT(slotSelectionChanged(QItemSelection, QItemSelection))); + updateWritableState(); } -void DolphinView::disconnectViewAccessor() +void DolphinView::slotItemsChanged() { - 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())); - - disconnect(dirLister, SIGNAL(clear()), this, SIGNAL(itemCountChanged())); - disconnect(dirLister, SIGNAL(newItems(KFileItemList)), this, SIGNAL(itemCountChanged())); - disconnect(dirLister, SIGNAL(infoMessage(const QString&)), this, SIGNAL(infoMessage(const QString&))); - disconnect(dirLister, SIGNAL(errorMessage(const QString&)), this, SIGNAL(errorMessage(const QString&))); - disconnect(dirLister, SIGNAL(percent(int)), this, SIGNAL(pathLoadingProgress(int))); - disconnect(dirLister, SIGNAL(urlIsFileError(const KUrl&)), this, SIGNAL(urlIsFileError(const KUrl&))); - disconnect(dirLister, SIGNAL(itemsDeleted(const KFileItemList&)), this, SIGNAL(itemCountChanged())); - - QAbstractItemView* view = m_viewAccessor.itemView(); - disconnect(view->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), - this, SLOT(slotSelectionChanged(QItemSelection, QItemSelection))); + m_assureVisibleCurrentIndex = false; } -void DolphinView::updateWritableState() +void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous) { - const bool wasFolderWritable = m_isFolderWritable; - m_isFolderWritable = true; + Q_UNUSED(previous) + Q_ASSERT(m_model->sortOrder() == current); - const KFileItem item = m_viewAccessor.dirLister()->rootItem(); - if (!item.isNull()) { - KFileItemListProperties capabilities(KFileItemList() << item); - m_isFolderWritable = capabilities.supportsWriting(); - } - if (m_isFolderWritable != wasFolderWritable) { - emit writeStateChanged(m_isFolderWritable); - } + ViewProperties props(viewPropertiesUrl()); + props.setSortOrder(current); + + emit sortOrderChanged(current); } -DolphinView::ViewAccessor::ViewAccessor() : - m_rootUrl(), - m_iconsView(0), - m_detailsView(0), - m_columnsContainer(0), - m_dolphinModel(0), - m_proxyModel(0), - m_dragSource(0) +void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous) { - DolphinDirLister* dirLister = new DolphinDirLister(); - dirLister->setAutoUpdate(true); - dirLister->setDelayedMimeTypes(true); + Q_UNUSED(previous) + Q_ASSERT(m_model->sortRole() == current); - m_dolphinModel = new DolphinModel(); - m_dolphinModel->setDirLister(dirLister); // m_dolphinModel takes ownership of dirLister - m_dolphinModel->setDropsAllowed(DolphinModel::DropOnDirectory); + ViewProperties props(viewPropertiesUrl()); + props.setSortRole(current); - m_proxyModel = new DolphinSortFilterProxyModel(); - m_proxyModel->setSourceModel(m_dolphinModel); - m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); + emit sortRoleChanged(current); } -DolphinView::ViewAccessor::~ViewAccessor() +void DolphinView::slotVisibleRolesChangedByHeader(const QList& current, + const QList& previous) { - delete m_proxyModel; - m_proxyModel = 0; + Q_UNUSED(previous) + Q_ASSERT(m_container->controller()->view()->visibleRoles() == current); - delete m_dolphinModel; - m_dolphinModel = 0; + const QList previousVisibleRoles = m_visibleRoles; - delete m_dragSource; - m_dragSource = 0; + m_visibleRoles = current; + + ViewProperties props(viewPropertiesUrl()); + props.setVisibleRoles(m_visibleRoles); + + emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles); } -void DolphinView::ViewAccessor::createView(QWidget* parent, - DolphinViewController* dolphinViewController, - const ViewModeController* viewModeController, - Mode mode) +void DolphinView::slotRoleEditingCanceled() { - Q_ASSERT(!itemView()); + disconnect(m_view, &DolphinItemListView::roleEditingFinished, + this, &DolphinView::slotRoleEditingFinished); +} - switch (mode) { - case IconsView: - m_iconsView = new DolphinIconsView(parent, - dolphinViewController, - viewModeController, - m_proxyModel); - break; +void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value) +{ + disconnect(m_view, &DolphinItemListView::roleEditingFinished, + this, &DolphinView::slotRoleEditingFinished); - case DetailsView: - m_detailsView = new DolphinDetailsView(parent, - dolphinViewController, - viewModeController, - m_proxyModel); - break; + if (index < 0 || index >= m_model->count()) { + return; + } - 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()); - } - break; + if (role == "text") { + const KFileItem oldItem = m_model->fileItem(index); + const QString newName = value.toString(); + if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1Char('.') && newName != QLatin1String("..")) { + const QUrl oldUrl = oldItem.url(); + + QUrl newUrl = oldUrl.adjusted(QUrl::RemoveFilename); + newUrl.setPath(newUrl.path() + KIO::encodeFileName(newName)); + +#ifndef Q_OS_WIN + //Confirm hiding file/directory by renaming inline + if (!hiddenFilesShown() && newName.startsWith(QLatin1Char('.')) && !oldItem.name().startsWith(QLatin1Char('.'))) { + KGuiItem yesGuiItem(KStandardGuiItem::yes()); + yesGuiItem.setText(i18nc("@action:button", "Rename and Hide")); + + const auto code = KMessageBox::questionYesNo(this, + oldItem.isFile() ? i18n("Adding a dot to the beginning of this file's name will hide it from view.\n" + "Do you still want to rename it?") + : i18n("Adding a dot to the beginning of this folder's name will hide it from view.\n" + "Do you still want to rename it?"), + oldItem.isFile() ? i18n("Hide this File?") : i18n("Hide this Folder?"), + yesGuiItem, + KStandardGuiItem::cancel(), + QStringLiteral("ConfirmHide") + ); + + if (code == KMessageBox::No) { + return; + } + } +#endif + + 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); + } - default: - Q_ASSERT(false); + 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); + } + } } } -void DolphinView::ViewAccessor::deleteView() +void DolphinView::loadDirectory(const QUrl& url, bool reload) { - if (m_columnsContainer) { - m_columnsContainer->close(); - m_columnsContainer->disconnect(); - m_columnsContainer->deleteLater(); - m_columnsContainer = 0; - } else { - QAbstractItemView* view = itemView(); - if (view) { - 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) { - // 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; - } + 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; + } - m_iconsView = 0; - m_detailsView = 0; + if (reload) { + m_model->refreshDirectory(url); + } else { + m_model->loadDirectory(url); } } -void DolphinView::ViewAccessor::prepareUrlChange(const KUrl& url) +void DolphinView::applyViewProperties() { - if (m_columnsContainer) { - m_columnsContainer->showColumn(url); - } + const ViewProperties props(viewPropertiesUrl()); + applyViewProperties(props); } -QAbstractItemView* DolphinView::ViewAccessor::itemView() const +void DolphinView::applyViewProperties(const ViewProperties& props) { - if (m_iconsView) { - return m_iconsView; + m_view->beginTransaction(); + + const Mode mode = props.viewMode(); + if (m_mode != mode) { + const Mode previousMode = m_mode; + m_mode = mode; + + // 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); + + if (m_view->zoomLevel() != oldZoomLevel) { + emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel); + } } - if (m_detailsView) { - return m_detailsView; + const bool hiddenFilesShown = props.hiddenFilesShown(); + if (hiddenFilesShown != m_model->showHiddenFiles()) { + m_model->setShowHiddenFiles(hiddenFilesShown); + emit hiddenFilesShownChanged(hiddenFilesShown); } - if (m_columnsContainer) { - return m_columnsContainer->activeColumn(); + const bool groupedSorting = props.groupedSorting(); + if (groupedSorting != m_model->groupedSorting()) { + m_model->setGroupedSorting(groupedSorting); + emit groupedSortingChanged(groupedSorting); } - return 0; -} + const QByteArray sortRole = props.sortRole(); + if (sortRole != m_model->sortRole()) { + m_model->setSortRole(sortRole); + emit sortRoleChanged(sortRole); + } -KFileItemDelegate* DolphinView::ViewAccessor::itemDelegate() const -{ - return static_cast(itemView()->itemDelegate()); -} + const Qt::SortOrder sortOrder = props.sortOrder(); + if (sortOrder != m_model->sortOrder()) { + m_model->setSortOrder(sortOrder); + emit sortOrderChanged(sortOrder); + } -QWidget* DolphinView::ViewAccessor::layoutTarget() const -{ - if (m_columnsContainer) { - return m_columnsContainer; + const bool sortFoldersFirst = props.sortFoldersFirst(); + if (sortFoldersFirst != m_model->sortDirectoriesFirst()) { + m_model->setSortDirectoriesFirst(sortFoldersFirst); + emit sortFoldersFirstChanged(sortFoldersFirst); } - return itemView(); -} -void DolphinView::ViewAccessor::setRootUrl(const KUrl& rootUrl) -{ - m_rootUrl = rootUrl; + 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); + } + + 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); + } + } + + 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); + + 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(); } -KUrl DolphinView::ViewAccessor::rootUrl() const +void DolphinView::applyModeToView() { - return m_columnsContainer ? m_columnsContainer->rootUrl() : m_rootUrl; + 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; + } } -bool DolphinView::ViewAccessor::supportsCategorizedSorting() const +void DolphinView::pasteToUrl(const QUrl& url) { - return m_iconsView != 0; + 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); } -bool DolphinView::ViewAccessor::itemsExpandable() const +QList DolphinView::simplifiedSelectedUrls() const { - return m_detailsView && m_detailsView->itemsExpandable(); + QList urls; + + const KFileItemList items = selectedItems(); + urls.reserve(items.count()); + foreach (const KFileItem& item, items) { + urls.append(item.url()); + } + + 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) { - 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 && 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) { - 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"