diff --git a/CMakeLists.txt b/CMakeLists.txt index 7816b5717..2feef8e28 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,155 +1,156 @@ cmake_minimum_required(VERSION 3.0) # KDE Application Version, managed by release script set (KDE_APPLICATIONS_VERSION_MAJOR "19") set (KDE_APPLICATIONS_VERSION_MINOR "07") set (KDE_APPLICATIONS_VERSION_MICRO "70") set (KDE_APPLICATIONS_VERSION "${KDE_APPLICATIONS_VERSION_MAJOR}.${KDE_APPLICATIONS_VERSION_MINOR}.${KDE_APPLICATIONS_VERSION_MICRO}") project(Dolphin VERSION ${KDE_APPLICATIONS_VERSION}) set(QT_MIN_VERSION "5.8.0") set(KF5_MIN_VERSION "5.58.0") # ECM setup find_package(ECM ${KF5_MIN_VERSION} CONFIG REQUIRED) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake) include(ECMSetupVersion) include(ECMGenerateHeaders) include(CMakePackageConfigHelpers) include(GenerateExportHeader) include(FeatureSummary) include(KDEInstallDirs) include(KDECMakeSettings) include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) include(ECMQtDeclareLoggingCategory) ecm_setup_version(${KDE_APPLICATIONS_VERSION} VARIABLE_PREFIX DOLPHIN VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/src/dolphin_version.h" ) ecm_setup_version("5.0.0" VARIABLE_PREFIX DOLPHINVCS VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/dolphinvcs_version.h" PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/DolphinVcsConfigVersion.cmake" SOVERSION 5 ) ecm_setup_version("5.0.0" VARIABLE_PREFIX DOLPHINPRIVATE SOVERSION 5 ) find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS Core Concurrent Widgets Gui DBus ) find_package(KF5 ${KF5_MIN_VERSION} REQUIRED COMPONENTS DocTools Init KCMUtils NewStuff CoreAddons I18n DBusAddons Bookmarks Config KIO Parts Solid IconThemes Completion TextWidgets Notifications Crash + WindowSystem ) find_package(KF5 ${KF5_MIN_VERSION} OPTIONAL_COMPONENTS Activities ) set_package_properties(KF5Activities PROPERTIES DESCRIPTION "KActivities libraries" URL "http://www.kde.org" TYPE OPTIONAL PURPOSE "For tracking which folders are frequently accessed on a Plasma desktop" ) find_package(Phonon4Qt5 CONFIG REQUIRED) find_package(KF5Baloo ${KF5_MIN_VERSION}) set_package_properties(KF5Baloo PROPERTIES DESCRIPTION "Baloo Core libraries" URL "http://www.kde.org" TYPE OPTIONAL PURPOSE "For adding desktop-wide search and tagging support to dolphin" ) find_package(KF5BalooWidgets 19.07.70) set_package_properties(KF5BalooWidgets PROPERTIES DESCRIPTION "Baloos Widgets" URL "http://www.kde.org" TYPE OPTIONAL ) find_package(KF5FileMetaData ${KF5_MIN_VERSION}) set_package_properties(KF5FileMetaData PROPERTIES URL "https://projects.kde.org/kfilemetadata" TYPE OPTIONAL PURPOSE "For accessing file metadata labels" ) if (KF5Activities_FOUND) set(HAVE_KACTIVITIES TRUE) endif() if (KF5Baloo_FOUND AND KF5BalooWidgets_FOUND AND KF5FileMetaData_FOUND) message(STATUS "Baloo packages are found") set(HAVE_BALOO TRUE) else() message(WARNING "Baloo packages not found. They are needed for the metadata features of Dolphin (including the information panel).") endif() # TODO: drop HAVE_TERMINAL once we are sure the terminal panel works on Windows too. if(WIN32) set(HAVE_TERMINAL FALSE) else() set(HAVE_TERMINAL TRUE) endif() add_subdirectory(src) add_subdirectory(doc) # CMake files set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/DolphinVcs") configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/DolphinVcsConfig.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/DolphinVcsConfig.cmake" INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR} ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/DolphinVcsConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/DolphinVcsConfigVersion.cmake" DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) install(EXPORT DolphinVcsTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}" FILE DolphinVcsTargets.cmake ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/dolphinvcs_version.h" DESTINATION "${KDE_INSTALL_INCLUDEDIR}/Dolphin" COMPONENT Devel ) configure_file(org.kde.dolphin.FileManager1.service.in ${CMAKE_CURRENT_BINARY_DIR}/org.kde.dolphin.FileManager1.service) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/org.kde.dolphin.FileManager1.service DESTINATION ${DBUS_SERVICES_INSTALL_DIR}) install( FILES dolphin.categories DESTINATION ${KDE_INSTALL_CONFDIR} ) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f1b7534ae..8a025e584 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,413 +1,414 @@ include(ECMAddAppIcon) configure_file(config-baloo.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-baloo.h) configure_file(config-kactivities.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-kactivities.h) configure_file(config-terminal.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-terminal.h) add_definitions( -DTRANSLATION_DOMAIN=\"dolphin\" ) remove_definitions( -DQT_NO_CAST_FROM_BYTEARRAY -DQT_NO_SIGNALS_SLOTS_KEYWORDS -DQT_NO_CAST_FROM_ASCII -DQT_NO_CAST_TO_ASCII ) ########################################## set(dolphinvcs_LIB_SRCS views/versioncontrol/kversioncontrolplugin.cpp ) add_library(dolphinvcs ${dolphinvcs_LIB_SRCS}) generate_export_header(dolphinvcs BASE_NAME dolphinvcs) target_link_libraries( dolphinvcs PUBLIC Qt5::Widgets ) set_target_properties(dolphinvcs PROPERTIES VERSION ${DOLPHINVCS_VERSION_STRING} SOVERSION ${DOLPHINVCS_SOVERSION} EXPORT_NAME DolphinVcs ) ecm_generate_headers(dolphinvcs_LIB_HEADERS HEADER_NAMES KVersionControlPlugin RELATIVE "views/versioncontrol" REQUIRED_HEADERS dolphinvcs_LIB_HEADERS ) install(TARGETS dolphinvcs EXPORT DolphinVcsTargets ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES views/versioncontrol/fileviewversioncontrolplugin.desktop DESTINATION ${KDE_INSTALL_KSERVICETYPES5DIR}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/dolphinvcs_export.h DESTINATION ${KDE_INSTALL_INCLUDEDIR} COMPONENT Devel) install(FILES ${dolphinvcs_LIB_HEADERS} DESTINATION "${KDE_INSTALL_INCLUDEDIR}/Dolphin" COMPONENT Devel) ########### next target ############### set(dolphinprivate_LIB_SRCS kitemviews/kfileitemlistview.cpp kitemviews/kfileitemlistwidget.cpp kitemviews/kfileitemmodel.cpp kitemviews/kfileitemmodelrolesupdater.cpp kitemviews/kitemlistcontainer.cpp kitemviews/kitemlistcontroller.cpp kitemviews/kitemlistgroupheader.cpp kitemviews/kitemlistheader.cpp kitemviews/kitemlistselectionmanager.cpp kitemviews/kitemliststyleoption.cpp kitemviews/kitemlistview.cpp kitemviews/kitemlistviewaccessible.cpp kitemviews/kitemlistwidget.cpp kitemviews/kitemmodelbase.cpp kitemviews/kitemset.cpp kitemviews/kstandarditem.cpp kitemviews/kstandarditemlistgroupheader.cpp kitemviews/kstandarditemlistwidget.cpp kitemviews/kstandarditemlistview.cpp kitemviews/kstandarditemmodel.cpp kitemviews/private/kdirectorycontentscounter.cpp kitemviews/private/kdirectorycontentscounterworker.cpp kitemviews/private/kfileitemclipboard.cpp kitemviews/private/kfileitemmodeldirlister.cpp kitemviews/private/kfileitemmodelfilter.cpp kitemviews/private/kitemlistheaderwidget.cpp kitemviews/private/kitemlistkeyboardsearchmanager.cpp kitemviews/private/kitemlistroleeditor.cpp kitemviews/private/kitemlistrubberband.cpp kitemviews/private/kitemlistselectiontoggle.cpp kitemviews/private/kitemlistsizehintresolver.cpp kitemviews/private/kitemlistsmoothscroller.cpp kitemviews/private/kitemlistviewanimation.cpp kitemviews/private/kitemlistviewlayouter.cpp kitemviews/private/kpixmapmodifier.cpp settings/applyviewpropsjob.cpp settings/viewmodes/viewmodesettings.cpp settings/viewpropertiesdialog.cpp settings/viewpropsprogressinfo.cpp views/dolphinfileitemlistwidget.cpp views/dolphinitemlistview.cpp views/dolphinnewfilemenuobserver.cpp views/dolphinremoteencoding.cpp views/dolphinview.cpp views/dolphinviewactionhandler.cpp views/draganddrophelper.cpp views/renamedialog.cpp views/versioncontrol/updateitemstatesthread.cpp views/versioncontrol/versioncontrolobserver.cpp views/viewmodecontroller.cpp views/viewproperties.cpp views/zoomlevelinfo.cpp dolphinremoveaction.cpp middleclickactioneventfilter.cpp dolphinnewfilemenu.cpp ) ecm_qt_declare_logging_category(dolphinprivate_LIB_SRCS HEADER dolphindebug.h IDENTIFIER DolphinDebug CATEGORY_NAME org.kde.dolphin) if(HAVE_BALOO) set(dolphinprivate_LIB_SRCS ${dolphinprivate_LIB_SRCS} views/tooltips/dolphinfilemetadatawidget.cpp views/tooltips/tooltipmanager.cpp kitemviews/private/kbaloorolesprovider.cpp ) endif() kconfig_add_kcfg_files(dolphinprivate_LIB_SRCS GENERATE_MOC settings/dolphin_compactmodesettings.kcfgc settings/dolphin_directoryviewpropertysettings.kcfgc settings/dolphin_detailsmodesettings.kcfgc settings/dolphin_iconsmodesettings.kcfgc settings/dolphin_generalsettings.kcfgc settings/dolphin_versioncontrolsettings.kcfgc ) add_library(dolphinprivate ${dolphinprivate_LIB_SRCS}) generate_export_header(dolphinprivate BASE_NAME dolphin) target_link_libraries( dolphinprivate PUBLIC dolphinvcs Qt5::Concurrent Qt5::Gui KF5::I18n KF5::IconThemes KF5::KIOCore KF5::KIOWidgets KF5::KIOFileWidgets KF5::Completion KF5::TextWidgets KF5::ConfigCore KF5::NewStuff KF5::Parts + KF5::WindowSystem ) if(HAVE_BALOO) target_link_libraries( dolphinprivate PUBLIC KF5::FileMetaData KF5::Baloo KF5::BalooWidgets ) endif() set_target_properties(dolphinprivate PROPERTIES VERSION ${DOLPHINPRIVATE_VERSION_STRING} SOVERSION ${DOLPHINPRIVATE_SOVERSION} ) install(TARGETS dolphinprivate ${KDE_INSTALL_TARGETS_DEFAULT_ARGS} LIBRARY NAMELINK_SKIP) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/dolphin_export.h DESTINATION ${KDE_INSTALL_INCLUDEDIR} COMPONENT Devel) ########################################## set(dolphinpart_SRCS dolphinpart.cpp dolphinpart_ext.cpp dolphindebug.cpp ) qt5_add_resources(dolphinpart_SRCS dolphinpart.qrc) add_library(dolphinpart MODULE ${dolphinpart_SRCS}) target_link_libraries(dolphinpart dolphinprivate ) install(TARGETS dolphinpart DESTINATION ${KDE_INSTALL_PLUGINDIR}) install(FILES dolphinpart.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR}) ########################################## set(dolphinstatic_SRCS dolphinbookmarkhandler.cpp dolphindockwidget.cpp dolphinmainwindow.cpp dolphinviewcontainer.cpp dolphincontextmenu.cpp dolphintabbar.cpp dolphinplacesmodelsingleton.cpp dolphinrecenttabsmenu.cpp dolphintabpage.cpp dolphintabwidget.cpp trash/dolphintrash.cpp filterbar/filterbar.cpp panels/places/placespanel.cpp panels/places/placesitem.cpp panels/places/placesitemlistgroupheader.cpp panels/places/placesitemlistwidget.cpp panels/places/placesitemmodel.cpp panels/places/placesitemsignalhandler.cpp panels/places/placesview.cpp panels/panel.cpp panels/folders/foldersitemlistwidget.cpp panels/folders/treeviewcontextmenu.cpp panels/folders/folderspanel.cpp panels/terminal/terminalpanel.cpp search/dolphinfacetswidget.cpp search/dolphinsearchbox.cpp settings/general/behaviorsettingspage.cpp settings/general/configurepreviewplugindialog.cpp settings/general/confirmationssettingspage.cpp settings/general/generalsettingspage.cpp settings/general/previewssettingspage.cpp settings/general/statusbarsettingspage.cpp settings/dolphinsettingsdialog.cpp settings/navigation/navigationsettingspage.cpp settings/services/servicessettingspage.cpp settings/settingspagebase.cpp settings/serviceitemdelegate.cpp settings/servicemodel.cpp settings/startup/startupsettingspage.cpp settings/trash/trashsettingspage.cpp settings/viewmodes/dolphinfontrequester.cpp settings/viewmodes/viewsettingspage.cpp settings/viewmodes/viewmodesettings.cpp settings/viewmodes/viewsettingstab.cpp statusbar/dolphinstatusbar.cpp statusbar/mountpointobserver.cpp statusbar/mountpointobservercache.cpp statusbar/spaceinfoobserver.cpp statusbar/statusbarspaceinfo.cpp views/zoomlevelinfo.cpp dolphindebug.cpp global.cpp ) if(HAVE_BALOO) set(dolphinstatic_SRCS ${dolphinstatic_SRCS} panels/information/informationpanel.cpp panels/information/informationpanelcontent.cpp panels/information/pixmapviewer.cpp panels/information/phononwidget.cpp ) endif() kconfig_add_kcfg_files(dolphinstatic_SRCS GENERATE_MOC panels/folders/dolphin_folderspanelsettings.kcfgc panels/information/dolphin_informationpanelsettings.kcfgc panels/places/dolphin_placespanelsettings.kcfgc settings/dolphin_compactmodesettings.kcfgc settings/dolphin_detailsmodesettings.kcfgc settings/dolphin_generalsettings.kcfgc settings/dolphin_iconsmodesettings.kcfgc search/dolphin_searchsettings.kcfgc settings/dolphin_versioncontrolsettings.kcfgc ) qt5_add_resources(dolphinstatic_SRCS dolphin.qrc) add_library(dolphinstatic STATIC ${dolphinstatic_SRCS}) target_include_directories(dolphinstatic SYSTEM PRIVATE ${PHONON_INCLUDES}) target_link_libraries(dolphinstatic dolphinprivate KF5::KCMUtils KF5::DBusAddons KF5::Notifications Phonon::phonon4qt5 ) if (HAVE_KACTIVITIES) target_link_libraries( dolphinstatic KF5::Activities ) endif() set(dolphin_SRCS dbusinterface.cpp main.cpp ) # Sets the icon on Windows and OSX file(GLOB ICONS_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/icons/*system-file-manager.png") ecm_add_app_icon(dolphin_SRCS ICONS ${ICONS_SRCS}) kf5_add_kdeinit_executable(dolphin ${dolphin_SRCS}) target_link_libraries(kdeinit_dolphin PRIVATE dolphinstatic dolphinprivate KF5::Crash ) include(DbusInterfaceMacros) generate_and_install_dbus_interface( kdeinit_dolphin dbusinterface.h org.freedesktop.FileManager1.xml OPTIONS -a ) install(TARGETS kdeinit_dolphin ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) install(TARGETS dolphin ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) ########################################## set(kcm_dolphinviewmodes_PART_SRCS settings/kcm/kcmdolphinviewmodes.cpp settings/viewmodes/dolphinfontrequester.cpp settings/viewmodes/viewmodesettings.cpp settings/viewmodes/viewsettingstab.cpp views/zoomlevelinfo.cpp) set(kcm_dolphinnavigation_PART_SRCS settings/kcm/kcmdolphinnavigation.cpp settings/navigation/navigationsettingspage.cpp settings/settingspagebase.cpp) set(kcm_dolphinservices_PART_SRCS settings/kcm/kcmdolphinservices.cpp settings/services/servicessettingspage.cpp settings/settingspagebase.cpp settings/serviceitemdelegate.cpp settings/servicemodel.cpp) set(kcm_dolphingeneral_PART_SRCS settings/kcm/kcmdolphingeneral.cpp settings/general/behaviorsettingspage.cpp settings/general/previewssettingspage.cpp settings/general/configurepreviewplugindialog.cpp settings/general/confirmationssettingspage.cpp settings/settingspagebase.cpp settings/serviceitemdelegate.cpp settings/servicemodel.cpp) kconfig_add_kcfg_files(kcm_dolphinviewmodes_PART_SRCS settings/dolphin_compactmodesettings.kcfgc settings/dolphin_directoryviewpropertysettings.kcfgc settings/dolphin_detailsmodesettings.kcfgc settings/dolphin_iconsmodesettings.kcfgc settings/dolphin_generalsettings.kcfgc settings/dolphin_versioncontrolsettings.kcfgc ) kconfig_add_kcfg_files(kcm_dolphinnavigation_PART_SRCS settings/dolphin_generalsettings.kcfgc) kconfig_add_kcfg_files(kcm_dolphinservices_PART_SRCS settings/dolphin_generalsettings.kcfgc settings/dolphin_versioncontrolsettings.kcfgc) kconfig_add_kcfg_files(kcm_dolphingeneral_PART_SRCS settings/dolphin_generalsettings.kcfgc) add_library(kcm_dolphinviewmodes MODULE ${kcm_dolphinviewmodes_PART_SRCS}) add_library(kcm_dolphinnavigation MODULE ${kcm_dolphinnavigation_PART_SRCS}) add_library(kcm_dolphinservices MODULE ${kcm_dolphinservices_PART_SRCS}) add_library(kcm_dolphingeneral MODULE ${kcm_dolphingeneral_PART_SRCS}) target_link_libraries(kcm_dolphinviewmodes dolphinprivate) target_link_libraries(kcm_dolphinnavigation dolphinprivate) target_link_libraries(kcm_dolphinservices dolphinprivate) target_link_libraries(kcm_dolphingeneral dolphinprivate) install(TARGETS kcm_dolphinviewmodes DESTINATION ${KDE_INSTALL_PLUGINDIR} ) install(TARGETS kcm_dolphinnavigation DESTINATION ${KDE_INSTALL_PLUGINDIR} ) install(TARGETS kcm_dolphinservices DESTINATION ${KDE_INSTALL_PLUGINDIR} ) install(TARGETS kcm_dolphingeneral DESTINATION ${KDE_INSTALL_PLUGINDIR} ) ########### install files ############### install( PROGRAMS org.kde.dolphin.desktop DESTINATION ${KDE_INSTALL_APPDIR} ) install( DIRECTORY DESTINATION "${KDE_INSTALL_FULL_DATAROOTDIR}/kglobalaccel" ) install( CODE "execute_process(COMMAND \"${CMAKE_COMMAND}\" -E create_symlink \"${KDE_INSTALL_FULL_APPDIR}/org.kde.dolphin.desktop\" \"\$ENV{DESTDIR}${KDE_INSTALL_FULL_DATAROOTDIR}/kglobalaccel/org.kde.dolphin.desktop\")" ) install( FILES settings/dolphin_directoryviewpropertysettings.kcfg settings/dolphin_generalsettings.kcfg settings/dolphin_compactmodesettings.kcfg settings/dolphin_iconsmodesettings.kcfg settings/dolphin_detailsmodesettings.kcfg settings/dolphin_versioncontrolsettings.kcfg DESTINATION ${KDE_INSTALL_KCFGDIR} ) install( FILES org.kde.dolphin.appdata.xml DESTINATION ${KDE_INSTALL_METAINFODIR} ) install( FILES settings/kcm/kcmdolphinviewmodes.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR} ) install( FILES settings/kcm/kcmdolphinnavigation.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR} ) install( FILES settings/kcm/kcmdolphinservices.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR} ) install( FILES settings/kcm/kcmdolphingeneral.desktop DESTINATION ${KDE_INSTALL_KSERVICES5DIR} ) install( FILES settings/services/servicemenu.knsrc DESTINATION ${KDE_INSTALL_CONFDIR} ) install( PROGRAMS settings/services/servicemenuinstallation DESTINATION ${KDE_INSTALL_BINDIR} ) install( PROGRAMS settings/services/servicemenudeinstallation DESTINATION ${KDE_INSTALL_BINDIR} ) if(BUILD_TESTING) find_package(Qt5Test ${QT_MIN_VERSION} CONFIG REQUIRED) add_subdirectory(tests) endif() diff --git a/src/dbusinterface.cpp b/src/dbusinterface.cpp index c780bc7cd..4e24354ab 100644 --- a/src/dbusinterface.cpp +++ b/src/dbusinterface.cpp @@ -1,64 +1,73 @@ /* * Copyright 2015 Ashish Bansal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dbusinterface.h" #include "global.h" +#include "dolphin_generalsettings.h" #include +#include #include +#include #include DBusInterface::DBusInterface() : QObject() { QDBusConnection::sessionBus().registerObject(QStringLiteral("/org/freedesktop/FileManager1"), this, QDBusConnection::ExportScriptableContents | QDBusConnection::ExportAdaptors); QDBusConnection::sessionBus().interface()->registerService(QStringLiteral("org.freedesktop.FileManager1"), QDBusConnectionInterface::QueueService); } void DBusInterface::ShowFolders(const QStringList& uriList, const QString& startUpId) { Q_UNUSED(startUpId); const QList urls = Dolphin::validateUris(uriList); if (urls.isEmpty()) { return; } - Dolphin::openNewWindow(urls); + const auto serviceName = QStringLiteral("org.kde.dolphin-%1").arg(QCoreApplication::applicationPid()); + if(!Dolphin::attachToExistingInstance(urls, false, GeneralSettings::splitView(), serviceName)) { + Dolphin::openNewWindow(urls); + } } void DBusInterface::ShowItems(const QStringList& uriList, const QString& startUpId) { Q_UNUSED(startUpId); const QList urls = Dolphin::validateUris(uriList); if (urls.isEmpty()) { return; } - Dolphin::openNewWindow(urls, nullptr, Dolphin::OpenNewWindowFlag::Select); + const auto serviceName = QStringLiteral("org.kde.dolphin-%1").arg(QCoreApplication::applicationPid()); + if(!Dolphin::attachToExistingInstance(urls, true, GeneralSettings::splitView(), serviceName)) { + Dolphin::openNewWindow(urls); + }; } void DBusInterface::ShowItemProperties(const QStringList& uriList, const QString& startUpId) { Q_UNUSED(startUpId); const QList urls = Dolphin::validateUris(uriList); if (!urls.isEmpty()) { KPropertiesDialog::showDialog(urls); } } diff --git a/src/dolphinmainwindow.cpp b/src/dolphinmainwindow.cpp index b57ed4fc4..385b61a2a 100644 --- a/src/dolphinmainwindow.cpp +++ b/src/dolphinmainwindow.cpp @@ -1,1709 +1,1736 @@ /*************************************************************************** * Copyright (C) 2006 by Peter Penz * * Copyright (C) 2006 by Stefan Monov * * Copyright (C) 2006 by Cvetoslav Ludmiloff * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ #include "dolphinmainwindow.h" #include "config-terminal.h" #include "global.h" #include "dolphinbookmarkhandler.h" #include "dolphindockwidget.h" #include "dolphincontextmenu.h" #include "dolphinnewfilemenu.h" #include "dolphinrecenttabsmenu.h" #include "dolphinviewcontainer.h" #include "dolphintabpage.h" #include "middleclickactioneventfilter.h" #include "panels/folders/folderspanel.h" #include "panels/places/placespanel.h" #include "panels/information/informationpanel.h" #include "panels/terminal/terminalpanel.h" #include "settings/dolphinsettingsdialog.h" #include "statusbar/dolphinstatusbar.h" #include "views/dolphinviewactionhandler.h" #include "views/dolphinremoteencoding.h" #include "views/draganddrophelper.h" #include "views/viewproperties.h" #include "views/dolphinnewfilemenuobserver.h" #include "dolphin_generalsettings.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include #include #include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { // Used for GeneralSettings::version() to determine whether // an updated version of Dolphin is running. const int CurrentDolphinVersion = 200; } DolphinMainWindow::DolphinMainWindow() : KXmlGuiWindow(nullptr), m_newFileMenu(nullptr), m_tabWidget(nullptr), m_activeViewContainer(nullptr), m_actionHandler(nullptr), m_remoteEncoding(nullptr), m_settingsDialog(), m_bookmarkHandler(nullptr), m_controlButton(nullptr), m_updateToolBarTimer(nullptr), m_lastHandleUrlStatJob(nullptr), m_terminalPanel(nullptr), m_placesPanel(nullptr), m_tearDownFromPlacesRequested(false) { Q_INIT_RESOURCE(dolphin); setComponentName(QStringLiteral("dolphin"), QGuiApplication::applicationDisplayName()); setObjectName(QStringLiteral("Dolphin#")); connect(&DolphinNewFileMenuObserver::instance(), &DolphinNewFileMenuObserver::errorMessage, this, &DolphinMainWindow::showErrorMessage); KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self(); undoManager->setUiInterface(new UndoUiInterface()); connect(undoManager, QOverload::of(&KIO::FileUndoManager::undoAvailable), this, &DolphinMainWindow::slotUndoAvailable); connect(undoManager, &KIO::FileUndoManager::undoTextChanged, this, &DolphinMainWindow::slotUndoTextChanged); connect(undoManager, &KIO::FileUndoManager::jobRecordingStarted, this, &DolphinMainWindow::clearStatusBar); connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinMainWindow::showCommand); GeneralSettings* generalSettings = GeneralSettings::self(); const bool firstRun = (generalSettings->version() < 200); if (firstRun) { generalSettings->setViewPropsTimestamp(QDateTime::currentDateTime()); } setAcceptDrops(true); m_tabWidget = new DolphinTabWidget(this); m_tabWidget->setObjectName("tabWidget"); connect(m_tabWidget, &DolphinTabWidget::activeViewChanged, this, &DolphinMainWindow::activeViewChanged); connect(m_tabWidget, &DolphinTabWidget::tabCountChanged, this, &DolphinMainWindow::tabCountChanged); connect(m_tabWidget, &DolphinTabWidget::currentUrlChanged, this, &DolphinMainWindow::updateWindowTitle); setCentralWidget(m_tabWidget); setupActions(); m_actionHandler = new DolphinViewActionHandler(actionCollection(), this); connect(m_actionHandler, &DolphinViewActionHandler::actionBeingHandled, this, &DolphinMainWindow::clearStatusBar); connect(m_actionHandler, &DolphinViewActionHandler::createDirectoryTriggered, this, &DolphinMainWindow::createDirectory); m_remoteEncoding = new DolphinRemoteEncoding(this, m_actionHandler); connect(this, &DolphinMainWindow::urlChanged, m_remoteEncoding, &DolphinRemoteEncoding::slotAboutToOpenUrl); setupDockWidgets(); setupGUI(Keys | Save | Create | ToolBar); stateChanged(QStringLiteral("new_file")); QClipboard* clipboard = QApplication::clipboard(); connect(clipboard, &QClipboard::dataChanged, this, &DolphinMainWindow::updatePasteAction); QAction* showFilterBarAction = actionCollection()->action(QStringLiteral("show_filter_bar")); showFilterBarAction->setChecked(generalSettings->filterBar()); if (firstRun) { menuBar()->setVisible(false); // Assure a proper default size if Dolphin runs the first time resize(750, 500); } const bool showMenu = !menuBar()->isHidden(); QAction* showMenuBarAction = actionCollection()->action(KStandardAction::name(KStandardAction::ShowMenubar)); showMenuBarAction->setChecked(showMenu); // workaround for bug #171080 if (!showMenu) { createControlButton(); } // enable middle-click on back/forward/up to open in a new tab auto *middleClickEventFilter = new MiddleClickActionEventFilter(this); connect(middleClickEventFilter, &MiddleClickActionEventFilter::actionMiddleClicked, this, &DolphinMainWindow::slotToolBarActionMiddleClicked); toolBar()->installEventFilter(middleClickEventFilter); } DolphinMainWindow::~DolphinMainWindow() { } QVector DolphinMainWindow::viewContainers() const { QVector viewContainers; viewContainers.reserve(m_tabWidget->count()); for (int i = 0; i < m_tabWidget->count(); ++i) { viewContainers << m_tabWidget->tabPageAt(i)->activeViewContainer(); } return viewContainers; } void DolphinMainWindow::openDirectories(const QList& dirs, bool splitView) { m_tabWidget->openDirectories(dirs, splitView); } +void DolphinMainWindow::openDirectories(const QStringList& dirs, bool splitView) +{ + openDirectories(QUrl::fromStringList(dirs), splitView); +} + void DolphinMainWindow::openFiles(const QList& files, bool splitView) { m_tabWidget->openFiles(files, splitView); } +void DolphinMainWindow::openFiles(const QStringList& files, bool splitView) +{ + openFiles(QUrl::fromStringList(files), splitView); +} + +void DolphinMainWindow::activateWindow() +{ + KStartupInfo::setNewStartupId(window(), KStartupInfo::startupId()); + KWindowSystem::activateWindow(window()->effectiveWinId()); +} + void DolphinMainWindow::showCommand(CommandType command) { DolphinStatusBar* statusBar = m_activeViewContainer->statusBar(); switch (command) { case KIO::FileUndoManager::Copy: statusBar->setText(i18nc("@info:status", "Successfully copied.")); break; case KIO::FileUndoManager::Move: statusBar->setText(i18nc("@info:status", "Successfully moved.")); break; case KIO::FileUndoManager::Link: statusBar->setText(i18nc("@info:status", "Successfully linked.")); break; case KIO::FileUndoManager::Trash: statusBar->setText(i18nc("@info:status", "Successfully moved to trash.")); break; case KIO::FileUndoManager::Rename: statusBar->setText(i18nc("@info:status", "Successfully renamed.")); break; case KIO::FileUndoManager::Mkdir: statusBar->setText(i18nc("@info:status", "Created folder.")); break; default: break; } } void DolphinMainWindow::pasteIntoFolder() { m_activeViewContainer->view()->pasteIntoFolder(); } void DolphinMainWindow::changeUrl(const QUrl &url) { if (!KProtocolManager::supportsListing(url)) { // The URL navigator only checks for validity, not // if the URL can be listed. An error message is // shown due to DolphinViewContainer::restoreView(). return; } m_activeViewContainer->setUrl(url); updateEditActions(); updatePasteAction(); updateViewActions(); updateGoActions(); emit urlChanged(url); } void DolphinMainWindow::slotTerminalDirectoryChanged(const QUrl& url) { if (m_tearDownFromPlacesRequested && url == QUrl::fromLocalFile(QDir::homePath())) { m_placesPanel->proceedWithTearDown(); m_tearDownFromPlacesRequested = false; } m_activeViewContainer->setAutoGrabFocus(false); changeUrl(url); m_activeViewContainer->setAutoGrabFocus(true); } void DolphinMainWindow::slotEditableStateChanged(bool editable) { KToggleAction* editableLocationAction = static_cast(actionCollection()->action(QStringLiteral("editable_location"))); editableLocationAction->setChecked(editable); } void DolphinMainWindow::slotSelectionChanged(const KFileItemList& selection) { updateEditActions(); const int selectedUrlsCount = m_tabWidget->currentTabPage()->selectedItemsCount(); QAction* compareFilesAction = actionCollection()->action(QStringLiteral("compare_files")); if (selectedUrlsCount == 2) { compareFilesAction->setEnabled(isKompareInstalled()); } else { compareFilesAction->setEnabled(false); } emit selectionChanged(selection); } void DolphinMainWindow::updateHistory() { const KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); const int index = urlNavigator->historyIndex(); QAction* backAction = actionCollection()->action(KStandardAction::name(KStandardAction::Back)); if (backAction) { backAction->setToolTip(i18nc("@info", "Go back")); backAction->setEnabled(index < urlNavigator->historySize() - 1); } QAction* forwardAction = actionCollection()->action(KStandardAction::name(KStandardAction::Forward)); if (forwardAction) { forwardAction->setToolTip(i18nc("@info", "Go forward")); forwardAction->setEnabled(index > 0); } } void DolphinMainWindow::updateFilterBarAction(bool show) { QAction* showFilterBarAction = actionCollection()->action(QStringLiteral("show_filter_bar")); showFilterBarAction->setChecked(show); } void DolphinMainWindow::openNewMainWindow() { Dolphin::openNewWindow({m_activeViewContainer->url()}, this); } void DolphinMainWindow::openNewActivatedTab() { m_tabWidget->openNewActivatedTab(); } void DolphinMainWindow::openNewTab(const QUrl& url, DolphinTabWidget::TabPlacement tabPlacement) { m_tabWidget->openNewTab(url, QUrl(), tabPlacement); } void DolphinMainWindow::openNewTabAfterCurrentTab(const QUrl& url) { m_tabWidget->openNewTab(url, QUrl(), DolphinTabWidget::AfterCurrentTab); } void DolphinMainWindow::openNewTabAfterLastTab(const QUrl& url) { m_tabWidget->openNewTab(url, QUrl(), DolphinTabWidget::AfterLastTab); } void DolphinMainWindow::openInNewTab() { const KFileItemList& list = m_activeViewContainer->view()->selectedItems(); bool tabCreated = false; foreach (const KFileItem& item, list) { const QUrl& url = DolphinView::openItemAsFolderUrl(item); if (!url.isEmpty()) { openNewTabAfterCurrentTab(url); tabCreated = true; } } // if no new tab has been created from the selection // open the current directory in a new tab if (!tabCreated) { openNewTabAfterCurrentTab(m_activeViewContainer->url()); } } void DolphinMainWindow::openInNewWindow() { QUrl newWindowUrl; const KFileItemList list = m_activeViewContainer->view()->selectedItems(); if (list.isEmpty()) { newWindowUrl = m_activeViewContainer->url(); } else if (list.count() == 1) { const KFileItem& item = list.first(); newWindowUrl = DolphinView::openItemAsFolderUrl(item); } if (!newWindowUrl.isEmpty()) { Dolphin::openNewWindow({newWindowUrl}, this); } } void DolphinMainWindow::showTarget() { const auto link = m_activeViewContainer->view()->selectedItems().at(0); const auto linkLocationDir = QFileInfo(link.localPath()).absoluteDir(); auto linkDestination = link.linkDest(); if (QFileInfo(linkDestination).isRelative()) { linkDestination = linkLocationDir.filePath(linkDestination); } if (QFileInfo::exists(linkDestination)) { KIO::highlightInFileManager({QUrl::fromLocalFile(linkDestination).adjusted(QUrl::StripTrailingSlash)}); } else { m_activeViewContainer->showMessage(xi18nc("@info", "Could not access %1.", linkDestination), DolphinViewContainer::Warning); } } void DolphinMainWindow::showEvent(QShowEvent* event) { KXmlGuiWindow::showEvent(event); if (!event->spontaneous()) { m_activeViewContainer->view()->setFocus(); } } void DolphinMainWindow::closeEvent(QCloseEvent* event) { // Find out if Dolphin is closed directly by the user or // by the session manager because the session is closed bool closedByUser = true; if (qApp->isSavingSession()) { closedByUser = false; } if (m_tabWidget->count() > 1 && GeneralSettings::confirmClosingMultipleTabs() && closedByUser) { // Ask the user if he really wants to quit and close all tabs. // Open a confirmation dialog with 3 buttons: // QDialogButtonBox::Yes -> Quit // QDialogButtonBox::No -> Close only the current tab // QDialogButtonBox::Cancel -> do nothing QDialog *dialog = new QDialog(this, Qt::Dialog); dialog->setWindowTitle(i18nc("@title:window", "Confirmation")); dialog->setModal(true); QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel); KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), KGuiItem(i18nc("@action:button 'Quit Dolphin' button", "&Quit %1", QGuiApplication::applicationDisplayName()), QIcon::fromTheme(QStringLiteral("application-exit")))); KGuiItem::assign(buttons->button(QDialogButtonBox::No), KGuiItem(i18n("C&lose Current Tab"), QIcon::fromTheme(QStringLiteral("tab-close")))); KGuiItem::assign(buttons->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel()); buttons->button(QDialogButtonBox::Yes)->setDefault(true); bool doNotAskAgainCheckboxResult = false; const auto result = KMessageBox::createKMessageBox(dialog, buttons, QMessageBox::Warning, i18n("You have multiple tabs open in this window, are you sure you want to quit?"), QStringList(), i18n("Do not ask again"), &doNotAskAgainCheckboxResult, KMessageBox::Notify); if (doNotAskAgainCheckboxResult) { GeneralSettings::setConfirmClosingMultipleTabs(false); } switch (result) { case QDialogButtonBox::Yes: // Quit break; case QDialogButtonBox::No: // Close only the current tab m_tabWidget->closeTab(); Q_FALLTHROUGH(); default: event->ignore(); return; } } if (m_terminalPanel->hasProgramRunning() && GeneralSettings::confirmClosingTerminalRunningProgram() && closedByUser) { // Ask if the user really wants to quit Dolphin with a program that is still running in the Terminal panel // Open a confirmation dialog with 3 buttons: // QDialogButtonBox::Yes -> Quit // QDialogButtonBox::No -> Show Terminal Panel // QDialogButtonBox::Cancel -> do nothing QDialog *dialog = new QDialog(this, Qt::Dialog); dialog->setWindowTitle(i18nc("@title:window", "Confirmation")); dialog->setModal(true); auto standardButtons = QDialogButtonBox::Yes | QDialogButtonBox::Cancel; if (!m_terminalPanel->isVisible()) { standardButtons |= QDialogButtonBox::No; } QDialogButtonBox *buttons = new QDialogButtonBox(standardButtons); KGuiItem::assign(buttons->button(QDialogButtonBox::Yes), KStandardGuiItem::quit()); if (!m_terminalPanel->isVisible()) { KGuiItem::assign( buttons->button(QDialogButtonBox::No), KGuiItem(i18n("Show &Terminal Panel"), QIcon::fromTheme(QStringLiteral("utilities-terminal")))); } KGuiItem::assign(buttons->button(QDialogButtonBox::Cancel), KStandardGuiItem::cancel()); bool doNotAskAgainCheckboxResult = false; const auto result = KMessageBox::createKMessageBox( dialog, buttons, QMessageBox::Warning, i18n("The program '%1' is still running in the Terminal panel. Are you sure you want to quit?", m_terminalPanel->runningProgramName()), QStringList(), i18n("Do not ask again"), &doNotAskAgainCheckboxResult, KMessageBox::Dangerous); if (doNotAskAgainCheckboxResult) { GeneralSettings::setConfirmClosingTerminalRunningProgram(false); } switch (result) { case QDialogButtonBox::Yes: // Quit break; case QDialogButtonBox::No: actionCollection()->action("show_terminal_panel")->trigger(); // Do not quit, ignore quit event Q_FALLTHROUGH(); default: event->ignore(); return; } } GeneralSettings::setVersion(CurrentDolphinVersion); GeneralSettings::self()->save(); KXmlGuiWindow::closeEvent(event); } void DolphinMainWindow::saveProperties(KConfigGroup& group) { m_tabWidget->saveProperties(group); } void DolphinMainWindow::readProperties(const KConfigGroup& group) { m_tabWidget->readProperties(group); } void DolphinMainWindow::updateNewMenu() { m_newFileMenu->setViewShowsHiddenFiles(activeViewContainer()->view()->hiddenFilesShown()); m_newFileMenu->checkUpToDate(); m_newFileMenu->setPopupFiles(activeViewContainer()->url()); } void DolphinMainWindow::createDirectory() { m_newFileMenu->setViewShowsHiddenFiles(activeViewContainer()->view()->hiddenFilesShown()); m_newFileMenu->setPopupFiles(activeViewContainer()->url()); m_newFileMenu->createDirectory(); } void DolphinMainWindow::quit() { close(); } void DolphinMainWindow::showErrorMessage(const QString& message) { m_activeViewContainer->showMessage(message, DolphinViewContainer::Error); } void DolphinMainWindow::slotUndoAvailable(bool available) { QAction* undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); if (undoAction) { undoAction->setEnabled(available); } } void DolphinMainWindow::slotUndoTextChanged(const QString& text) { QAction* undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); if (undoAction) { undoAction->setText(text); } } void DolphinMainWindow::undo() { clearStatusBar(); KIO::FileUndoManager::self()->uiInterface()->setParentWidget(this); KIO::FileUndoManager::self()->undo(); } void DolphinMainWindow::cut() { m_activeViewContainer->view()->cutSelectedItems(); } void DolphinMainWindow::copy() { m_activeViewContainer->view()->copySelectedItems(); } void DolphinMainWindow::paste() { m_activeViewContainer->view()->paste(); } void DolphinMainWindow::find() { m_activeViewContainer->setSearchModeEnabled(true); } void DolphinMainWindow::updatePasteAction() { QAction* pasteAction = actionCollection()->action(KStandardAction::name(KStandardAction::Paste)); QPair pasteInfo = m_activeViewContainer->view()->pasteInfo(); pasteAction->setEnabled(pasteInfo.first); pasteAction->setText(pasteInfo.second); } void DolphinMainWindow::slotDirectoryLoadingCompleted() { updatePasteAction(); } void DolphinMainWindow::slotToolBarActionMiddleClicked(QAction *action) { if (action == actionCollection()->action(KStandardAction::name(KStandardAction::Back))) { goBackInNewTab(); } else if (action == actionCollection()->action(KStandardAction::name(KStandardAction::Forward))) { goForwardInNewTab(); } else if (action == actionCollection()->action(QStringLiteral("go_up"))) { goUpInNewTab(); } else if (action == actionCollection()->action(QStringLiteral("go_home"))) { goHomeInNewTab(); } } void DolphinMainWindow::selectAll() { clearStatusBar(); // if the URL navigator is editable and focused, select the whole // URL instead of all items of the view KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); QLineEdit* lineEdit = urlNavigator->editor()->lineEdit(); const bool selectUrl = urlNavigator->isUrlEditable() && lineEdit->hasFocus(); if (selectUrl) { lineEdit->selectAll(); } else { m_activeViewContainer->view()->selectAll(); } } void DolphinMainWindow::invertSelection() { clearStatusBar(); m_activeViewContainer->view()->invertSelection(); } void DolphinMainWindow::toggleSplitView() { DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); tabPage->setSplitViewEnabled(!tabPage->splitViewEnabled()); updateViewActions(); } void DolphinMainWindow::toggleSplitStash() { DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); tabPage->setSplitViewEnabled(false); tabPage->setSplitViewEnabled(true, QUrl("stash:/")); } void DolphinMainWindow::reloadView() { clearStatusBar(); m_activeViewContainer->reload(); m_activeViewContainer->statusBar()->updateSpaceInfo(); } void DolphinMainWindow::stopLoading() { m_activeViewContainer->view()->stopLoading(); } void DolphinMainWindow::enableStopAction() { actionCollection()->action(QStringLiteral("stop"))->setEnabled(true); } void DolphinMainWindow::disableStopAction() { actionCollection()->action(QStringLiteral("stop"))->setEnabled(false); } void DolphinMainWindow::showFilterBar() { m_activeViewContainer->setFilterBarVisible(true); } void DolphinMainWindow::toggleEditLocation() { clearStatusBar(); QAction* action = actionCollection()->action(QStringLiteral("editable_location")); KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); urlNavigator->setUrlEditable(action->isChecked()); } void DolphinMainWindow::replaceLocation() { KUrlNavigator* navigator = m_activeViewContainer->urlNavigator(); QLineEdit* lineEdit = navigator->editor()->lineEdit(); // If the text field currently has focus and everything is selected, // pressing the keyboard shortcut returns the whole thing to breadcrumb mode if (navigator->isUrlEditable() && lineEdit->hasFocus() && lineEdit->selectedText() == lineEdit->text() ) { navigator->setUrlEditable(false); } else { navigator->setUrlEditable(true); navigator->setFocus(); lineEdit->selectAll(); } } void DolphinMainWindow::togglePanelLockState() { const bool newLockState = !GeneralSettings::lockPanels(); foreach (QObject* child, children()) { DolphinDockWidget* dock = qobject_cast(child); if (dock) { dock->setLocked(newLockState); } } GeneralSettings::setLockPanels(newLockState); } void DolphinMainWindow::slotTerminalPanelVisibilityChanged() { if (m_terminalPanel->isHiddenInVisibleWindow()) { m_activeViewContainer->view()->setFocus(); } } void DolphinMainWindow::goBack() { KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); urlNavigator->goBack(); if (urlNavigator->locationState().isEmpty()) { // An empty location state indicates a redirection URL, // which must be skipped too urlNavigator->goBack(); } } void DolphinMainWindow::goForward() { m_activeViewContainer->urlNavigator()->goForward(); } void DolphinMainWindow::goUp() { m_activeViewContainer->urlNavigator()->goUp(); } void DolphinMainWindow::goHome() { m_activeViewContainer->urlNavigator()->goHome(); } void DolphinMainWindow::goBackInNewTab() { KUrlNavigator* urlNavigator = activeViewContainer()->urlNavigator(); const int index = urlNavigator->historyIndex() + 1; openNewTabAfterCurrentTab(urlNavigator->locationUrl(index)); } void DolphinMainWindow::goForwardInNewTab() { KUrlNavigator* urlNavigator = activeViewContainer()->urlNavigator(); const int index = urlNavigator->historyIndex() - 1; openNewTabAfterCurrentTab(urlNavigator->locationUrl(index)); } void DolphinMainWindow::goUpInNewTab() { const QUrl currentUrl = activeViewContainer()->urlNavigator()->locationUrl(); openNewTabAfterCurrentTab(KIO::upUrl(currentUrl)); } void DolphinMainWindow::goHomeInNewTab() { openNewTabAfterCurrentTab(Dolphin::homeUrl()); } void DolphinMainWindow::compareFiles() { const KFileItemList items = m_tabWidget->currentTabPage()->selectedItems(); if (items.count() != 2) { // The action is disabled in this case, but it could have been triggered // via D-Bus, see https://bugs.kde.org/show_bug.cgi?id=325517 return; } QUrl urlA = items.at(0).url(); QUrl urlB = items.at(1).url(); QString command(QStringLiteral("kompare -c \"")); command.append(urlA.toDisplayString(QUrl::PreferLocalFile)); command.append("\" \""); command.append(urlB.toDisplayString(QUrl::PreferLocalFile)); command.append('\"'); KRun::runCommand(command, QStringLiteral("Kompare"), QStringLiteral("kompare"), this); } void DolphinMainWindow::toggleShowMenuBar() { const bool visible = menuBar()->isVisible(); menuBar()->setVisible(!visible); if (visible) { createControlButton(); } else { deleteControlButton(); } } void DolphinMainWindow::openTerminal() { QString dir(QDir::homePath()); // If the given directory is not local, it can still be the URL of an // ioslave using UDS_LOCAL_PATH which to be converted first. KIO::StatJob* statJob = KIO::mostLocalUrl(m_activeViewContainer->url()); KJobWidgets::setWindow(statJob, this); statJob->exec(); QUrl url = statJob->mostLocalUrl(); //If the URL is local after the above conversion, set the directory. if (url.isLocalFile()) { dir = url.toLocalFile(); } KToolInvocation::invokeTerminal(QString(), dir); } void DolphinMainWindow::editSettings() { if (!m_settingsDialog) { DolphinViewContainer* container = activeViewContainer(); container->view()->writeSettings(); const QUrl url = container->url(); DolphinSettingsDialog* settingsDialog = new DolphinSettingsDialog(url, this); connect(settingsDialog, &DolphinSettingsDialog::settingsChanged, this, &DolphinMainWindow::refreshViews); settingsDialog->setAttribute(Qt::WA_DeleteOnClose); settingsDialog->show(); m_settingsDialog = settingsDialog; } else { m_settingsDialog.data()->raise(); } } void DolphinMainWindow::handleUrl(const QUrl& url) { delete m_lastHandleUrlStatJob; m_lastHandleUrlStatJob = nullptr; if (url.isLocalFile() && QFileInfo(url.toLocalFile()).isDir()) { activeViewContainer()->setUrl(url); } else if (KProtocolManager::supportsListing(url)) { // stat the URL to see if it is a dir or not m_lastHandleUrlStatJob = KIO::stat(url, KIO::HideProgressInfo); if (m_lastHandleUrlStatJob->uiDelegate()) { KJobWidgets::setWindow(m_lastHandleUrlStatJob, this); } connect(m_lastHandleUrlStatJob, &KIO::Job::result, this, &DolphinMainWindow::slotHandleUrlStatFinished); } else { new KRun(url, this); // Automatically deletes itself after being finished } } void DolphinMainWindow::slotHandleUrlStatFinished(KJob* job) { m_lastHandleUrlStatJob = nullptr; const KIO::UDSEntry entry = static_cast(job)->statResult(); const QUrl url = static_cast(job)->url(); if (entry.isDir()) { activeViewContainer()->setUrl(url); } else { new KRun(url, this); // Automatically deletes itself after being finished } } void DolphinMainWindow::slotWriteStateChanged(bool isFolderWritable) { // trash:/ is writable but we don't want to create new items in it. // TODO: remove the trash check once https://phabricator.kde.org/T8234 is implemented newFileMenu()->setEnabled(isFolderWritable && m_activeViewContainer->url().scheme() != QLatin1String("trash")); } void DolphinMainWindow::openContextMenu(const QPoint& pos, const KFileItem& item, const QUrl& url, const QList& customActions) { QPointer contextMenu = new DolphinContextMenu(this, pos, item, url); contextMenu.data()->setCustomActions(customActions); const DolphinContextMenu::Command command = contextMenu.data()->open(); switch (command) { case DolphinContextMenu::OpenParentFolder: changeUrl(KIO::upUrl(item.url())); m_activeViewContainer->view()->markUrlsAsSelected({item.url()}); m_activeViewContainer->view()->markUrlAsCurrent(item.url()); break; case DolphinContextMenu::OpenParentFolderInNewWindow: Dolphin::openNewWindow({item.url()}, this, Dolphin::OpenNewWindowFlag::Select); break; case DolphinContextMenu::OpenParentFolderInNewTab: openNewTabAfterLastTab(KIO::upUrl(item.url())); break; case DolphinContextMenu::None: default: break; } // Delete the menu, unless it has been deleted in its own nested event loop already. if (contextMenu) { contextMenu->deleteLater(); } } void DolphinMainWindow::updateControlMenu() { QMenu* menu = qobject_cast(sender()); Q_ASSERT(menu); // All actions get cleared by QMenu::clear(). This includes the sub-menus // because 'menu' is their parent. menu->clear(); KActionCollection* ac = actionCollection(); // Add "Create New" menu menu->addMenu(m_newFileMenu->menu()); menu->addSeparator(); // Overwrite Find action to Search action QAction *searchAction = ac->action(KStandardAction::name(KStandardAction::Find)); searchAction->setText(i18n("Search...")); // Add "Edit" actions bool added = addActionToMenu(ac->action(KStandardAction::name(KStandardAction::Undo)), menu) | addActionToMenu(searchAction, menu) | addActionToMenu(ac->action(KStandardAction::name(KStandardAction::SelectAll)), menu) | addActionToMenu(ac->action(QStringLiteral("invert_selection")), menu); if (added) { menu->addSeparator(); } // Add "View" actions if (!GeneralSettings::showZoomSlider()) { addActionToMenu(ac->action(KStandardAction::name(KStandardAction::ZoomIn)), menu); addActionToMenu(ac->action(KStandardAction::name(KStandardAction::ZoomOut)), menu); menu->addSeparator(); } added = addActionToMenu(ac->action(QStringLiteral("sort")), menu) | addActionToMenu(ac->action(QStringLiteral("view_mode")), menu) | addActionToMenu(ac->action(QStringLiteral("additional_info")), menu) | addActionToMenu(ac->action(QStringLiteral("show_preview")), menu) | addActionToMenu(ac->action(QStringLiteral("show_in_groups")), menu) | addActionToMenu(ac->action(QStringLiteral("show_hidden_files")), menu); if (added) { menu->addSeparator(); } added = addActionToMenu(ac->action(QStringLiteral("split_view")), menu) | addActionToMenu(ac->action(KStandardAction::name(KStandardAction::Redisplay)), menu) | addActionToMenu(ac->action(QStringLiteral("view_properties")), menu); if (added) { menu->addSeparator(); } addActionToMenu(ac->action(QStringLiteral("panels")), menu); QMenu* locationBarMenu = new QMenu(i18nc("@action:inmenu", "Location Bar"), menu); locationBarMenu->addAction(ac->action(QStringLiteral("editable_location"))); locationBarMenu->addAction(ac->action(QStringLiteral("replace_location"))); menu->addMenu(locationBarMenu); menu->addSeparator(); // Add "Go" menu QMenu* goMenu = new QMenu(i18nc("@action:inmenu", "Go"), menu); goMenu->addAction(ac->action(KStandardAction::name(KStandardAction::Back))); goMenu->addAction(ac->action(KStandardAction::name(KStandardAction::Forward))); goMenu->addAction(ac->action(KStandardAction::name(KStandardAction::Up))); goMenu->addAction(ac->action(KStandardAction::name(KStandardAction::Home))); goMenu->addAction(ac->action(QStringLiteral("closed_tabs"))); KActionMenu *bookmarkMenu = new KActionMenu(i18nc("@title:menu", "&Bookmarks"), goMenu); m_bookmarkHandler->fillControlMenu(bookmarkMenu->menu(), ac); goMenu->addAction(bookmarkMenu); menu->addMenu(goMenu); // Add "Tool" menu QMenu* toolsMenu = new QMenu(i18nc("@action:inmenu", "Tools"), menu); toolsMenu->addAction(ac->action(QStringLiteral("show_filter_bar"))); toolsMenu->addAction(ac->action(QStringLiteral("compare_files"))); toolsMenu->addAction(ac->action(QStringLiteral("open_terminal"))); toolsMenu->addAction(ac->action(QStringLiteral("change_remote_encoding"))); menu->addMenu(toolsMenu); // Add "Settings" menu entries addActionToMenu(ac->action(KStandardAction::name(KStandardAction::KeyBindings)), menu); addActionToMenu(ac->action(KStandardAction::name(KStandardAction::ConfigureToolbars)), menu); addActionToMenu(ac->action(KStandardAction::name(KStandardAction::Preferences)), menu); // Add "Help" menu auto helpMenu = new KHelpMenu(menu); menu->addMenu(helpMenu->menu()); menu->addSeparator(); addActionToMenu(ac->action(KStandardAction::name(KStandardAction::ShowMenubar)), menu); } void DolphinMainWindow::updateToolBar() { if (!menuBar()->isVisible()) { createControlButton(); } } void DolphinMainWindow::slotControlButtonDeleted() { m_controlButton = nullptr; m_updateToolBarTimer->start(); } void DolphinMainWindow::slotPlaceActivated(const QUrl& url) { DolphinViewContainer* view = activeViewContainer(); if (view->url() == url) { // We can end up here if the user clicked a device in the Places Panel // which had been unmounted earlier, see https://bugs.kde.org/show_bug.cgi?id=161385. reloadView(); } else { changeUrl(url); } } void DolphinMainWindow::closedTabsCountChanged(unsigned int count) { actionCollection()->action(QStringLiteral("undo_close_tab"))->setEnabled(count > 0); } void DolphinMainWindow::activeViewChanged(DolphinViewContainer* viewContainer) { DolphinViewContainer* oldViewContainer = m_activeViewContainer; Q_ASSERT(viewContainer); m_activeViewContainer = viewContainer; if (oldViewContainer) { // Disconnect all signals between the old view container (container, // view and url navigator) and main window. oldViewContainer->disconnect(this); oldViewContainer->view()->disconnect(this); oldViewContainer->urlNavigator()->disconnect(this); // except the requestItemInfo so that on hover the information panel can still be updated connect(oldViewContainer->view(), &DolphinView::requestItemInfo, this, &DolphinMainWindow::requestItemInfo); } connectViewSignals(viewContainer); m_actionHandler->setCurrentView(viewContainer->view()); updateHistory(); updateEditActions(); updatePasteAction(); updateViewActions(); updateGoActions(); const QUrl url = viewContainer->url(); emit urlChanged(url); } void DolphinMainWindow::tabCountChanged(int count) { const bool enableTabActions = (count > 1); actionCollection()->action(QStringLiteral("activate_next_tab"))->setEnabled(enableTabActions); actionCollection()->action(QStringLiteral("activate_prev_tab"))->setEnabled(enableTabActions); } void DolphinMainWindow::updateWindowTitle() { const QString newTitle = m_activeViewContainer->caption(); if (windowTitle() != newTitle) { setWindowTitle(newTitle); } } void DolphinMainWindow::slotStorageTearDownFromPlacesRequested(const QString& mountPath) { if (m_terminalPanel->currentWorkingDirectory().startsWith(mountPath)) { m_tearDownFromPlacesRequested = true; m_terminalPanel->goHome(); // m_placesPanel->proceedWithTearDown() will be called in slotTerminalDirectoryChanged } else { m_placesPanel->proceedWithTearDown(); } } void DolphinMainWindow::slotStorageTearDownExternallyRequested(const QString& mountPath) { if (m_terminalPanel->currentWorkingDirectory().startsWith(mountPath)) { m_tearDownFromPlacesRequested = false; m_terminalPanel->goHome(); } } void DolphinMainWindow::setupActions() { // setup 'File' menu m_newFileMenu = new DolphinNewFileMenu(actionCollection(), this); QMenu* menu = m_newFileMenu->menu(); menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New")); menu->setIcon(QIcon::fromTheme(QStringLiteral("document-new"))); m_newFileMenu->setDelayed(false); connect(menu, &QMenu::aboutToShow, this, &DolphinMainWindow::updateNewMenu); QAction* newWindow = KStandardAction::openNew(this, &DolphinMainWindow::openNewMainWindow, actionCollection()); newWindow->setText(i18nc("@action:inmenu File", "New &Window")); newWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); QAction* newTab = actionCollection()->addAction(QStringLiteral("new_tab")); newTab->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); newTab->setText(i18nc("@action:inmenu File", "New Tab")); actionCollection()->setDefaultShortcuts(newTab, {Qt::CTRL + Qt::Key_T, Qt::CTRL + Qt::SHIFT + Qt::Key_N}); connect(newTab, &QAction::triggered, this, &DolphinMainWindow::openNewActivatedTab); QAction* closeTab = KStandardAction::close(m_tabWidget, QOverload<>::of(&DolphinTabWidget::closeTab), actionCollection()); closeTab->setText(i18nc("@action:inmenu File", "Close Tab")); KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection()); // setup 'Edit' menu KStandardAction::undo(this, &DolphinMainWindow::undo, actionCollection()); KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection()); KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection()); QAction* paste = KStandardAction::paste(this, &DolphinMainWindow::paste, actionCollection()); // The text of the paste-action is modified dynamically by Dolphin // (e. g. to "Paste One Folder"). To prevent that the size of the toolbar changes // due to the long text, the text "Paste" is used: paste->setIconText(i18nc("@action:inmenu Edit", "Paste")); QAction *searchAction = KStandardAction::find(this, &DolphinMainWindow::find, actionCollection()); searchAction->setText(i18n("Search...")); KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection()); QAction* invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection")); invertSelection->setText(i18nc("@action:inmenu Edit", "Invert Selection")); invertSelection->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-invert"))); actionCollection()->setDefaultShortcut(invertSelection, Qt::CTRL + Qt::SHIFT + Qt::Key_A); connect(invertSelection, &QAction::triggered, this, &DolphinMainWindow::invertSelection); // setup 'View' menu // (note that most of it is set up in DolphinViewActionHandler) QAction* split = actionCollection()->addAction(QStringLiteral("split_view")); actionCollection()->setDefaultShortcut(split, Qt::Key_F3); connect(split, &QAction::triggered, this, &DolphinMainWindow::toggleSplitView); QAction* stashSplit = actionCollection()->addAction(QStringLiteral("split_stash")); actionCollection()->setDefaultShortcut(stashSplit, Qt::CTRL + Qt::Key_S); stashSplit->setText(i18nc("@action:intoolbar Stash", "Stash")); stashSplit->setToolTip(i18nc("@info", "Opens the stash virtual directory in a split window")); stashSplit->setIcon(QIcon::fromTheme(QStringLiteral("folder-stash"))); stashSplit->setCheckable(false); stashSplit->setVisible(KProtocolInfo::isKnownProtocol("stash")); connect(stashSplit, &QAction::triggered, this, &DolphinMainWindow::toggleSplitStash); KStandardAction::redisplay(this, &DolphinMainWindow::reloadView, actionCollection()); QAction* stop = actionCollection()->addAction(QStringLiteral("stop")); stop->setText(i18nc("@action:inmenu View", "Stop")); stop->setToolTip(i18nc("@info", "Stop loading")); stop->setIcon(QIcon::fromTheme(QStringLiteral("process-stop"))); connect(stop, &QAction::triggered, this, &DolphinMainWindow::stopLoading); KToggleAction* editableLocation = actionCollection()->add(QStringLiteral("editable_location")); editableLocation->setText(i18nc("@action:inmenu Navigation Bar", "Editable Location")); actionCollection()->setDefaultShortcut(editableLocation, Qt::Key_F6); connect(editableLocation, &KToggleAction::triggered, this, &DolphinMainWindow::toggleEditLocation); QAction* replaceLocation = actionCollection()->addAction(QStringLiteral("replace_location")); replaceLocation->setText(i18nc("@action:inmenu Navigation Bar", "Replace Location")); actionCollection()->setDefaultShortcut(replaceLocation, Qt::CTRL + Qt::Key_L); connect(replaceLocation, &QAction::triggered, this, &DolphinMainWindow::replaceLocation); // setup 'Go' menu QAction* backAction = KStandardAction::back(this, &DolphinMainWindow::goBack, actionCollection()); auto backShortcuts = backAction->shortcuts(); backShortcuts.append(QKeySequence(Qt::Key_Backspace)); actionCollection()->setDefaultShortcuts(backAction, backShortcuts); DolphinRecentTabsMenu* recentTabsMenu = new DolphinRecentTabsMenu(this); actionCollection()->addAction(QStringLiteral("closed_tabs"), recentTabsMenu); connect(m_tabWidget, &DolphinTabWidget::rememberClosedTab, recentTabsMenu, &DolphinRecentTabsMenu::rememberClosedTab); connect(recentTabsMenu, &DolphinRecentTabsMenu::restoreClosedTab, m_tabWidget, &DolphinTabWidget::restoreClosedTab); connect(recentTabsMenu, &DolphinRecentTabsMenu::closedTabsCountChanged, this, &DolphinMainWindow::closedTabsCountChanged); QAction* undoCloseTab = actionCollection()->addAction(QStringLiteral("undo_close_tab")); undoCloseTab->setText(i18nc("@action:inmenu File", "Undo close tab")); actionCollection()->setDefaultShortcut(undoCloseTab, Qt::CTRL + Qt::SHIFT + Qt::Key_T); undoCloseTab->setIcon(QIcon::fromTheme(QStringLiteral("edit-undo"))); undoCloseTab->setEnabled(false); connect(undoCloseTab, &QAction::triggered, recentTabsMenu, &DolphinRecentTabsMenu::undoCloseTab); auto undoAction = actionCollection()->action(KStandardAction::name(KStandardAction::Undo)); undoAction->setEnabled(false); // undo should be disabled by default KStandardAction::forward(this, &DolphinMainWindow::goForward, actionCollection()); KStandardAction::up(this, &DolphinMainWindow::goUp, actionCollection()); KStandardAction::home(this, &DolphinMainWindow::goHome, actionCollection()); // setup 'Tools' menu QAction* showFilterBar = actionCollection()->addAction(QStringLiteral("show_filter_bar")); showFilterBar->setText(i18nc("@action:inmenu Tools", "Show Filter Bar")); showFilterBar->setIcon(QIcon::fromTheme(QStringLiteral("view-filter"))); actionCollection()->setDefaultShortcuts(showFilterBar, {Qt::CTRL + Qt::Key_I, Qt::Key_Slash}); connect(showFilterBar, &QAction::triggered, this, &DolphinMainWindow::showFilterBar); QAction* compareFiles = actionCollection()->addAction(QStringLiteral("compare_files")); compareFiles->setText(i18nc("@action:inmenu Tools", "Compare Files")); compareFiles->setIcon(QIcon::fromTheme(QStringLiteral("kompare"))); compareFiles->setEnabled(false); connect(compareFiles, &QAction::triggered, this, &DolphinMainWindow::compareFiles); #ifdef HAVE_TERMINAL if (KAuthorized::authorize(QStringLiteral("shell_access"))) { QAction* openTerminal = actionCollection()->addAction(QStringLiteral("open_terminal")); openTerminal->setText(i18nc("@action:inmenu Tools", "Open Terminal")); openTerminal->setIcon(QIcon::fromTheme(QStringLiteral("utilities-terminal"))); actionCollection()->setDefaultShortcut(openTerminal, Qt::SHIFT + Qt::Key_F4); connect(openTerminal, &QAction::triggered, this, &DolphinMainWindow::openTerminal); } #endif // setup 'Bookmarks' menu KActionMenu *bookmarkMenu = new KActionMenu(i18nc("@title:menu", "&Bookmarks"), this); m_bookmarkHandler = new DolphinBookmarkHandler(this, actionCollection(), bookmarkMenu->menu(), this); actionCollection()->addAction(QStringLiteral("bookmarks"), bookmarkMenu); // setup 'Settings' menu KToggleAction* showMenuBar = KStandardAction::showMenubar(nullptr, nullptr, actionCollection()); connect(showMenuBar, &KToggleAction::triggered, // Fixes #286822 this, &DolphinMainWindow::toggleShowMenuBar, Qt::QueuedConnection); KStandardAction::preferences(this, &DolphinMainWindow::editSettings, actionCollection()); // not in menu actions QList nextTabKeys = KStandardShortcut::tabNext(); nextTabKeys.append(QKeySequence(Qt::CTRL + Qt::Key_Tab)); QList prevTabKeys = KStandardShortcut::tabPrev(); prevTabKeys.append(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Tab)); QAction* activateNextTab = actionCollection()->addAction(QStringLiteral("activate_next_tab")); activateNextTab->setIconText(i18nc("@action:inmenu", "Next Tab")); activateNextTab->setText(i18nc("@action:inmenu", "Activate Next Tab")); activateNextTab->setEnabled(false); connect(activateNextTab, &QAction::triggered, m_tabWidget, &DolphinTabWidget::activateNextTab); actionCollection()->setDefaultShortcuts(activateNextTab, nextTabKeys); QAction* activatePrevTab = actionCollection()->addAction(QStringLiteral("activate_prev_tab")); activatePrevTab->setIconText(i18nc("@action:inmenu", "Previous Tab")); activatePrevTab->setText(i18nc("@action:inmenu", "Activate Previous Tab")); activatePrevTab->setEnabled(false); connect(activatePrevTab, &QAction::triggered, m_tabWidget, &DolphinTabWidget::activatePrevTab); actionCollection()->setDefaultShortcuts(activatePrevTab, prevTabKeys); // for context menu QAction* showTarget = actionCollection()->addAction(QStringLiteral("show_target")); showTarget->setText(i18nc("@action:inmenu", "Show Target")); showTarget->setIcon(QIcon::fromTheme(QStringLiteral("document-open-folder"))); showTarget->setEnabled(false); connect(showTarget, &QAction::triggered, this, &DolphinMainWindow::showTarget); QAction* openInNewTab = actionCollection()->addAction(QStringLiteral("open_in_new_tab")); openInNewTab->setText(i18nc("@action:inmenu", "Open in New Tab")); openInNewTab->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); connect(openInNewTab, &QAction::triggered, this, &DolphinMainWindow::openInNewTab); QAction* openInNewTabs = actionCollection()->addAction(QStringLiteral("open_in_new_tabs")); openInNewTabs->setText(i18nc("@action:inmenu", "Open in New Tabs")); openInNewTabs->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); connect(openInNewTabs, &QAction::triggered, this, &DolphinMainWindow::openInNewTab); QAction* openInNewWindow = actionCollection()->addAction(QStringLiteral("open_in_new_window")); openInNewWindow->setText(i18nc("@action:inmenu", "Open in New Window")); openInNewWindow->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); connect(openInNewWindow, &QAction::triggered, this, &DolphinMainWindow::openInNewWindow); } void DolphinMainWindow::setupDockWidgets() { const bool lock = GeneralSettings::lockPanels(); KDualAction* lockLayoutAction = actionCollection()->add(QStringLiteral("lock_panels")); lockLayoutAction->setActiveText(i18nc("@action:inmenu Panels", "Unlock Panels")); lockLayoutAction->setActiveIcon(QIcon::fromTheme(QStringLiteral("object-unlocked"))); lockLayoutAction->setInactiveText(i18nc("@action:inmenu Panels", "Lock Panels")); lockLayoutAction->setInactiveIcon(QIcon::fromTheme(QStringLiteral("object-locked"))); lockLayoutAction->setActive(lock); connect(lockLayoutAction, &KDualAction::triggered, this, &DolphinMainWindow::togglePanelLockState); // Setup "Information" DolphinDockWidget* infoDock = new DolphinDockWidget(i18nc("@title:window", "Information")); infoDock->setLocked(lock); infoDock->setObjectName(QStringLiteral("infoDock")); infoDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); #ifdef HAVE_BALOO InformationPanel* infoPanel = new InformationPanel(infoDock); infoPanel->setCustomContextMenuActions({lockLayoutAction}); connect(infoPanel, &InformationPanel::urlActivated, this, &DolphinMainWindow::handleUrl); infoDock->setWidget(infoPanel); QAction* infoAction = infoDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("dialog-information")), Qt::Key_F11, infoAction, QStringLiteral("show_information_panel")); addDockWidget(Qt::RightDockWidgetArea, infoDock); connect(this, &DolphinMainWindow::urlChanged, infoPanel, &InformationPanel::setUrl); connect(this, &DolphinMainWindow::selectionChanged, infoPanel, &InformationPanel::setSelection); connect(this, &DolphinMainWindow::requestItemInfo, infoPanel, &InformationPanel::requestDelayedItemInfo); #endif // Setup "Folders" DolphinDockWidget* foldersDock = new DolphinDockWidget(i18nc("@title:window", "Folders")); foldersDock->setLocked(lock); foldersDock->setObjectName(QStringLiteral("foldersDock")); foldersDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); FoldersPanel* foldersPanel = new FoldersPanel(foldersDock); foldersPanel->setCustomContextMenuActions({lockLayoutAction}); foldersDock->setWidget(foldersPanel); QAction* foldersAction = foldersDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("folder")), Qt::Key_F7, foldersAction, QStringLiteral("show_folders_panel")); addDockWidget(Qt::LeftDockWidgetArea, foldersDock); connect(this, &DolphinMainWindow::urlChanged, foldersPanel, &FoldersPanel::setUrl); connect(foldersPanel, &FoldersPanel::folderActivated, this, &DolphinMainWindow::changeUrl); connect(foldersPanel, &FoldersPanel::folderMiddleClicked, this, &DolphinMainWindow::openNewTabAfterCurrentTab); connect(foldersPanel, &FoldersPanel::errorMessage, this, &DolphinMainWindow::showErrorMessage); // Setup "Terminal" #ifdef HAVE_TERMINAL if (KAuthorized::authorize(QStringLiteral("shell_access"))) { DolphinDockWidget* terminalDock = new DolphinDockWidget(i18nc("@title:window Shell terminal", "Terminal")); terminalDock->setLocked(lock); terminalDock->setObjectName(QStringLiteral("terminalDock")); m_terminalPanel = new TerminalPanel(terminalDock); m_terminalPanel->setCustomContextMenuActions({lockLayoutAction}); terminalDock->setWidget(m_terminalPanel); connect(m_terminalPanel, &TerminalPanel::hideTerminalPanel, terminalDock, &DolphinDockWidget::hide); connect(m_terminalPanel, &TerminalPanel::changeUrl, this, &DolphinMainWindow::slotTerminalDirectoryChanged); connect(terminalDock, &DolphinDockWidget::visibilityChanged, m_terminalPanel, &TerminalPanel::dockVisibilityChanged); connect(terminalDock, &DolphinDockWidget::visibilityChanged, this, &DolphinMainWindow::slotTerminalPanelVisibilityChanged); QAction* terminalAction = terminalDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("utilities-terminal")), Qt::Key_F4, terminalAction, QStringLiteral("show_terminal_panel")); addDockWidget(Qt::BottomDockWidgetArea, terminalDock); connect(this, &DolphinMainWindow::urlChanged, m_terminalPanel, &TerminalPanel::setUrl); if (GeneralSettings::version() < 200) { terminalDock->hide(); } } #endif if (GeneralSettings::version() < 200) { infoDock->hide(); foldersDock->hide(); } // Setup "Places" DolphinDockWidget* placesDock = new DolphinDockWidget(i18nc("@title:window", "Places")); placesDock->setLocked(lock); placesDock->setObjectName(QStringLiteral("placesDock")); placesDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); m_placesPanel = new PlacesPanel(placesDock); m_placesPanel->setCustomContextMenuActions({lockLayoutAction}); placesDock->setWidget(m_placesPanel); QAction *placesAction = placesDock->toggleViewAction(); createPanelAction(QIcon::fromTheme(QStringLiteral("bookmarks")), Qt::Key_F9, placesAction, QStringLiteral("show_places_panel")); addDockWidget(Qt::LeftDockWidgetArea, placesDock); connect(m_placesPanel, &PlacesPanel::placeActivated, this, &DolphinMainWindow::slotPlaceActivated); connect(m_placesPanel, &PlacesPanel::placeMiddleClicked, this, &DolphinMainWindow::openNewTabAfterCurrentTab); connect(m_placesPanel, &PlacesPanel::errorMessage, this, &DolphinMainWindow::showErrorMessage); connect(this, &DolphinMainWindow::urlChanged, m_placesPanel, &PlacesPanel::setUrl); connect(placesDock, &DolphinDockWidget::visibilityChanged, m_tabWidget, &DolphinTabWidget::slotPlacesPanelVisibilityChanged); connect(this, &DolphinMainWindow::settingsChanged, m_placesPanel, &PlacesPanel::readSettings); connect(m_placesPanel, &PlacesPanel::storageTearDownRequested, this, &DolphinMainWindow::slotStorageTearDownFromPlacesRequested); connect(m_placesPanel, &PlacesPanel::storageTearDownExternallyRequested, this, &DolphinMainWindow::slotStorageTearDownExternallyRequested); m_tabWidget->slotPlacesPanelVisibilityChanged(m_placesPanel->isVisible()); auto actionShowAllPlaces = new QAction(QIcon::fromTheme(QStringLiteral("hint")), i18nc("@item:inmenu", "Show Hidden Places"), this); actionShowAllPlaces->setCheckable(true); actionShowAllPlaces->setDisabled(true); connect(actionShowAllPlaces, &QAction::triggered, this, [actionShowAllPlaces, this](bool checked){ actionShowAllPlaces->setIcon(QIcon::fromTheme(checked ? QStringLiteral("visibility") : QStringLiteral("hint"))); m_placesPanel->showHiddenEntries(checked); }); connect(m_placesPanel, &PlacesPanel::showHiddenEntriesChanged, this, [actionShowAllPlaces] (bool checked){ actionShowAllPlaces->setChecked(checked); actionShowAllPlaces->setIcon(QIcon::fromTheme(checked ? QStringLiteral("visibility") : QStringLiteral("hint"))); }); // Add actions into the "Panels" menu KActionMenu* panelsMenu = new KActionMenu(i18nc("@action:inmenu View", "Panels"), this); actionCollection()->addAction(QStringLiteral("panels"), panelsMenu); panelsMenu->setDelayed(false); const KActionCollection* ac = actionCollection(); panelsMenu->addAction(ac->action(QStringLiteral("show_places_panel"))); #ifdef HAVE_BALOO panelsMenu->addAction(ac->action(QStringLiteral("show_information_panel"))); #endif panelsMenu->addAction(ac->action(QStringLiteral("show_folders_panel"))); panelsMenu->addAction(ac->action(QStringLiteral("show_terminal_panel"))); panelsMenu->addSeparator(); panelsMenu->addAction(actionShowAllPlaces); panelsMenu->addAction(lockLayoutAction); connect(panelsMenu->menu(), &QMenu::aboutToShow, this, [actionShowAllPlaces, this]{ actionShowAllPlaces->setEnabled(m_placesPanel->hiddenListCount()); }); } void DolphinMainWindow::updateEditActions() { const KFileItemList list = m_activeViewContainer->view()->selectedItems(); if (list.isEmpty()) { stateChanged(QStringLiteral("has_no_selection")); } else { stateChanged(QStringLiteral("has_selection")); KActionCollection* col = actionCollection(); QAction* renameAction = col->action(KStandardAction::name(KStandardAction::RenameFile)); QAction* moveToTrashAction = col->action(KStandardAction::name(KStandardAction::MoveToTrash)); QAction* deleteAction = col->action(KStandardAction::name(KStandardAction::DeleteFile)); QAction* cutAction = col->action(KStandardAction::name(KStandardAction::Cut)); QAction* deleteWithTrashShortcut = col->action(QStringLiteral("delete_shortcut")); // see DolphinViewActionHandler QAction* showTarget = col->action(QStringLiteral("show_target")); KFileItemListProperties capabilities(list); const bool enableMoveToTrash = capabilities.isLocal() && capabilities.supportsMoving(); renameAction->setEnabled(capabilities.supportsMoving()); moveToTrashAction->setEnabled(enableMoveToTrash); deleteAction->setEnabled(capabilities.supportsDeleting()); deleteWithTrashShortcut->setEnabled(capabilities.supportsDeleting() && !enableMoveToTrash); cutAction->setEnabled(capabilities.supportsMoving()); showTarget->setEnabled(list.length() == 1 && list.at(0).isLink()); } } void DolphinMainWindow::updateViewActions() { m_actionHandler->updateViewActions(); QAction* showFilterBarAction = actionCollection()->action(QStringLiteral("show_filter_bar")); showFilterBarAction->setChecked(m_activeViewContainer->isFilterBarVisible()); updateSplitAction(); QAction* editableLocactionAction = actionCollection()->action(QStringLiteral("editable_location")); const KUrlNavigator* urlNavigator = m_activeViewContainer->urlNavigator(); editableLocactionAction->setChecked(urlNavigator->isUrlEditable()); } void DolphinMainWindow::updateGoActions() { QAction* goUpAction = actionCollection()->action(KStandardAction::name(KStandardAction::Up)); const QUrl currentUrl = m_activeViewContainer->url(); goUpAction->setEnabled(KIO::upUrl(currentUrl) != currentUrl); } void DolphinMainWindow::createControlButton() { if (m_controlButton) { return; } Q_ASSERT(!m_controlButton); m_controlButton = new QToolButton(this); m_controlButton->setIcon(QIcon::fromTheme(QStringLiteral("application-menu"))); m_controlButton->setText(i18nc("@action", "Control")); m_controlButton->setPopupMode(QToolButton::InstantPopup); m_controlButton->setToolButtonStyle(toolBar()->toolButtonStyle()); QMenu* controlMenu = new QMenu(m_controlButton); connect(controlMenu, &QMenu::aboutToShow, this, &DolphinMainWindow::updateControlMenu); m_controlButton->setMenu(controlMenu); toolBar()->addWidget(m_controlButton); connect(toolBar(), &KToolBar::iconSizeChanged, m_controlButton, &QToolButton::setIconSize); connect(toolBar(), &KToolBar::toolButtonStyleChanged, m_controlButton, &QToolButton::setToolButtonStyle); // The added widgets are owned by the toolbar and may get deleted when e.g. the toolbar // gets edited. In this case we must add them again. The adding is done asynchronously by // m_updateToolBarTimer. connect(m_controlButton, &QToolButton::destroyed, this, &DolphinMainWindow::slotControlButtonDeleted); m_updateToolBarTimer = new QTimer(this); m_updateToolBarTimer->setInterval(500); connect(m_updateToolBarTimer, &QTimer::timeout, this, &DolphinMainWindow::updateToolBar); } void DolphinMainWindow::deleteControlButton() { delete m_controlButton; m_controlButton = nullptr; delete m_updateToolBarTimer; m_updateToolBarTimer = nullptr; } bool DolphinMainWindow::addActionToMenu(QAction* action, QMenu* menu) { Q_ASSERT(action); Q_ASSERT(menu); const KToolBar* toolBarWidget = toolBar(); foreach (const QWidget* widget, action->associatedWidgets()) { if (widget == toolBarWidget) { return false; } } menu->addAction(action); return true; } void DolphinMainWindow::refreshViews() { m_tabWidget->refreshViews(); if (GeneralSettings::modifiedStartupSettings()) { // The startup settings have been changed by the user (see bug #254947). // Synchronize the split-view setting with the active view: const bool splitView = GeneralSettings::splitView(); m_tabWidget->currentTabPage()->setSplitViewEnabled(splitView); updateSplitAction(); updateWindowTitle(); } emit settingsChanged(); } void DolphinMainWindow::clearStatusBar() { m_activeViewContainer->statusBar()->resetToDefaultText(); } void DolphinMainWindow::connectViewSignals(DolphinViewContainer* container) { connect(container, &DolphinViewContainer::showFilterBarChanged, this, &DolphinMainWindow::updateFilterBarAction); connect(container, &DolphinViewContainer::writeStateChanged, this, &DolphinMainWindow::slotWriteStateChanged); const DolphinView* view = container->view(); connect(view, &DolphinView::selectionChanged, this, &DolphinMainWindow::slotSelectionChanged); connect(view, &DolphinView::requestItemInfo, this, &DolphinMainWindow::requestItemInfo); connect(view, &DolphinView::tabRequested, this, &DolphinMainWindow::openNewTab); connect(view, &DolphinView::requestContextMenu, this, &DolphinMainWindow::openContextMenu); connect(view, &DolphinView::directoryLoadingStarted, this, &DolphinMainWindow::enableStopAction); connect(view, &DolphinView::directoryLoadingCompleted, this, &DolphinMainWindow::disableStopAction); connect(view, &DolphinView::directoryLoadingCompleted, this, &DolphinMainWindow::slotDirectoryLoadingCompleted); connect(view, &DolphinView::goBackRequested, this, &DolphinMainWindow::goBack); connect(view, &DolphinView::goForwardRequested, this, &DolphinMainWindow::goForward); connect(view, &DolphinView::urlActivated, this, &DolphinMainWindow::handleUrl); const KUrlNavigator* navigator = container->urlNavigator(); connect(navigator, &KUrlNavigator::urlChanged, this, &DolphinMainWindow::changeUrl); connect(navigator, &KUrlNavigator::historyChanged, this, &DolphinMainWindow::updateHistory); connect(navigator, &KUrlNavigator::editableStateChanged, this, &DolphinMainWindow::slotEditableStateChanged); connect(navigator, &KUrlNavigator::tabRequested, this, &DolphinMainWindow::openNewTabAfterLastTab); } void DolphinMainWindow::updateSplitAction() { QAction* splitAction = actionCollection()->action(QStringLiteral("split_view")); const DolphinTabPage* tabPage = m_tabWidget->currentTabPage(); if (tabPage->splitViewEnabled()) { if (GeneralSettings::closeActiveSplitView() ? tabPage->primaryViewActive() : !tabPage->primaryViewActive()) { splitAction->setText(i18nc("@action:intoolbar Close left view", "Close")); splitAction->setToolTip(i18nc("@info", "Close left view")); splitAction->setIcon(QIcon::fromTheme(QStringLiteral("view-left-close"))); } else { splitAction->setText(i18nc("@action:intoolbar Close right view", "Close")); splitAction->setToolTip(i18nc("@info", "Close right view")); splitAction->setIcon(QIcon::fromTheme(QStringLiteral("view-right-close"))); } } else { splitAction->setText(i18nc("@action:intoolbar Split view", "Split")); splitAction->setToolTip(i18nc("@info", "Split view")); splitAction->setIcon(QIcon::fromTheme(QStringLiteral("view-right-new"))); } } bool DolphinMainWindow::isKompareInstalled() const { static bool initialized = false; static bool installed = false; if (!initialized) { // TODO: maybe replace this approach later by using a menu // plugin like kdiff3plugin.cpp installed = !QStandardPaths::findExecutable(QStringLiteral("kompare")).isEmpty(); initialized = true; } return installed; } void DolphinMainWindow::createPanelAction(const QIcon& icon, const QKeySequence& shortcut, QAction* dockAction, const QString& actionName) { QAction* panelAction = actionCollection()->addAction(actionName); panelAction->setCheckable(true); panelAction->setChecked(dockAction->isChecked()); panelAction->setText(dockAction->text()); panelAction->setIcon(icon); actionCollection()->setDefaultShortcut(panelAction, shortcut); connect(panelAction, &QAction::triggered, dockAction, &QAction::trigger); connect(dockAction, &QAction::toggled, panelAction, &QAction::setChecked); } DolphinMainWindow::UndoUiInterface::UndoUiInterface() : KIO::FileUndoManager::UiInterface() { } DolphinMainWindow::UndoUiInterface::~UndoUiInterface() { } void DolphinMainWindow::UndoUiInterface::jobError(KIO::Job* job) { DolphinMainWindow* mainWin= qobject_cast(parentWidget()); if (mainWin) { DolphinViewContainer* container = mainWin->activeViewContainer(); container->showMessage(job->errorString(), DolphinViewContainer::Error); } else { KIO::FileUndoManager::UiInterface::jobError(job); } } +bool DolphinMainWindow::isUrlOpen(const QString& url) +{ + if (m_tabWidget->getIndexByUrl(QUrl::fromUserInput((url))) >= 0) { + return true; + } else { + return false; + } +} + diff --git a/src/dolphinmainwindow.h b/src/dolphinmainwindow.h index 1e2460768..4037c1468 100644 --- a/src/dolphinmainwindow.h +++ b/src/dolphinmainwindow.h @@ -1,556 +1,589 @@ /*************************************************************************** * Copyright (C) 2006 by Peter Penz * * Copyright (C) 2006 by Stefan Monov * * Copyright (C) 2006 by Cvetoslav Ludmiloff * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ #ifndef DOLPHIN_MAINWINDOW_H #define DOLPHIN_MAINWINDOW_H #include "dolphintabwidget.h" #include #include #include #include #include #include #include #include #include typedef KIO::FileUndoManager::CommandType CommandType; class DolphinBookmarkHandler; class DolphinViewActionHandler; class DolphinSettingsDialog; class DolphinViewContainer; class DolphinRemoteEncoding; class DolphinTabWidget; class KFileItem; class KFileItemList; class KJob; class KNewFileMenu; class QToolButton; class QIcon; class PlacesPanel; class TerminalPanel; /** * @short Main window for Dolphin. * * Handles the menus, toolbars and Dolphin views. */ class DolphinMainWindow: public KXmlGuiWindow { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.dolphin.MainWindow") public: DolphinMainWindow(); ~DolphinMainWindow() override; /** * Returns the currently active view. * All menu actions are applied to this view. When * having a split view setup, the nonactive view * is usually shown in darker colors. */ DolphinViewContainer* activeViewContainer() const; /** * Returns view container for all tabs */ QVector viewContainers() const; /** * Opens each directory in \p dirs in a separate tab. If \a splitView is set, * 2 directories are collected within one tab. * \pre \a dirs must contain at least one url. */ void openDirectories(const QList &dirs, bool splitView); /** * Opens the directories which contain the files \p files and selects all files. * If \a splitView is set, 2 directories are collected within one tab. * \pre \a files must contain at least one url. */ void openFiles(const QList& files, bool splitView); /** * Returns the 'Create New...' sub menu which also can be shared * with other menus (e. g. a context menu). */ KNewFileMenu* newFileMenu() const; void setTabsToHomeIfMountPathOpen(const QString& mountPath); public slots: + /** + * Opens each directory in \p dirs in a separate tab. If \a splitView is set, + * 2 directories are collected within one tab. + * \pre \a dirs must contain at least one url. + * + * @note this function is overloaded so that it is callable via DBus. + */ + void openDirectories(const QStringList &dirs, bool splitView); + + /** + * Opens the directories which contain the files \p files and selects all files. + * If \a splitView is set, 2 directories are collected within one tab. + * \pre \a files must contain at least one url. + * + * @note this is overloaded so that this function is callable via DBus. + */ + void openFiles(const QStringList &files, bool splitView); + + /** + * Tries to raise/activate the Dolphin window. + */ + void activateWindow(); + + /** + * Determines if a URL is open in any tab. + * @note Use of QString instead of QUrl is required to be callable via DBus. + * + * @param url URL to look for + * @returns true if url is currently open in a tab, false otherwise. + */ + bool isUrlOpen(const QString &url); + + /** * Pastes the clipboard data into the currently selected folder * of the active view. If not exactly one folder is selected, * no pasting is done at all. */ void pasteIntoFolder(); /** * Implementation of the MainWindowAdaptor/QDBusAbstractAdaptor interface. * Inform all affected dolphin components (panels, views) of an URL * change. */ void changeUrl(const QUrl& url); /** * The current directory of the Terminal Panel has changed, probably because * the user entered a 'cd' command. This slot calls changeUrl(url) and makes * sure that the panel keeps the keyboard focus. */ void slotTerminalDirectoryChanged(const QUrl& url); /** Stores all settings and quits Dolphin. */ void quit(); /** * Opens a new tab and places it after the current tab */ void openNewTabAfterCurrentTab(const QUrl& url); /** * Opens a new tab and places it as the last tab */ void openNewTabAfterLastTab(const QUrl& url); signals: /** * Is sent if the selection of the currently active view has * been changed. */ void selectionChanged(const KFileItemList& selection); /** * Is sent if the url of the currently active view has * been changed. */ void urlChanged(const QUrl& url); /** * Is emitted if information of an item is requested to be shown e. g. in the panel. * If item is null, no item information request is pending. */ void requestItemInfo(const KFileItem& item); /** * Is emitted if the settings have been changed. */ void settingsChanged(); protected: /** @see QWidget::showEvent() */ void showEvent(QShowEvent* event) override; /** @see QMainWindow::closeEvent() */ void closeEvent(QCloseEvent* event) override; /** @see KMainWindow::saveProperties() */ void saveProperties(KConfigGroup& group) override; /** @see KMainWindow::readProperties() */ void readProperties(const KConfigGroup& group) override; private slots: /** * Refreshes the views of the main window by recreating them according to * the given Dolphin settings. */ void refreshViews(); void clearStatusBar(); /** Updates the 'Create New...' sub menu. */ void updateNewMenu(); void createDirectory(); /** Shows the error message in the status bar of the active view. */ void showErrorMessage(const QString& message); /** * Updates the state of the 'Undo' menu action dependent * on the parameter \a available. */ void slotUndoAvailable(bool available); /** Sets the text of the 'Undo' menu action to \a text. */ void slotUndoTextChanged(const QString& text); /** Performs the current undo operation. */ void undo(); /** * Copies all selected items to the clipboard and marks * the items as cut. */ void cut(); /** Copies all selected items to the clipboard. */ void copy(); /** Pastes the clipboard data to the active view. */ void paste(); /** Replaces the URL navigator by a search box to find files. */ void find(); /** * Updates the text of the paste action dependent on * the number of items which are in the clipboard. */ void updatePasteAction(); /** Selects all items from the active view. */ void selectAll(); /** * Inverts the selection of all items of the active view: * Selected items get nonselected and nonselected items get * selected. */ void invertSelection(); /** * Switches between one and two views: * If one view is visible, it will get split into two views. * If already two views are visible, the active view gets closed. */ void toggleSplitView(); /** Dedicated action to open the stash:/ ioslave in split view. */ void toggleSplitStash(); /** Reloads the currently active view. */ void reloadView(); /** Stops the loading process for the currently active view. */ void stopLoading(); void enableStopAction(); void disableStopAction(); void showFilterBar(); /** * Toggles between edit and browse mode of the navigation bar. */ void toggleEditLocation(); /** * Switches to the edit mode of the navigation bar and selects * the whole URL, so that it can be replaced by the user. If the edit mode is * already active, it is assured that the navigation bar get focused. */ void replaceLocation(); /** * Toggles the state of the panels between a locked and unlocked layout. */ void togglePanelLockState(); /** * Is invoked if the Terminal panel got visible/invisible and takes care * that the active view has the focus if the Terminal panel is invisible. */ void slotTerminalPanelVisibilityChanged(); /** Goes back one step of the URL history. */ void goBack(); /** Goes forward one step of the URL history. */ void goForward(); /** Goes up one hierarchy of the current URL. */ void goUp(); /** Changes the location to the home URL. */ void goHome(); /** Open the previous URL in the URL history in a new tab. */ void goBackInNewTab(); /** Open the next URL in the URL history in a new tab. */ void goForwardInNewTab(); /** Open the URL one hierarchy above the current URL in a new tab. */ void goUpInNewTab(); /** * Open the home URL in a new tab. */ void goHomeInNewTab(); /** Opens Kompare for 2 selected files. */ void compareFiles(); /** * Hides the menu bar if it is visible, makes the menu bar * visible if it is hidden. */ void toggleShowMenuBar(); /** Opens a terminal window for the current location. */ void openTerminal(); /** Opens the settings dialog for Dolphin. */ void editSettings(); /** Updates the state of the 'Show Full Location' action. */ void slotEditableStateChanged(bool editable); /** * Updates the state of the 'Edit' menu actions and emits * the signal selectionChanged(). */ void slotSelectionChanged(const KFileItemList& selection); /** * Updates the state of the 'Back' and 'Forward' menu * actions corresponding to the current history. */ void updateHistory(); /** Updates the state of the 'Show filter bar' menu action. */ void updateFilterBarAction(bool show); /** Open a new main window. */ void openNewMainWindow(); /** * Opens a new view with the current URL that is part of a tab and * activates it. */ void openNewActivatedTab(); /** * Opens a new tab in the background showing the URL \a url. */ void openNewTab(const QUrl& url, DolphinTabWidget::TabPlacement tabPlacement); /** * Opens the selected folder in a new tab. */ void openInNewTab(); /** * Opens the selected folder in a new window. */ void openInNewWindow(); /** * Show the target of the selected symlink */ void showTarget(); /** * Indicates in the statusbar that the execution of the command \a command * has been finished. */ void showCommand(CommandType command); /** * If the URL can be listed, open it in the current view, otherwise * run it through KRun. */ void handleUrl(const QUrl& url); /** * handleUrl() can trigger a stat job to see if the url can actually * be listed. */ void slotHandleUrlStatFinished(KJob* job); /** * Is invoked when the write state of a folder has been changed and * enables/disables the "Create New..." menu entry. */ void slotWriteStateChanged(bool isFolderWritable); /** * Opens the context menu on the current mouse position. * @pos Position in screen coordinates. * @item File item context. If item is null, the context menu * should be applied to \a url. * @url URL which contains \a item. * @customActions Actions that should be added to the context menu, * if the file item is null. */ void openContextMenu(const QPoint& pos, const KFileItem& item, const QUrl& url, const QList& customActions); void updateControlMenu(); void updateToolBar(); void slotControlButtonDeleted(); /** * Is called if the user clicked an item in the Places Panel. * Reloads the view if \a url is the current URL already, and changes the * current URL otherwise. */ void slotPlaceActivated(const QUrl& url); /** * Is called if the another view has been activated by changing the current * tab or activating another view in split-view mode. * * Activates the given view, which means that all menu actions are applied * to this view. When having a split view setup, the nonactive view is * usually shown in darker colors. */ void activeViewChanged(DolphinViewContainer* viewContainer); void closedTabsCountChanged(unsigned int count); /** * Is called if a new tab has been opened or a tab has been closed to * enable/disable the tab actions. */ void tabCountChanged(int count); /** * Updates the Window Title with the caption from the active view container */ void updateWindowTitle(); /** * This slot is called when the user requested to unmount a removable media * from the places menu */ void slotStorageTearDownFromPlacesRequested(const QString& mountPath); /** * This slot is called when the user requested to unmount a removable media * _not_ from the dolphin's places menu (from the notification area for e.g.) * This slot is basically connected to each removable device's * Solid::StorageAccess::teardownRequested(const QString & udi) * signal through the places panel. */ void slotStorageTearDownExternallyRequested(const QString& mountPath); /** * Is called when the view has finished loading the directory. */ void slotDirectoryLoadingCompleted(); /** * Is called when the user middle clicks a toolbar button. * * Here middle clicking Back/Forward/Up/Home will open the resulting * folder in a new tab. */ void slotToolBarActionMiddleClicked(QAction *action); private: void setupActions(); void setupDockWidgets(); void updateEditActions(); void updateViewActions(); void updateGoActions(); void createControlButton(); void deleteControlButton(); /** * Adds the action \p action to the menu \p menu in * case if it has not added already to the toolbar. * @return True if the action has been added to the menu. */ bool addActionToMenu(QAction* action, QMenu* menu); /** * Connects the signals from the created DolphinView with * the DolphinViewContainer \a container with the corresponding slots of * the DolphinMainWindow. This method must be invoked each * time a DolphinView has been created. */ void connectViewSignals(DolphinViewContainer* container); /** * Updates the text of the split action: * If two views are shown, the text is set to "Split", * otherwise the text is set to "Join". The icon * is updated to match with the text and the currently active view. */ void updateSplitAction(); bool isKompareInstalled() const; /** * Creates an action for showing/hiding a panel, that is accessible * in "Configure toolbars..." and "Configure shortcuts...". This is necessary * as the action for toggling the dock visibility is done by Qt which * is no KAction instance. */ void createPanelAction(const QIcon &icon, const QKeySequence& shortcut, QAction* dockAction, const QString& actionName); private: /** * Implements a custom error handling for the undo manager. This * assures that all errors are shown in the status bar of Dolphin * instead as modal error dialog with an OK button. */ class UndoUiInterface : public KIO::FileUndoManager::UiInterface { public: UndoUiInterface(); ~UndoUiInterface() override; void jobError(KIO::Job* job) override; }; KNewFileMenu* m_newFileMenu; DolphinTabWidget* m_tabWidget; DolphinViewContainer* m_activeViewContainer; DolphinViewActionHandler* m_actionHandler; DolphinRemoteEncoding* m_remoteEncoding; QPointer m_settingsDialog; DolphinBookmarkHandler* m_bookmarkHandler; // Members for the toolbar menu that is shown when the menubar is hidden: QToolButton* m_controlButton; QTimer* m_updateToolBarTimer; KIO::Job* m_lastHandleUrlStatJob; TerminalPanel* m_terminalPanel; PlacesPanel* m_placesPanel; bool m_tearDownFromPlacesRequested; }; inline DolphinViewContainer* DolphinMainWindow::activeViewContainer() const { return m_activeViewContainer; } inline KNewFileMenu* DolphinMainWindow::newFileMenu() const { return m_newFileMenu; } #endif // DOLPHIN_MAINWINDOW_H diff --git a/src/dolphintabwidget.cpp b/src/dolphintabwidget.cpp index e54ab5ada..defd089c1 100644 --- a/src/dolphintabwidget.cpp +++ b/src/dolphintabwidget.cpp @@ -1,376 +1,396 @@ /*************************************************************************** * Copyright (C) 2014 by Emmanuel Pescosta * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ #include "dolphintabwidget.h" #include "dolphin_generalsettings.h" #include "dolphintabbar.h" #include "dolphintabpage.h" #include "dolphinviewcontainer.h" #include #include #include #include #include #include DolphinTabWidget::DolphinTabWidget(QWidget* parent) : QTabWidget(parent), m_placesSelectorVisible(true), m_lastViewedTab(0) { connect(this, &DolphinTabWidget::tabCloseRequested, this, QOverload::of(&DolphinTabWidget::closeTab)); connect(this, &DolphinTabWidget::currentChanged, this, &DolphinTabWidget::currentTabChanged); DolphinTabBar* tabBar = new DolphinTabBar(this); connect(tabBar, &DolphinTabBar::openNewActivatedTab, this, QOverload::of(&DolphinTabWidget::openNewActivatedTab)); connect(tabBar, &DolphinTabBar::tabDropEvent, this, &DolphinTabWidget::tabDropEvent); connect(tabBar, &DolphinTabBar::tabDetachRequested, this, &DolphinTabWidget::detachTab); tabBar->hide(); setTabBar(tabBar); setDocumentMode(true); setElideMode(Qt::ElideRight); setUsesScrollButtons(true); } DolphinTabPage* DolphinTabWidget::currentTabPage() const { return tabPageAt(currentIndex()); } DolphinTabPage* DolphinTabWidget::nextTabPage() const { const int index = currentIndex() + 1; return tabPageAt(index < count() ? index : 0); } DolphinTabPage* DolphinTabWidget::prevTabPage() const { const int index = currentIndex() - 1; return tabPageAt(index >= 0 ? index : (count() - 1)); } DolphinTabPage* DolphinTabWidget::tabPageAt(const int index) const { return static_cast(widget(index)); } void DolphinTabWidget::saveProperties(KConfigGroup& group) const { const int tabCount = count(); group.writeEntry("Tab Count", tabCount); group.writeEntry("Active Tab Index", currentIndex()); for (int i = 0; i < tabCount; ++i) { const DolphinTabPage* tabPage = tabPageAt(i); group.writeEntry("Tab Data " % QString::number(i), tabPage->saveState()); } } void DolphinTabWidget::readProperties(const KConfigGroup& group) { const int tabCount = group.readEntry("Tab Count", 0); for (int i = 0; i < tabCount; ++i) { if (i >= count()) { openNewActivatedTab(); } if (group.hasKey("Tab Data " % QString::number(i))) { // Tab state created with Dolphin > 4.14.x const QByteArray state = group.readEntry("Tab Data " % QString::number(i), QByteArray()); tabPageAt(i)->restoreState(state); } else { // Tab state created with Dolphin <= 4.14.x const QByteArray state = group.readEntry("Tab " % QString::number(i), QByteArray()); tabPageAt(i)->restoreStateV1(state); } } const int index = group.readEntry("Active Tab Index", 0); setCurrentIndex(index); } void DolphinTabWidget::refreshViews() { // Left-elision is better when showing full paths, since you care most // about the current directory which is on the right if (GeneralSettings::showFullPathInTitlebar()) { setElideMode(Qt::ElideLeft); } else { setElideMode(Qt::ElideRight); } const int tabCount = count(); for (int i = 0; i < tabCount; ++i) { tabBar()->setTabText(i, tabName(tabPageAt(i))); tabPageAt(i)->refreshViews(); } } void DolphinTabWidget::openNewActivatedTab() { const DolphinViewContainer* oldActiveViewContainer = currentTabPage()->activeViewContainer(); Q_ASSERT(oldActiveViewContainer); const bool isUrlEditable = oldActiveViewContainer->urlNavigator()->isUrlEditable(); openNewActivatedTab(oldActiveViewContainer->url()); DolphinViewContainer* newActiveViewContainer = currentTabPage()->activeViewContainer(); Q_ASSERT(newActiveViewContainer); // The URL navigator of the new tab should have the same editable state // as the current tab newActiveViewContainer->urlNavigator()->setUrlEditable(isUrlEditable); // Always focus the new tab's view newActiveViewContainer->view()->setFocus(); } void DolphinTabWidget::openNewActivatedTab(const QUrl& primaryUrl, const QUrl& secondaryUrl) { openNewTab(primaryUrl, secondaryUrl); setCurrentIndex(count() - 1); } void DolphinTabWidget::openNewTab(const QUrl& primaryUrl, const QUrl& secondaryUrl, TabPlacement tabPlacement) { QWidget* focusWidget = QApplication::focusWidget(); DolphinTabPage* tabPage = new DolphinTabPage(primaryUrl, secondaryUrl, this); tabPage->setPlacesSelectorVisible(m_placesSelectorVisible); connect(tabPage, &DolphinTabPage::activeViewChanged, this, &DolphinTabWidget::activeViewChanged); connect(tabPage, &DolphinTabPage::activeViewUrlChanged, this, &DolphinTabWidget::tabUrlChanged); int newTabIndex = -1; if (tabPlacement == AfterCurrentTab) { newTabIndex = currentIndex() + 1; } insertTab(newTabIndex, tabPage, QIcon::fromTheme(KIO::iconNameForUrl(primaryUrl)), tabName(tabPage)); if (focusWidget) { // The DolphinViewContainer grabbed the keyboard focus. As the tab is opened // in background, assure that the previous focused widget gets the focus back. focusWidget->setFocus(); } } void DolphinTabWidget::openDirectories(const QList& dirs, bool splitView) { Q_ASSERT(dirs.size() > 0); QList::const_iterator it = dirs.constBegin(); while (it != dirs.constEnd()) { const QUrl& primaryUrl = *(it++); + const int index = getIndexByUrl(primaryUrl); + if (index >= 0) { + setCurrentIndex(index); + continue; + } if (splitView && (it != dirs.constEnd())) { const QUrl& secondaryUrl = *(it++); - openNewTab(primaryUrl, secondaryUrl); + openNewActivatedTab(primaryUrl, secondaryUrl); } else { - openNewTab(primaryUrl); + openNewActivatedTab(primaryUrl); } } } void DolphinTabWidget::openFiles(const QList& files, bool splitView) { Q_ASSERT(files.size() > 0); // Get all distinct directories from 'files' and open a tab // for each directory. If the "split view" option is enabled, two // directories are shown inside one tab (see openDirectories()). QList dirs; foreach (const QUrl& url, files) { const QUrl dir(url.adjusted(QUrl::RemoveFilename)); if (!dirs.contains(dir)) { dirs.append(dir); } } const int oldTabCount = count(); openDirectories(dirs, splitView); const int tabCount = count(); // Select the files. Although the files can be split between several // tabs, there is no need to split 'files' accordingly, as // the DolphinView will just ignore invalid selections. for (int i = oldTabCount; i < tabCount; ++i) { DolphinTabPage* tabPage = tabPageAt(i); tabPage->markUrlsAsSelected(files); tabPage->markUrlAsCurrent(files.first()); } } void DolphinTabWidget::closeTab() { closeTab(currentIndex()); } void DolphinTabWidget::closeTab(const int index) { Q_ASSERT(index >= 0); Q_ASSERT(index < count()); if (count() < 2) { // Close Dolphin when closing the last tab. parentWidget()->close(); return; } DolphinTabPage* tabPage = tabPageAt(index); emit rememberClosedTab(tabPage->activeViewContainer()->url(), tabPage->saveState()); removeTab(index); tabPage->deleteLater(); } void DolphinTabWidget::activateNextTab() { const int index = currentIndex() + 1; setCurrentIndex(index < count() ? index : 0); } void DolphinTabWidget::activatePrevTab() { const int index = currentIndex() - 1; setCurrentIndex(index >= 0 ? index : (count() - 1)); } void DolphinTabWidget::slotPlacesPanelVisibilityChanged(bool visible) { // The places-selector from the URL navigator should only be shown // if the places dock is invisible m_placesSelectorVisible = !visible; const int tabCount = count(); for (int i = 0; i < tabCount; ++i) { DolphinTabPage* tabPage = tabPageAt(i); tabPage->setPlacesSelectorVisible(m_placesSelectorVisible); } } void DolphinTabWidget::restoreClosedTab(const QByteArray& state) { openNewActivatedTab(); currentTabPage()->restoreState(state); } void DolphinTabWidget::detachTab(int index) { Q_ASSERT(index >= 0); QStringList args; const DolphinTabPage* tabPage = tabPageAt(index); args << tabPage->primaryViewContainer()->url().url(); if (tabPage->splitViewEnabled()) { args << tabPage->secondaryViewContainer()->url().url(); args << QStringLiteral("--split"); } + args << QStringLiteral("--new-window"); const QString command = QStringLiteral("dolphin %1").arg(KShell::joinArgs(args)); KRun::runCommand(command, this); closeTab(index); } void DolphinTabWidget::openNewActivatedTab(int index) { Q_ASSERT(index >= 0); const DolphinTabPage* tabPage = tabPageAt(index); openNewActivatedTab(tabPage->activeViewContainer()->url()); } void DolphinTabWidget::tabDropEvent(int index, QDropEvent* event) { if (index >= 0) { DolphinView* view = tabPageAt(index)->activeViewContainer()->view(); view->dropUrls(view->url(), event, view); } } void DolphinTabWidget::tabUrlChanged(const QUrl& url) { const int index = indexOf(qobject_cast(sender())); if (index >= 0) { tabBar()->setTabText(index, tabName(tabPageAt(index))); tabBar()->setTabIcon(index, QIcon::fromTheme(KIO::iconNameForUrl(url))); // Emit the currentUrlChanged signal if the url of the current tab has been changed. if (index == currentIndex()) { emit currentUrlChanged(url); } } } void DolphinTabWidget::currentTabChanged(int index) { // last-viewed tab deactivation if (DolphinTabPage* tabPage = tabPageAt(m_lastViewedTab)) { tabPage->setActive(false); } DolphinTabPage* tabPage = tabPageAt(index); DolphinViewContainer* viewContainer = tabPage->activeViewContainer(); emit activeViewChanged(viewContainer); emit currentUrlChanged(viewContainer->url()); tabPage->setActive(true); m_lastViewedTab = index; } void DolphinTabWidget::tabInserted(int index) { QTabWidget::tabInserted(index); if (count() > 1) { tabBar()->show(); } emit tabCountChanged(count()); } void DolphinTabWidget::tabRemoved(int index) { QTabWidget::tabRemoved(index); // If only one tab is left, then remove the tab entry so that // closing the last tab is not possible. if (count() < 2) { tabBar()->hide(); } emit tabCountChanged(count()); } QString DolphinTabWidget::tabName(DolphinTabPage* tabPage) const { if (!tabPage) { return QString(); } QString name = tabPage->activeViewContainer()->caption(); // Make sure that a '&' inside the directory name is displayed correctly // and not misinterpreted as a keyboard shortcut in QTabBar::setTabText() return name.replace('&', QLatin1String("&&")); } + +int DolphinTabWidget::getIndexByUrl(const QUrl& url) const +{ + for (int i = 0; i < count(); i++) { + // Conversion to display string is necessary to deal with the '~' alias. + // i.e. to acknowledge that ~/ is equivalent to /home/user/ + const QUrl tabUrl = tabPageAt(i)->activeViewContainer()->url(); + if (url == tabUrl || + url.toDisplayString(QUrl::StripTrailingSlash) == tabUrl.toDisplayString(QUrl::StripTrailingSlash)) { + return i; + } + } + return -1; +} diff --git a/src/dolphintabwidget.h b/src/dolphintabwidget.h index 7e3b30c0d..3e8301725 100644 --- a/src/dolphintabwidget.h +++ b/src/dolphintabwidget.h @@ -1,221 +1,227 @@ /*************************************************************************** * Copyright (C) 2014 by Emmanuel Pescosta * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ #ifndef DOLPHIN_TAB_WIDGET_H #define DOLPHIN_TAB_WIDGET_H #include #include class DolphinViewContainer; class DolphinTabPage; class KConfigGroup; class DolphinTabWidget : public QTabWidget { Q_OBJECT public: /** * @brief Controls where tabs are placed */ enum TabPlacement { /** * The new tab is placed after the current tab */ AfterCurrentTab, /** * The new tab is placed after the last tab */ AfterLastTab }; explicit DolphinTabWidget(QWidget* parent); /** * @return Tab page at the current index (can be 0 if tabs count is smaller than 1) */ DolphinTabPage* currentTabPage() const; /** * @return the next tab page. If the current active tab is the last tab, * it returns the first tab. If there is only one tab, returns nullptr */ DolphinTabPage* nextTabPage() const; /** * @return the previous tab page. If the current active tab is the first tab, * it returns the last tab. If there is only one tab, returns nullptr */ DolphinTabPage* prevTabPage() const; /** * @return Tab page at the given \a index (can be 0 if the index is out-of-range) */ DolphinTabPage* tabPageAt(const int index) const; void saveProperties(KConfigGroup& group) const; void readProperties(const KConfigGroup& group); /** * Refreshes the views of the main window by recreating them according to * the given Dolphin settings. */ void refreshViews(); + /** + * @param url The URL that we would like + * @return index of the tab with the desired URL. returns -1 if not found + */ + int getIndexByUrl(const QUrl& url) const; + signals: /** * Is emitted when the active view has been changed, by changing the current * tab or by activating another view when split view is enabled in the current * tab. */ void activeViewChanged(DolphinViewContainer* viewContainer); /** * Is emitted when the number of open tabs has changed (e.g. by opening or * closing a tab) */ void tabCountChanged(int count); /** * Is emitted when a tab has been closed. */ void rememberClosedTab(const QUrl& url, const QByteArray& state); /** * Is emitted when the url of the current tab has been changed. This signal * is also emitted when the active view has been changed. */ void currentUrlChanged(const QUrl& url); public slots: /** * Opens a new view with the current URL that is part of a tab and activates * the tab. */ void openNewActivatedTab(); /** * Opens a new tab showing the URL \a primaryUrl and the optional URL * \a secondaryUrl and activates the tab. */ void openNewActivatedTab(const QUrl& primaryUrl, const QUrl& secondaryUrl = QUrl()); /** * Opens a new tab in the background showing the URL \a primaryUrl and the * optional URL \a secondaryUrl. \a tabPlacement controls where the new tab * is placed. */ void openNewTab(const QUrl &primaryUrl, const QUrl &secondaryUrl = QUrl(), DolphinTabWidget::TabPlacement tabPlacement = AfterLastTab); /** * Opens each directory in \p dirs in a separate tab. If \a splitView is set, * 2 directories are collected within one tab. * \pre \a dirs must contain at least one url. */ void openDirectories(const QList& dirs, bool splitView); /** * Opens the directories which contain the files \p files and selects all files. * If \a splitView is set, 2 directories are collected within one tab. * \pre \a files must contain at least one url. */ void openFiles(const QList &files, bool splitView); /** * Closes the currently active tab. */ void closeTab(); /** * Closes the tab with the index \a index and activates the tab with index - 1. */ void closeTab(const int index); /** * Activates the next tab in the tab bar. * If the current active tab is the last tab, it activates the first tab. */ void activateNextTab(); /** * Activates the previous tab in the tab bar. * If the current active tab is the first tab, it activates the last tab. */ void activatePrevTab(); /** * Is invoked if the Places panel got visible/invisible and takes care * that the places-selector of all views is only shown if the Places panel * is invisible. */ void slotPlacesPanelVisibilityChanged(bool visible); /** * Is called when the user wants to reopen a previously closed tab from * the recent tabs menu. */ void restoreClosedTab(const QByteArray& state); private slots: /** * Opens the tab with the index \a index in a new Dolphin instance and closes * this tab. */ void detachTab(int index); /** * Opens a new tab showing the url from tab at the given \a index and * activates the tab. */ void openNewActivatedTab(int index); /** * Is connected to the KTabBar signal receivedDropEvent. * Allows dragging and dropping files onto tabs. */ void tabDropEvent(int tab, QDropEvent* event); /** * The active view url of a tab has been changed so update the text and the * icon of the corresponding tab. */ void tabUrlChanged(const QUrl& url); void currentTabChanged(int index); protected: void tabInserted(int index) override; void tabRemoved(int index) override; private: /** * @param tabPage The tab page to get the name of * @return The name of the tab page */ QString tabName(DolphinTabPage* tabPage) const; private: /** Caches the (negated) places panel visibility */ bool m_placesSelectorVisible; int m_lastViewedTab; }; #endif diff --git a/src/global.cpp b/src/global.cpp index aaeb58120..e7ff67d77 100644 --- a/src/global.cpp +++ b/src/global.cpp @@ -1,63 +1,143 @@ /* * Copyright 2015 Ashish Bansal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "global.h" #include "dolphin_generalsettings.h" #include "dolphindebug.h" #include +#include #include #include +#include +#include QList Dolphin::validateUris(const QStringList& uriList) { const QString currentDir = QDir::currentPath(); QList urls; foreach (const QString& str, uriList) { const QUrl url = QUrl::fromUserInput(str, currentDir, QUrl::AssumeLocalFile); if (url.isValid()) { urls.append(url); } else { qCWarning(DolphinDebug) << "Invalid URL: " << str; } } return urls; } QUrl Dolphin::homeUrl() { return QUrl::fromUserInput(GeneralSettings::homeUrl(), QString(), QUrl::AssumeLocalFile); } void Dolphin::openNewWindow(const QList &urls, QWidget *window, const OpenNewWindowFlags &flags) { - QString command = QStringLiteral("dolphin"); + QString command = QStringLiteral("dolphin --new-window"); if (flags.testFlag(OpenNewWindowFlag::Select)) { command.append(QLatin1String(" --select")); } if (!urls.isEmpty()) { command.append(QLatin1String(" %U")); } + KRun::run( + command, + urls, + window, + QApplication::applicationDisplayName(), + QApplication::windowIcon().name() + ); +} + +bool Dolphin::attachToExistingInstance(const QList& urls, bool openFiles, bool splitView, const QString& preferredService) +{ + if (KWindowSystem::isPlatformWayland()) { + // TODO: once Wayland clients can raise or activate themselves remove this conditional + return false; + } + + const QStringList services = QDBusConnection::sessionBus().interface()->registeredServiceNames().value(); + + // Don't match the service without trailing "-" (unique instance) + const QString pattern = QStringLiteral("org.kde.dolphin-"); + const QString myPid = QString::number(QCoreApplication::applicationPid()); + QVector, QStringList>> dolphinServices; + if (!preferredService.isEmpty()) { + QSharedPointer preferred( + new QDBusInterface(preferredService, + QStringLiteral("/dolphin/Dolphin_1"), + QStringLiteral("org.kde.dolphin.MainWindow")) + ); + if (preferred->isValid()) { + dolphinServices.append(qMakePair(preferred, QStringList() )); + } + } + + // find all dolphin instances + for (const QString& service : services) { + if (service.startsWith(pattern) && !service.endsWith(myPid)) { + // Check if instance can handle our URLs + QSharedPointer instance( + new QDBusInterface(service, + QStringLiteral("/dolphin/Dolphin_1"), + QStringLiteral("org.kde.dolphin.MainWindow")) + ); + if (!instance->isValid()) { + continue; + } + dolphinServices.append(qMakePair(instance, QStringList())); + } + } + + if (dolphinServices.isEmpty()) { + return false; + } + + QStringList newUrls; + + // check to see if any instances already have any of the given URLs open + for (const QString& url : QUrl::toStringList(urls)) { + bool urlFound = false; + for (auto& service: dolphinServices) { + QDBusReply isUrlOpen = service.first->call(QStringLiteral("isUrlOpen"), url); + if (isUrlOpen.isValid() && isUrlOpen.value()) { + service.second.append(url); + urlFound = true; + break; + } + } + if (!urlFound) { + newUrls.append(url); + } + } + dolphinServices.front().second << newUrls; - KRun::run(command, urls, window, qApp->applicationDisplayName(), qApp->windowIcon().name()); + for (const auto& service: dolphinServices) { + if (!service.second.isEmpty()) { + service.first->call(openFiles ? QStringLiteral("openFiles") : QStringLiteral("openDirectories"), service.second, splitView); + service.first->call(QStringLiteral("activateWindow")); + } + } + return true; } diff --git a/src/global.h b/src/global.h index e3c4a1cca..16305eafe 100644 --- a/src/global.h +++ b/src/global.h @@ -1,51 +1,57 @@ /* * Copyright 2015 Ashish Bansal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GLOBAL_H #define GLOBAL_H #include #include namespace Dolphin { QList validateUris(const QStringList& uriList); /** * Returns the home url which is defined in General Settings */ QUrl homeUrl(); enum class OpenNewWindowFlag { None = 0, Select = 1<<1 }; Q_DECLARE_FLAGS(OpenNewWindowFlags, OpenNewWindowFlag) /** * Opens a new Dolphin window */ void openNewWindow(const QList &urls = {}, QWidget *window = nullptr, const OpenNewWindowFlags &flags = OpenNewWindowFlag::None); + /** + * Attaches URLs to an existing Dolphin instance if possible. + * Returns true if URLs were successfully attached + */ + bool attachToExistingInstance(const QList& urls, bool openFiles, bool splitView, const QString& preferredService = QString()); + /** * TODO: Move this somewhere global to all KDE apps, not just Dolphin */ const int VERTICAL_SPACER_HEIGHT = 18; } #endif //GLOBAL_H diff --git a/src/main.cpp b/src/main.cpp index 08405d007..639dc32ef 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,169 +1,182 @@ /*************************************************************************** * Copyright (C) 2006 by Peter Penz * * Copyright (C) 2006 by Stefan Monov * * Copyright (C) 2015 by Mathieu Tarral * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ #include "dbusinterface.h" #include "dolphin_generalsettings.h" #include "dolphin_version.h" #include "dolphindebug.h" #include "dolphinmainwindow.h" #include "global.h" #include #include #include #include #include #include #include +#include +#include +#include +#include #ifndef Q_OS_WIN #include #endif #include extern "C" Q_DECL_EXPORT int kdemain(int argc, char **argv) { #ifndef Q_OS_WIN // Prohibit using sudo or kdesu (but allow using the root user directly) if (getuid() == 0) { if (!qEnvironmentVariableIsEmpty("SUDO_USER")) { std::cout << "Executing Dolphin with sudo is not possible due to unfixable security vulnerabilities." << std::endl; return EXIT_FAILURE; } else if (!qEnvironmentVariableIsEmpty("KDESU_USER")) { std::cout << "Executing Dolphin with kdesu is not possible due to unfixable security vulnerabilities." << std::endl; return EXIT_FAILURE; } } #endif QApplication app(argc, argv); app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); app.setWindowIcon(QIcon::fromTheme(QStringLiteral("system-file-manager"), app.windowIcon())); KCrash::initialize(); Kdelibs4ConfigMigrator migrate(QStringLiteral("dolphin")); migrate.setConfigFiles(QStringList() << QStringLiteral("dolphinrc")); migrate.setUiFiles(QStringList() << QStringLiteral("dolphinpart.rc") << QStringLiteral("dolphinui.rc")); migrate.migrate(); KLocalizedString::setApplicationDomain("dolphin"); KAboutData aboutData(QStringLiteral("dolphin"), i18n("Dolphin"), QStringLiteral(DOLPHIN_VERSION_STRING), i18nc("@title", "File Manager"), KAboutLicense::GPL, i18nc("@info:credit", "(C) 2006-2018 Peter Penz, Frank Reininghaus, Emmanuel Pescosta and Elvis Angelaccio")); aboutData.setHomepage(QStringLiteral("https://dolphin.kde.org")); aboutData.addAuthor(i18nc("@info:credit", "Elvis Angelaccio"), i18nc("@info:credit", "Maintainer (since 2018) and developer"), QStringLiteral("elvis.angelaccio@kde.org")); aboutData.addAuthor(i18nc("@info:credit", "Emmanuel Pescosta"), i18nc("@info:credit", "Maintainer (2014-2018) and developer"), QStringLiteral("emmanuelpescosta099@gmail.com")); aboutData.addAuthor(i18nc("@info:credit", "Frank Reininghaus"), i18nc("@info:credit", "Maintainer (2012-2014) and developer"), QStringLiteral("frank78ac@googlemail.com")); aboutData.addAuthor(i18nc("@info:credit", "Peter Penz"), i18nc("@info:credit", "Maintainer and developer (2006-2012)"), QStringLiteral("peter.penz19@gmail.com")); aboutData.addAuthor(i18nc("@info:credit", "Sebastian Trüg"), i18nc("@info:credit", "Developer"), QStringLiteral("trueg@kde.org")); aboutData.addAuthor(i18nc("@info:credit", "David Faure"), i18nc("@info:credit", "Developer"), QStringLiteral("faure@kde.org")); aboutData.addAuthor(i18nc("@info:credit", "Aaron J. Seigo"), i18nc("@info:credit", "Developer"), QStringLiteral("aseigo@kde.org")); aboutData.addAuthor(i18nc("@info:credit", "Rafael Fernández López"), i18nc("@info:credit", "Developer"), QStringLiteral("ereslibre@kde.org")); aboutData.addAuthor(i18nc("@info:credit", "Kevin Ottens"), i18nc("@info:credit", "Developer"), QStringLiteral("ervin@kde.org")); aboutData.addAuthor(i18nc("@info:credit", "Holger Freyther"), i18nc("@info:credit", "Developer"), QStringLiteral("freyther@gmx.net")); aboutData.addAuthor(i18nc("@info:credit", "Max Blazejak"), i18nc("@info:credit", "Developer"), QStringLiteral("m43ksrocks@gmail.com")); aboutData.addAuthor(i18nc("@info:credit", "Michael Austin"), i18nc("@info:credit", "Documentation"), QStringLiteral("tuxedup@users.sourceforge.net")); KAboutData::setApplicationData(aboutData); KDBusService dolphinDBusService; DBusInterface interface; QCommandLineParser parser; aboutData.setupCommandLine(&parser); // command line options parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("select"), i18nc("@info:shell", "The files and folders passed as arguments " "will be selected."))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("split"), i18nc("@info:shell", "Dolphin will get started with a split view."))); + parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("new-window"), i18nc("@info:shell", "Dolphin will explicitly open in a new window."))); parser.addOption(QCommandLineOption(QStringList() << QStringLiteral("daemon"), i18nc("@info:shell", "Start Dolphin Daemon (only required for DBus Interface)"))); parser.addPositionalArgument(QStringLiteral("+[Url]"), i18nc("@info:shell", "Document to open")); parser.process(app); aboutData.processCommandLine(&parser); + const bool splitView = parser.isSet(QStringLiteral("split")) || GeneralSettings::splitView(); + const bool openFiles = parser.isSet(QStringLiteral("select")); + const QStringList args = parser.positionalArguments(); + QList urls = Dolphin::validateUris(args); + if (parser.isSet(QStringLiteral("daemon"))) { return app.exec(); } - const QStringList args = parser.positionalArguments(); - QList urls = Dolphin::validateUris(args); - if (urls.isEmpty()) { // We need at least one URL to open Dolphin urls.append(Dolphin::homeUrl()); } - const bool splitView = parser.isSet(QStringLiteral("split")) || GeneralSettings::splitView(); if (splitView && urls.size() < 2) { // Split view does only make sense if we have at least 2 URLs urls.append(urls.last()); } + if (!parser.isSet(QStringLiteral("new-window"))) { + if (Dolphin::attachToExistingInstance(urls, openFiles, splitView)) { + // Successfully attached to existing instance of Dolphin + return 0; + } + } + DolphinMainWindow* mainWindow = new DolphinMainWindow(); - if (parser.isSet(QStringLiteral("select"))) { + if (openFiles) { mainWindow->openFiles(urls, splitView); } else { mainWindow->openDirectories(urls, splitView); } mainWindow->show(); if (app.isSessionRestored()) { const QString className = KXmlGuiWindow::classNameOfToplevel(1); if (className == QLatin1String("DolphinMainWindow")) { mainWindow->restore(1); } else { qCWarning(DolphinDebug) << "Unknown class " << className << " in session saved data!"; } } return app.exec(); // krazy:exclude=crash; }