diff --git a/src/dolphinmainwindow.cpp b/src/dolphinmainwindow.cpp index c839e2d5c..ae139d363 100644 --- a/src/dolphinmainwindow.cpp +++ b/src/dolphinmainwindow.cpp @@ -1,1739 +1,2096 @@ /*************************************************************************** * 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 #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), + KXmlGuiWindow(nullptr, Qt::WindowContextHelpButtonHint), m_newFileMenu(nullptr), + m_helpMenu(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); + + setupWhatsThis(); } 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->setWhatsThis(i18nc("@info:whatsthis go back", "Return to the previously viewed folder.")); backAction->setEnabled(index < urlNavigator->historySize() - 1); } QAction* forwardAction = actionCollection()->action(KStandardAction::name(KStandardAction::Forward)); if (forwardAction) { forwardAction->setToolTip(i18nc("@info", "Go forward")); + forwardAction->setWhatsThis(xi18nc("@info:whatsthis go forward", + "This undoes a Go|Back action.")); 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->addMenu(m_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->setWhatsThis(xi18nc("@info:whatsthis", "This opens a new " + "window just like this one with the current location and view." + "You can drag and drop items between windows.")); 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")); + newTab->setWhatsThis(xi18nc("@info:whatsthis", "This opens a new " + "Tab with the current location and view." + "A tab is an additional view within this window. " + "You can drag and drop items between tabs.")); 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")); + closeTab->setWhatsThis(i18nc("@info:whatsthis", "This closes the " + "currently viewed tab. If no more tabs are left this window " + "will close instead.")); - KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection()); + QAction* quitAction = KStandardAction::quit(this, &DolphinMainWindow::quit, actionCollection()); + quitAction->setWhatsThis(i18nc("@info:whatsthis quit", "This closes this window.")); // setup 'Edit' menu KStandardAction::undo(this, &DolphinMainWindow::undo, actionCollection()); - - KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection()); - KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection()); + // i18n: This will be the last paragraph for the whatsthis for all three: + // Cut, Copy and Paste + const QString cutCopyPastePara = xi18nc("@info:whatsthis", "Cut, " + "Copy and Paste work between many " + "applications and are among the most used commands. That's why their " + "keyboard shortcuts are prominently placed right " + "next to each other on the keyboard: Ctrl+X, " + "Ctrl+C and Ctrl+V."); + QAction* cutAction = KStandardAction::cut(this, &DolphinMainWindow::cut, actionCollection()); + cutAction->setWhatsThis(xi18nc("@info:whatsthis cut", "This copies the items " + "in your current selection to the clipboard." + "Use the Paste action afterwards to copy them from " + "the clipboard to a new location. The items will be removed from their " + "initial location.") + cutCopyPastePara); + QAction* copyAction = KStandardAction::copy(this, &DolphinMainWindow::copy, actionCollection()); + copyAction->setWhatsThis(xi18nc("@info:whatsthis copy", "This copies the " + "items in your current selection to the clipboard." + "Use the Paste action afterwards to copy them " + "from the clipboard to a new location.") + cutCopyPastePara); 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")); + paste->setWhatsThis(xi18nc("@info:whatsthis paste", "This copies the items from " + "your clipboard to the currently viewed folder." + "If the items were added to the clipboard by the Cut " + "action they are removed from their old location.") + cutCopyPastePara); QAction *searchAction = KStandardAction::find(this, &DolphinMainWindow::find, actionCollection()); searchAction->setText(i18n("Search...")); - - KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection()); + searchAction->setToolTip(i18nc("@info:tooltip", "Search for files and folders")); + searchAction->setWhatsThis(xi18nc("@info:whatsthis find", "This helps you " + "find files and folders by opening a find bar. " + "There you can enter search terms and specify settings to find the " + "objects you are looking for.Use this help again on " + "the find bar so we can have a look at it while the settings are " + "explained.")); + + QAction* selectAllAction = KStandardAction::selectAll(this, &DolphinMainWindow::selectAll, actionCollection()); + selectAllAction->setWhatsThis(xi18nc("@info:whatsthis", "This selects all " + "files and folders in the current location.")); QAction* invertSelection = actionCollection()->addAction(QStringLiteral("invert_selection")); invertSelection->setText(i18nc("@action:inmenu Edit", "Invert Selection")); + invertSelection->setWhatsThis(xi18nc("@info:whatsthis invert", "This selects all " + "objects that you have currently not selected instead.")); 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")); + split->setWhatsThis(xi18nc("@info:whatsthis find", "This splits " + "the folder view below into two autonomous views.This " + "way you can see two locations at once and move items between them " + "quickly.Click this again afterwards to recombine the views.")); 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->setWhatsThis(i18nc("@info", "This stops the loading of the contents of the current folder.")); 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")); + editableLocation->setWhatsThis(xi18nc("@info:whatsthis", + "This toggles the Location Bar to be " + "editable so you can directly enter a location you want to go to." + "You can also switch to editing by clicking to the right of the " + "location and switch back by confirming the edited 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")); + // i18n: "enter" is used both in the meaning of "writing" and "going to" a new location here. + // Both meanings are useful but not necessary to understand the use of "Replace Location". + // So you might want to be more verbose in your language to convey the meaning but it's up to you. + replaceLocation->setWhatsThis(xi18nc("@info:whatsthis", + "This switches to editing the location and selects it " + "so you can quickly enter a different 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")); + undoCloseTab->setWhatsThis(i18nc("@info:whatsthis undo close tab", + "This returns you to the previously closed 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->setWhatsThis(xi18nc("@info:whatsthis", "This undoes " + "the last change you made to files or folders." + "Such changes include creating, renaming " + "and moving them to a different location " + "or to the Trash. Changes that can't " + "be undone will ask for your confirmation.")); 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()); + QAction* homeAction = KStandardAction::home(this, &DolphinMainWindow::goHome, actionCollection()); + homeAction->setWhatsThis(xi18nc("@info:whatsthis", "Go to your " + "Home folder.Every user account " + "has their own Home that contains their data " + "including folders that contain personal application data.")); // setup 'Tools' menu QAction* showFilterBar = actionCollection()->addAction(QStringLiteral("show_filter_bar")); showFilterBar->setText(i18nc("@action:inmenu Tools", "Show Filter Bar")); + showFilterBar->setWhatsThis(xi18nc("@info:whatsthis", "This opens the " + "Filter Bar at the bottom of the window. " + "There you can enter a text to filter the files and folders currently displayed. " + "Only those that contain the text in their name will be kept in view.")); 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->setWhatsThis(xi18nc("@info:whatsthis", + "This opens a terminal application for the viewed location." + "To learn more about terminals use the help in the terminal application.")); 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); bookmarkMenu->setIcon(QIcon::fromTheme(QStringLiteral("bookmarks"))); // Make the toolbar button version work properly on click bookmarkMenu->setDelayed(false); m_bookmarkHandler = new DolphinBookmarkHandler(this, actionCollection(), bookmarkMenu->menu(), this); actionCollection()->addAction(QStringLiteral("bookmarks"), bookmarkMenu); // setup 'Settings' menu KToggleAction* showMenuBar = KStandardAction::showMenubar(nullptr, nullptr, actionCollection()); + showMenuBar->setWhatsThis(xi18nc("@info:whatsthis", + "This switches between having a Menubar " + "and having a Control button. Both " + "contain mostly the same commands and configuration options.")); connect(showMenuBar, &KToggleAction::triggered, // Fixes #286822 this, &DolphinMainWindow::toggleShowMenuBar, Qt::QueuedConnection); KStandardAction::preferences(this, &DolphinMainWindow::editSettings, actionCollection()); + // setup 'Help' menu for the m_controlButton. The other one is set up in the base class. + m_helpMenu = new KHelpMenu(nullptr); + m_helpMenu->menu()->installEventFilter(this); + // remove duplicate shortcuts + m_helpMenu->action(KHelpMenu::menuHelpContents)->setShortcut(QKeySequence()); + m_helpMenu->action(KHelpMenu::menuWhatsThis)->setShortcut(QKeySequence()); + // 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->setWhatsThis(xi18nc("@info:whatsthis", "This " + "switches between having panels locked or " + "unlocked.Unlocked panels can be " + "dragged to the other side of the window and have a close " + "button.Locked panels are embedded more cleanly.")); 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 + // i18n: This is the last paragraph for the "What's This"-texts of all four panels. + const QString panelWhatsThis = xi18nc("@info:whatsthis", "To show or " + "hide panels like this go to Control|Panels " + "or View|Panels."); + actionCollection()->action(QStringLiteral("show_information_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", " This toggles the " + "information panel at the right side of the " + "window.The panel provides in-depth information " + "about the items your mouse is hovering over or about the selected " + "items. Otherwise it informs you about the currently viewed folder." + "For single items a preview of their contents is provided.")); + infoDock->setWhatsThis(xi18nc("@info:whatsthis", "This panel " + "provides in-depth information about the items your mouse is " + "hovering over or about the selected items. Otherwise it informs " + "you about the currently viewed folder.For single items a " + "preview of their contents is provided.You can configure " + "which and how details are given here by right-clicking.") + panelWhatsThis); + // 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); + actionCollection()->action(QStringLiteral("show_folders_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the " + "folders panel at the left side of the window." + "It shows the folders of the file system" + " in a tree view.")); + foldersDock->setWhatsThis(xi18nc("@info:whatsthis", "This panel " + "shows the folders of the file system in a " + "tree view.Click a folder to go " + "there. Click the arrow to the left of a folder to see its subfolders. " + "This allows quick switching between any folders.") + panelWhatsThis); + // 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(); } + + actionCollection()->action(QStringLiteral("show_terminal_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the " + "terminal panel at the bottom of the window." + "The location in the terminal will always match the folder " + "view so you can navigate using either.The terminal " + "panel is not needed for basic computer usage but can be useful " + "for advanced tasks. To learn more about terminals use the help " + "in a standalone terminal application like Konsole.")); + terminalDock->setWhatsThis(xi18nc("@info:whatsthis", "This is " + "the terminal panel. It behaves like a " + "normal terminal but will match the location of the folder view " + "so you can navigate using either.The terminal panel " + "is not needed for basic computer usage but can be useful for " + "advanced tasks. To learn more about terminals use the help in a " + "standalone terminal application like Konsole.") + panelWhatsThis); } #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); + actionShowAllPlaces->setWhatsThis(i18nc("@info:whatsthis", "This displays " + "all places in the places panel that have been hidden. They will " + "appear semi-transparent unless you uncheck their hide property.")); 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"))); }); + actionCollection()->action(QStringLiteral("show_places_panel")) + ->setWhatsThis(xi18nc("@info:whatsthis", "This toggles the " + "places panel at the left side of the window." + "It allows you to go to locations you have " + "bookmarked and to access disk or media attached to the computer " + "or to the network. It also contains sections to find recently " + "saved files or files of a certain type.")); + placesDock->setWhatsThis(xi18nc("@info:whatsthis", "This is the " + "Places panel. It allows you to go to locations " + "you have bookmarked and to access disk or media attached to the " + "computer or to the network. It also contains sections to find " + "recently saved files or files of a certain type." + "Click on an entry to go there. Click with the right mouse button " + "instead to open any entry in a new tab or new window." + "New entries can be added by dragging folders onto this panel. " + "Right-click any section or entry to hide it. Right-click an empty " + "space on this panel and select Show Hidden Places" + " to display it again.") + panelWhatsThis); + // 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(); + // I think this is one of the best places to firstly be confronted + // with a file system and its hierarchy. Talking about the root + // directory might seem too much here but it is the question that + // naturally arises in this context. + goUpAction->setWhatsThis(xi18nc("@info:whatsthis", "Go to " + "the folder that contains the currenty viewed one." + "All files and folders are organized in a hierarchical " + "file system. At the top of this hierarchy is " + "a directory that contains all data connected to this computer" + "—the root directory.")); 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->setAttribute(Qt::WidgetAttribute::WA_CustomWhatsThis); m_controlButton->setPopupMode(QToolButton::InstantPopup); m_controlButton->setToolButtonStyle(toolBar()->toolButtonStyle()); QMenu* controlMenu = new QMenu(m_controlButton); connect(controlMenu, &QMenu::aboutToShow, this, &DolphinMainWindow::updateControlMenu); + controlMenu->installEventFilter(this); 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); } +void DolphinMainWindow::setupWhatsThis() +{ + // main widgets + menuBar()->setWhatsThis(xi18nc("@info:whatsthis", "This is the " + "Menubar. It provides access to commands and " + "configuration options. Left-click on any of the menus on this " + "bar to see its contents.The Menubar can be hidden " + "by unchecking Settings|Show Menubar. Then " + "most of its contents become available through a Control" + " button on the Toolbar.")); + toolBar()->setWhatsThis(xi18nc("@info:whatsthis", "This is the " + "Toolbar. It allows quick access to " + "frequently used actions.It is highly customizable. " + "All items you see in the Control menu or " + "in the Menubar can be placed on the " + "Toolbar. Just right-click on it and select Configure " + "Toolbars… or find this action in the " + "Control or Settings menu." + "The location of the bar and the style of its " + "buttons can also be changed in the right-click menu. Right-click " + "a button if you want to show or hide its text.")); + m_tabWidget->setWhatsThis(xi18nc("@info:whatsthis main view", + "Here you can see the folders and " + "files that are at the location described in " + "the Location Bar above. This area is the " + "central part of this application where you navigate to the files " + "you want to use.For an elaborate and general " + "introduction to this application " + "click here. This will open an introductory article from " + "the KDE UserBase Wiki.For brief " + "explanations of all the features of this view " + "click here " + "instead. This will open a page from the Handbook" + " that covers the basics.")); + + // Settings menu + actionCollection()->action(KStandardAction::name(KStandardAction::KeyBindings)) + ->setWhatsThis(xi18nc("@info:whatsthis","This opens a window " + "that lists the keyboard shortcuts." + "There you can set up key combinations to trigger an action when " + "they are pressed simultaneously. All commands in this application can " + "be triggered this way.")); + actionCollection()->action(KStandardAction::name(KStandardAction::ConfigureToolbars)) + ->setWhatsThis(xi18nc("@info:whatsthis","This opens a window in which " + "you can change which buttons appear on the Toolbar." + "All items you see in the Control menu " + "or in the Menubar can also be placed on the Toolbar.")); + actionCollection()->action(KStandardAction::name(KStandardAction::Preferences)) + ->setWhatsThis(xi18nc("@info:whatsthis","This opens a window where you can " + "change a multitude of settings for this application. For an explanation " + "of the various settings go to the chapter Configuring Dolphin" + " in Help|Dolphin Handbook.")); + + // Help menu + // The whatsthis has to be set for the m_helpMenu and for the + // StandardAction separately because both are used in different locations. + // m_helpMenu is only used for createControlButton() button. + + // Links do not work within the Menubar so texts without links are provided there. + + // i18n: If the external link isn't available in your language you should + // probably state the external link language at least in brackets to not + // frustrate the user. If there are multiple languages that the user might + // know with a reasonable chance you might want to have 2 external links. + // The same is in my opinion true for every external link you translate. + const QString whatsThisHelpContents = xi18nc("@info:whatsthis handbook", + "This opens the Handbook for this application. It provides " + "explanations for every part of Dolphin."); + actionCollection()->action(KStandardAction::name(KStandardAction::HelpContents)) + ->setWhatsThis(whatsThisHelpContents + + xi18nc("@info:whatsthis second half of handbook hb text without link", + "If you want more elaborate introductions to the " + "different features of Dolphin " + "go to the KDE UserBase Wiki.")); + m_helpMenu->action(KHelpMenu::menuHelpContents)->setWhatsThis(whatsThisHelpContents + + xi18nc("@info:whatsthis second half of handbook text with link", + "If you want more elaborate introductions to the " + "different features of Dolphin " + "click here. " + "It will open the dedicated page in the KDE UserBase Wiki.")); + + const QString whatsThisWhatsThis = xi18nc("@info:whatsthis whatsthis button", + "This is the button that invokes the help feature you are " + "using right now! Click it, then click any component of this " + "application to ask \"What's this?\" about it. The mouse cursor " + "will change appearance if no help is available for a spot."); + actionCollection()->action(KStandardAction::name(KStandardAction::WhatsThis)) + ->setWhatsThis(whatsThisWhatsThis + + xi18nc("@info:whatsthis second half of whatsthis button text without link", + "There are two other ways to get help for this application: The " + "Dolphin Handbook in the Help" + " menu and the KDE UserBase Wiki " + "article about File Management online." + "The \"What's this?\" help is " + "missing in most other windows so don't get too used to this.")); + m_helpMenu->action(KHelpMenu::menuWhatsThis)->setWhatsThis(whatsThisWhatsThis + + xi18nc("@info:whatsthis second half of whatsthis button text with link", + "There are two other ways to get help: " + "The Dolphin Handbook and " + "the KDE " + "UserBase Wiki.The \"What's this?\" help is " + "missing in most other windows so don't get too used to this.")); + + const QString whatsThisReportBug = xi18nc("@info:whatsthis","This opens a " + "window that will guide you through reporting errors or flaws " + "in this application or in other KDE software."); + actionCollection()->action(KStandardAction::name(KStandardAction::ReportBug)) + ->setWhatsThis(whatsThisReportBug); + m_helpMenu->action(KHelpMenu::menuReportBug)->setWhatsThis(whatsThisReportBug + + xi18nc("@info:whatsthis second half of reportbug text with link", + "High-quality bug reports are much appreciated. To learn " + "how to make your bug report as effective as possible " + "" + "click here.")); + + const QString whatsThisDonate = xi18nc("@info:whatsthis","This opens a " + "web page where you can donate to " + "support the continued work on this application and many " + "other projects by the KDE community." + "Donating is the easiest and fastest way to efficiently " + "support KDE and its projects. KDE projects are available for " + "free therefore your donation is needed to cover things that " + "require money like servers, contributor meetings, etc." + "KDE e.V. is the non-profit " + "organization behind the KDE community."); + actionCollection()->action(KStandardAction::name(KStandardAction::Donate)) + ->setWhatsThis(whatsThisDonate); + m_helpMenu->action(KHelpMenu::menuDonate)->setWhatsThis(whatsThisDonate); + + const QString whatsThisSwitchLanguage = xi18nc("@info:whatsthis", + "With this you can change the language this application uses." + "You can even set secondary languages which will be used " + "if texts are not available in your preferred language."); + actionCollection()->action(KStandardAction::name(KStandardAction::SwitchApplicationLanguage)) + ->setWhatsThis(whatsThisSwitchLanguage); + m_helpMenu->action(KHelpMenu::menuSwitchLanguage)->setWhatsThis(whatsThisSwitchLanguage); + + const QString whatsThisAboutApp = xi18nc("@info:whatsthis","This opens a " + "window that informs you about the version, license, " + "used libraries and maintainers of this application."); + actionCollection()->action(KStandardAction::name(KStandardAction::AboutApp)) + ->setWhatsThis(whatsThisAboutApp); + m_helpMenu->action(KHelpMenu::menuAboutApp)->setWhatsThis(whatsThisAboutApp); + + const QString whatsThisAboutKDE = xi18nc("@info:whatsthis","This opens a " + "window with information about KDE. " + "The KDE community are the people behind this free software." + "If you like using this application but don't know " + "about KDE or want to see a cute dragon have a look!"); + actionCollection()->action(KStandardAction::name(KStandardAction::AboutKDE)) + ->setWhatsThis(whatsThisAboutKDE); + m_helpMenu->action(KHelpMenu::menuAboutKDE)->setWhatsThis(whatsThisAboutKDE); +} + +bool DolphinMainWindow::event(QEvent *event) +{ + if (event->type() == QEvent::WhatsThisClicked) { + event->accept(); + QWhatsThisClickedEvent* whatsThisEvent = dynamic_cast(event); + QDesktopServices::openUrl(QUrl(whatsThisEvent->href())); + return true; + } + return KXmlGuiWindow::event(event); +} + +bool DolphinMainWindow::eventFilter(QObject* obj, QEvent* event) +{ + Q_UNUSED(obj) + if (event->type() == QEvent::WhatsThisClicked) { + event->accept(); + QWhatsThisClickedEvent* whatsThisEvent = dynamic_cast(event); + QDesktopServices::openUrl(QUrl(whatsThisEvent->href())); + return true; + } + return false; +} + 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 4037c1468..dcfd9bce2 100644 --- a/src/dolphinmainwindow.h +++ b/src/dolphinmainwindow.h @@ -1,589 +1,607 @@ /*************************************************************************** * 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 KHelpMenu; 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; + /** Handles QWhatsThisClickedEvent and passes all others on. */ + bool event(QEvent* event) override; + /** Handles QWhatsThisClickedEvent and passes all others on. */ + bool eventFilter(QObject*, QEvent*) 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: + /** + * Sets up the various menus and actions and connects them. + */ void setupActions(); + + /** + * Sets up the dock widgets and their panels. + */ 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); + /** Adds "What's This?" texts to many widgets and StandardActions. */ + void setupWhatsThis(); + 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; + KHelpMenu* m_helpMenu; 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/dolphinviewcontainer.cpp b/src/dolphinviewcontainer.cpp index 1e5d0f7d1..5d1d257e5 100644 --- a/src/dolphinviewcontainer.cpp +++ b/src/dolphinviewcontainer.cpp @@ -1,781 +1,805 @@ /*************************************************************************** * Copyright (C) 2007 by Peter Penz * * * * 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 "dolphinviewcontainer.h" #include "dolphin_generalsettings.h" #include "dolphinplacesmodelsingleton.h" #include "dolphindebug.h" #include "filterbar/filterbar.h" #include "global.h" #include "search/dolphinsearchbox.h" #include "statusbar/dolphinstatusbar.h" #include "trash/dolphintrash.h" #include "views/viewmodecontroller.h" #include "views/viewproperties.h" #ifdef HAVE_KACTIVITIES #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include DolphinViewContainer::DolphinViewContainer(const QUrl& url, QWidget* parent) : QWidget(parent), m_topLayout(nullptr), m_navigatorWidget(nullptr), m_urlNavigator(nullptr), m_emptyTrashButton(nullptr), m_searchBox(nullptr), m_searchModeEnabled(false), m_messageWidget(nullptr), m_view(nullptr), m_filterBar(nullptr), m_statusBar(nullptr), m_statusBarTimer(nullptr), m_statusBarTimestamp(), m_autoGrabFocus(true) #ifdef HAVE_KACTIVITIES , m_activityResourceInstance(nullptr) #endif { hide(); m_topLayout = new QVBoxLayout(this); m_topLayout->setSpacing(0); m_topLayout->setContentsMargins(0, 0, 0, 0); m_navigatorWidget = new QWidget(this); QHBoxLayout* navigatorLayout = new QHBoxLayout(m_navigatorWidget); navigatorLayout->setSpacing(0); navigatorLayout->setContentsMargins(0, 0, 0, 0); + m_navigatorWidget->setWhatsThis(xi18nc("@info:whatsthis location bar", + "This line describes the location of the files and folders " + "displayed below.The name of the currently viewed " + "folder can be read at the very right. To the left of it is the " + "name of the folder that contains it. The whole line is called " + "the path to the current location because " + "following these folders from left to right leads here." + "The path is displayed on the location bar " + "which is more powerful than one would expect. To learn more " + "about the basic and advanced features of the location bar " + "click here. " + "This will open the dedicated page in the Handbook.")); m_urlNavigator = new KUrlNavigator(DolphinPlacesModelSingleton::instance().placesModel(), url, this); connect(m_urlNavigator, &KUrlNavigator::activated, this, &DolphinViewContainer::activate); connect(m_urlNavigator->editor(), &KUrlComboBox::completionModeChanged, this, &DolphinViewContainer::saveUrlCompletionMode); const GeneralSettings* settings = GeneralSettings::self(); m_urlNavigator->setUrlEditable(settings->editableUrl()); m_urlNavigator->setShowFullPath(settings->showFullPath()); m_urlNavigator->setHomeUrl(Dolphin::homeUrl()); KUrlComboBox* editor = m_urlNavigator->editor(); editor->setCompletionMode(KCompletion::CompletionMode(settings->urlCompletionMode())); m_emptyTrashButton = new QPushButton(QIcon::fromTheme(QStringLiteral("user-trash")), i18nc("@action:button", "Empty Trash"), this); m_emptyTrashButton->setFlat(true); connect(m_emptyTrashButton, &QPushButton::clicked, this, [this]() { Trash::empty(this); }); connect(&Trash::instance(), &Trash::emptinessChanged, m_emptyTrashButton, &QPushButton::setDisabled); m_emptyTrashButton->setDisabled(Trash::isEmpty()); m_emptyTrashButton->hide(); m_searchBox = new DolphinSearchBox(this); m_searchBox->hide(); connect(m_searchBox, &DolphinSearchBox::activated, this, &DolphinViewContainer::activate); connect(m_searchBox, &DolphinSearchBox::closeRequest, this, &DolphinViewContainer::closeSearchBox); connect(m_searchBox, &DolphinSearchBox::searchRequest, this, &DolphinViewContainer::startSearching); connect(m_searchBox, &DolphinSearchBox::returnPressed, this, &DolphinViewContainer::requestFocus); + m_searchBox->setWhatsThis(xi18nc("@info:whatsthis findbar", + "This helps you find files and folders. Enter a " + "search term and specify search settings with the " + "buttons at the bottom:Filename/Content: " + "Does the item you are looking for contain the search terms " + "within its filename or its contents?The contents of images, " + "audio files and videos will not be searched." + "From Here/Everywhere: Do you want to search in this " + "folder and its sub-folders or everywhere?" + "More Options: Click this to search by media type, access " + "time or rating.More Search Tools: Install other " + "means to find an item.")); m_messageWidget = new KMessageWidget(this); m_messageWidget->setCloseButtonVisible(true); m_messageWidget->hide(); #ifndef Q_OS_WIN if (getuid() == 0) { // We must be logged in as the root user; show a big scary warning showMessage(i18n("Running Dolphin as root can be dangerous. Please be careful."), Warning); } #endif // Initialize filter bar m_filterBar = new FilterBar(this); m_filterBar->setVisible(settings->filterBar()); connect(m_filterBar, &FilterBar::filterChanged, this, &DolphinViewContainer::setNameFilter); connect(m_filterBar, &FilterBar::closeRequest, this, &DolphinViewContainer::closeFilterBar); connect(m_filterBar, &FilterBar::focusViewRequest, this, &DolphinViewContainer::requestFocus); // Initialize the main view m_view = new DolphinView(url, this); connect(m_view, &DolphinView::urlChanged, m_filterBar, &FilterBar::slotUrlChanged); connect(m_view, &DolphinView::urlChanged, m_urlNavigator, &KUrlNavigator::setLocationUrl); connect(m_view, &DolphinView::urlChanged, m_messageWidget, &KMessageWidget::hide); connect(m_view, &DolphinView::writeStateChanged, this, &DolphinViewContainer::writeStateChanged); connect(m_view, &DolphinView::requestItemInfo, this, &DolphinViewContainer::showItemInfo); connect(m_view, &DolphinView::itemActivated, this, &DolphinViewContainer::slotItemActivated); connect(m_view, &DolphinView::itemsActivated, this, &DolphinViewContainer::slotItemsActivated); connect(m_view, &DolphinView::redirection, this, &DolphinViewContainer::redirect); connect(m_view, &DolphinView::directoryLoadingStarted, this, &DolphinViewContainer::slotDirectoryLoadingStarted); connect(m_view, &DolphinView::directoryLoadingCompleted, this, &DolphinViewContainer::slotDirectoryLoadingCompleted); connect(m_view, &DolphinView::directoryLoadingCanceled, this, &DolphinViewContainer::slotDirectoryLoadingCanceled); connect(m_view, &DolphinView::itemCountChanged, this, &DolphinViewContainer::delayedStatusBarUpdate); connect(m_view, &DolphinView::directoryLoadingProgress, this, &DolphinViewContainer::updateDirectoryLoadingProgress); connect(m_view, &DolphinView::directorySortingProgress, this, &DolphinViewContainer::updateDirectorySortingProgress); connect(m_view, &DolphinView::selectionChanged, this, &DolphinViewContainer::delayedStatusBarUpdate); connect(m_view, &DolphinView::errorMessage, this, &DolphinViewContainer::showErrorMessage); connect(m_view, &DolphinView::urlIsFileError, this, &DolphinViewContainer::slotUrlIsFileError); connect(m_view, &DolphinView::activated, this, &DolphinViewContainer::activate); connect(m_urlNavigator, &KUrlNavigator::urlAboutToBeChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged); connect(m_urlNavigator, &KUrlNavigator::urlChanged, this, &DolphinViewContainer::slotUrlNavigatorLocationChanged); connect(m_urlNavigator, &KUrlNavigator::urlSelectionRequested, this, &DolphinViewContainer::slotUrlSelectionRequested); connect(m_urlNavigator, &KUrlNavigator::returnPressed, this, &DolphinViewContainer::slotReturnPressed); connect(m_urlNavigator, &KUrlNavigator::urlsDropped, this, [=](const QUrl &destination, QDropEvent *event) { m_view->dropUrls(destination, event, m_urlNavigator->dropWidget()); }); connect(m_view, &DolphinView::directoryLoadingCompleted, this, [this]() { m_emptyTrashButton->setVisible(m_view->url().scheme() == QLatin1String("trash")); }); // Initialize status bar m_statusBar = new DolphinStatusBar(this); m_statusBar->setUrl(m_view->url()); m_statusBar->setZoomLevel(m_view->zoomLevel()); connect(m_view, &DolphinView::urlChanged, m_statusBar, &DolphinStatusBar::setUrl); connect(m_view, &DolphinView::zoomLevelChanged, m_statusBar, &DolphinStatusBar::setZoomLevel); connect(m_view, &DolphinView::infoMessage, m_statusBar, &DolphinStatusBar::setText); connect(m_view, &DolphinView::operationCompletedMessage, m_statusBar, &DolphinStatusBar::setText); connect(m_statusBar, &DolphinStatusBar::stopPressed, this, &DolphinViewContainer::stopDirectoryLoading); connect(m_statusBar, &DolphinStatusBar::zoomLevelChanged, this, &DolphinViewContainer::slotStatusBarZoomLevelChanged); m_statusBarTimer = new QTimer(this); m_statusBarTimer->setSingleShot(true); m_statusBarTimer->setInterval(300); connect(m_statusBarTimer, &QTimer::timeout, this, &DolphinViewContainer::updateStatusBar); KIO::FileUndoManager* undoManager = KIO::FileUndoManager::self(); connect(undoManager, &KIO::FileUndoManager::jobRecordingFinished, this, &DolphinViewContainer::delayedStatusBarUpdate); navigatorLayout->addWidget(m_urlNavigator); navigatorLayout->addWidget(m_emptyTrashButton); m_topLayout->addWidget(m_navigatorWidget); m_topLayout->addWidget(m_searchBox); m_topLayout->addWidget(m_messageWidget); m_topLayout->addWidget(m_view); m_topLayout->addWidget(m_filterBar); m_topLayout->addWidget(m_statusBar); setSearchModeEnabled(isSearchUrl(url)); // Initialize kactivities resource instance #ifdef HAVE_KACTIVITIES m_activityResourceInstance = new KActivities::ResourceInstance(window()->winId(), url); m_activityResourceInstance->setParent(this); #endif } DolphinViewContainer::~DolphinViewContainer() { } QUrl DolphinViewContainer::url() const { return m_view->url(); } void DolphinViewContainer::setActive(bool active) { m_searchBox->setActive(active); m_urlNavigator->setActive(active); m_view->setActive(active); #ifdef HAVE_KACTIVITIES if (active) { m_activityResourceInstance->notifyFocusedIn(); } else { m_activityResourceInstance->notifyFocusedOut(); } #endif } bool DolphinViewContainer::isActive() const { Q_ASSERT(m_view->isActive() == m_urlNavigator->isActive()); return m_view->isActive(); } void DolphinViewContainer::setAutoGrabFocus(bool grab) { m_autoGrabFocus = grab; } bool DolphinViewContainer::autoGrabFocus() const { return m_autoGrabFocus; } QString DolphinViewContainer::currentSearchText() const { return m_searchBox->text(); } const DolphinStatusBar* DolphinViewContainer::statusBar() const { return m_statusBar; } DolphinStatusBar* DolphinViewContainer::statusBar() { return m_statusBar; } const KUrlNavigator* DolphinViewContainer::urlNavigator() const { return m_urlNavigator; } KUrlNavigator* DolphinViewContainer::urlNavigator() { return m_urlNavigator; } const DolphinView* DolphinViewContainer::view() const { return m_view; } DolphinView* DolphinViewContainer::view() { return m_view; } void DolphinViewContainer::showMessage(const QString& msg, MessageType type) { if (msg.isEmpty()) { return; } m_messageWidget->setText(msg); // TODO: wrap at arbitrary character positions once QLabel can do this // https://bugreports.qt.io/browse/QTBUG-1276 m_messageWidget->setWordWrap(true); switch (type) { case Information: m_messageWidget->setMessageType(KMessageWidget::Information); break; case Warning: m_messageWidget->setMessageType(KMessageWidget::Warning); break; case Error: m_messageWidget->setMessageType(KMessageWidget::Error); break; default: Q_ASSERT(false); break; } m_messageWidget->setWordWrap(false); const int unwrappedWidth = m_messageWidget->sizeHint().width(); m_messageWidget->setWordWrap(unwrappedWidth > size().width()); if (m_messageWidget->isVisible()) { m_messageWidget->hide(); } m_messageWidget->animatedShow(); } void DolphinViewContainer::readSettings() { if (GeneralSettings::modifiedStartupSettings()) { // The startup settings should only get applied if they have been // modified by the user. Otherwise keep the (possibly) different current // settings of the URL navigator and the filterbar. m_urlNavigator->setUrlEditable(GeneralSettings::editableUrl()); m_urlNavigator->setShowFullPath(GeneralSettings::showFullPath()); m_urlNavigator->setHomeUrl(Dolphin::homeUrl()); setFilterBarVisible(GeneralSettings::filterBar()); } m_view->readSettings(); m_statusBar->readSettings(); } bool DolphinViewContainer::isFilterBarVisible() const { return m_filterBar->isVisible(); } void DolphinViewContainer::setSearchModeEnabled(bool enabled) { if (enabled == isSearchModeEnabled()) { if (enabled && !m_searchBox->hasFocus()) { m_searchBox->setFocus(); m_searchBox->selectAll(); } return; } m_searchBox->setVisible(enabled); m_navigatorWidget->setVisible(!enabled); if (enabled) { const QUrl& locationUrl = m_urlNavigator->locationUrl(); m_searchBox->fromSearchUrl(locationUrl); } else { m_view->setViewPropertiesContext(QString()); // Restore the URL for the URL navigator. If Dolphin has been // started with a search-URL, the home URL is used as fallback. QUrl url = m_searchBox->searchPath(); if (url.isEmpty() || !url.isValid() || isSearchUrl(url)) { url = Dolphin::homeUrl(); } m_urlNavigator->setLocationUrl(url); } m_searchModeEnabled = enabled; } bool DolphinViewContainer::isSearchModeEnabled() const { return m_searchModeEnabled; } QString DolphinViewContainer::placesText() const { QString text; if (isSearchModeEnabled()) { text = i18n("Search for %1 in %2", m_searchBox->text(), m_searchBox->searchPath().fileName()); } else { text = url().fileName(); if (text.isEmpty()) { text = url().host(); } if (text.isEmpty()) { text = url().scheme(); } } return text; } void DolphinViewContainer::reload() { view()->reload(); m_messageWidget->hide(); } QString DolphinViewContainer::caption() const { if (GeneralSettings::showFullPathInTitlebar()) { if (!url().isLocalFile()) { return url().adjusted(QUrl::StripTrailingSlash).toString(); } return url().adjusted(QUrl::StripTrailingSlash).path(); } KFilePlacesModel *placesModel = DolphinPlacesModelSingleton::instance().placesModel(); const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, url(), 1, Qt::MatchExactly); if (!matchedPlaces.isEmpty()) { return placesModel->text(matchedPlaces.first()); } if (isSearchModeEnabled()) { if (currentSearchText().isEmpty()){ return i18n("Search"); } else { return i18n("Search for %1", currentSearchText()); } } if (!url().isLocalFile()) { QUrl adjustedUrl = url().adjusted(QUrl::StripTrailingSlash); QString caption; if (!adjustedUrl.fileName().isEmpty()) { caption = adjustedUrl.fileName(); } else if (!adjustedUrl.path().isEmpty() && adjustedUrl.path() != "/") { caption = adjustedUrl.path(); } else if (!adjustedUrl.host().isEmpty()) { caption = adjustedUrl.host(); } else { caption = adjustedUrl.toString(); } return caption; } QString fileName = url().adjusted(QUrl::StripTrailingSlash).fileName(); if (fileName.isEmpty()) { fileName = '/'; } return fileName; } void DolphinViewContainer::setUrl(const QUrl& newUrl) { if (newUrl != m_urlNavigator->locationUrl()) { m_urlNavigator->setLocationUrl(newUrl); } #ifdef HAVE_KACTIVITIES m_activityResourceInstance->setUri(newUrl); #endif } void DolphinViewContainer::setFilterBarVisible(bool visible) { Q_ASSERT(m_filterBar); if (visible) { m_filterBar->show(); m_filterBar->setFocus(); m_filterBar->selectAll(); } else { closeFilterBar(); } } void DolphinViewContainer::delayedStatusBarUpdate() { if (m_statusBarTimer->isActive() && (m_statusBarTimestamp.elapsed() > 2000)) { // No update of the statusbar has been done during the last 2 seconds, // although an update has been requested. Trigger an immediate update. m_statusBarTimer->stop(); updateStatusBar(); } else { // Invoke updateStatusBar() with a small delay. This assures that // when a lot of delayedStatusBarUpdates() are done in a short time, // no bottleneck is given. m_statusBarTimer->start(); } } void DolphinViewContainer::updateStatusBar() { m_statusBarTimestamp.start(); const QString text = m_view->statusBarText(); m_statusBar->setDefaultText(text); m_statusBar->resetToDefaultText(); } void DolphinViewContainer::updateDirectoryLoadingProgress(int percent) { if (m_statusBar->progressText().isEmpty()) { m_statusBar->setProgressText(i18nc("@info:progress", "Loading folder...")); } m_statusBar->setProgress(percent); } void DolphinViewContainer::updateDirectorySortingProgress(int percent) { if (m_statusBar->progressText().isEmpty()) { m_statusBar->setProgressText(i18nc("@info:progress", "Sorting...")); } m_statusBar->setProgress(percent); } void DolphinViewContainer::slotDirectoryLoadingStarted() { if (isSearchUrl(url())) { // Search KIO-slaves usually don't provide any progress information. Give // a hint to the user that a searching is done: updateStatusBar(); m_statusBar->setProgressText(i18nc("@info", "Searching...")); m_statusBar->setProgress(-1); } else { // Trigger an undetermined progress indication. The progress // information in percent will be triggered by the percent() signal // of the directory lister later. updateDirectoryLoadingProgress(-1); } } void DolphinViewContainer::slotDirectoryLoadingCompleted() { if (!m_statusBar->progressText().isEmpty()) { m_statusBar->setProgressText(QString()); m_statusBar->setProgress(100); } if (isSearchUrl(url()) && m_view->itemsCount() == 0) { // The dir lister has been completed on a Baloo-URI and no items have been found. Instead // of showing the default status bar information ("0 items") a more helpful information is given: m_statusBar->setText(i18nc("@info:status", "No items found.")); } else { updateStatusBar(); } } void DolphinViewContainer::slotDirectoryLoadingCanceled() { if (!m_statusBar->progressText().isEmpty()) { m_statusBar->setProgressText(QString()); m_statusBar->setProgress(100); } m_statusBar->setText(QString()); } void DolphinViewContainer::slotUrlIsFileError(const QUrl& url) { const KFileItem item(url); // Find out if the file can be opened in the view (for example, this is the // case if the file is an archive). The mime type must be known for that. item.determineMimeType(); const QUrl& folderUrl = DolphinView::openItemAsFolderUrl(item, true); if (!folderUrl.isEmpty()) { setUrl(folderUrl); } else { slotItemActivated(item); } } void DolphinViewContainer::slotItemActivated(const KFileItem& item) { // It is possible to activate items on inactive views by // drag & drop operations. Assure that activating an item always // results in an active view. m_view->setActive(true); const QUrl& url = DolphinView::openItemAsFolderUrl(item, GeneralSettings::browseThroughArchives()); if (!url.isEmpty()) { setUrl(url); return; } KRun *run = new KRun(item.targetUrl(), this); run->setShowScriptExecutionPrompt(true); } void DolphinViewContainer::slotItemsActivated(const KFileItemList& items) { Q_ASSERT(items.count() >= 2); KFileItemActions fileItemActions(this); fileItemActions.runPreferredApplications(items, QString()); } void DolphinViewContainer::showItemInfo(const KFileItem& item) { if (item.isNull()) { m_statusBar->resetToDefaultText(); } else { m_statusBar->setText(item.getStatusBarInfo()); } } void DolphinViewContainer::closeFilterBar() { m_filterBar->closeFilterBar(); m_view->setFocus(); emit showFilterBarChanged(false); } void DolphinViewContainer::setNameFilter(const QString& nameFilter) { m_view->setNameFilter(nameFilter); delayedStatusBarUpdate(); } void DolphinViewContainer::activate() { setActive(true); } void DolphinViewContainer::slotUrlNavigatorLocationAboutToBeChanged(const QUrl&) { saveViewState(); } void DolphinViewContainer::slotUrlNavigatorLocationChanged(const QUrl& url) { slotReturnPressed(); if (KProtocolManager::supportsListing(url)) { setSearchModeEnabled(isSearchUrl(url)); m_view->setUrl(url); tryRestoreViewState(); if (m_autoGrabFocus && isActive() && !isSearchUrl(url)) { // When an URL has been entered, the view should get the focus. // The focus must be requested asynchronously, as changing the URL might create // a new view widget. QTimer::singleShot(0, this, &DolphinViewContainer::requestFocus); } } else if (KProtocolManager::isSourceProtocol(url)) { QString app = QStringLiteral("konqueror"); if (url.scheme().startsWith(QLatin1String("http"))) { showMessage(i18nc("@info:status", // krazy:exclude=qmethods "Dolphin does not support web pages, the web browser has been launched"), Information); const KConfigGroup config(KSharedConfig::openConfig(QStringLiteral("kdeglobals")), "General"); const QString browser = config.readEntry("BrowserApplication"); if (!browser.isEmpty()) { app = browser; if (app.startsWith('!')) { // a literal command has been configured, remove the '!' prefix app = app.mid(1); } } } else { showMessage(i18nc("@info:status", "Protocol not supported by Dolphin, Konqueror has been launched"), Information); } const QString secureUrl = KShell::quoteArg(url.toDisplayString(QUrl::PreferLocalFile)); const QString command = app + ' ' + secureUrl; KRun::runCommand(command, app, app, this); } else { showMessage(i18nc("@info:status", "Invalid protocol"), Error); } } void DolphinViewContainer::slotUrlSelectionRequested(const QUrl& url) { m_view->markUrlsAsSelected({url}); m_view->markUrlAsCurrent(url); // makes the item scroll into view } void DolphinViewContainer::redirect(const QUrl& oldUrl, const QUrl& newUrl) { Q_UNUSED(oldUrl); const bool block = m_urlNavigator->signalsBlocked(); m_urlNavigator->blockSignals(true); // Assure that the location state is reset for redirection URLs. This // allows to skip redirection URLs when going back or forward in the // URL history. m_urlNavigator->saveLocationState(QByteArray()); m_urlNavigator->setLocationUrl(newUrl); setSearchModeEnabled(isSearchUrl(newUrl)); m_urlNavigator->blockSignals(block); } void DolphinViewContainer::requestFocus() { m_view->setFocus(); } void DolphinViewContainer::saveUrlCompletionMode(KCompletion::CompletionMode completion) { GeneralSettings::setUrlCompletionMode(completion); } void DolphinViewContainer::slotReturnPressed() { if (!GeneralSettings::editableUrl()) { m_urlNavigator->setUrlEditable(false); } } void DolphinViewContainer::startSearching() { const QUrl url = m_searchBox->urlForSearching(); if (url.isValid() && !url.isEmpty()) { m_view->setViewPropertiesContext(QStringLiteral("search")); m_urlNavigator->setLocationUrl(url); } } void DolphinViewContainer::closeSearchBox() { setSearchModeEnabled(false); } void DolphinViewContainer::stopDirectoryLoading() { m_view->stopLoading(); m_statusBar->setProgress(100); } void DolphinViewContainer::slotStatusBarZoomLevelChanged(int zoomLevel) { m_view->setZoomLevel(zoomLevel); } void DolphinViewContainer::showErrorMessage(const QString& msg) { showMessage(msg, Error); } bool DolphinViewContainer::isSearchUrl(const QUrl& url) const { return url.scheme().contains(QStringLiteral("search")); } void DolphinViewContainer::saveViewState() { QByteArray locationState; QDataStream stream(&locationState, QIODevice::WriteOnly); m_view->saveState(stream); m_urlNavigator->saveLocationState(locationState); } void DolphinViewContainer::tryRestoreViewState() { QByteArray locationState = m_urlNavigator->locationState(); if (!locationState.isEmpty()) { QDataStream stream(&locationState, QIODevice::ReadOnly); m_view->restoreState(stream); } } diff --git a/src/statusbar/dolphinstatusbar.cpp b/src/statusbar/dolphinstatusbar.cpp index 0feaa119b..41c787eaa 100644 --- a/src/statusbar/dolphinstatusbar.cpp +++ b/src/statusbar/dolphinstatusbar.cpp @@ -1,342 +1,351 @@ /*************************************************************************** * Copyright (C) 2006-2012 by Peter Penz * * * * 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 "dolphinstatusbar.h" #include "dolphin_generalsettings.h" #include "statusbarspaceinfo.h" #include "views/dolphinview.h" #include "views/zoomlevelinfo.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace { const int ResetToDefaultTimeout = 1000; } DolphinStatusBar::DolphinStatusBar(QWidget* parent) : QWidget(parent), m_text(), m_defaultText(), m_label(nullptr), m_spaceInfo(nullptr), m_zoomSlider(nullptr), m_progressBar(nullptr), m_stopButton(nullptr), m_progress(100), m_showProgressBarTimer(nullptr), m_resetToDefaultTextTimer(nullptr), m_textTimestamp() { // Initialize text label m_label = new KSqueezedTextLabel(m_text, this); m_label->setWordWrap(true); m_label->setTextFormat(Qt::PlainText); // Initialize zoom widget m_zoomSlider = new QSlider(Qt::Horizontal, this); m_zoomSlider->setAccessibleName(i18n("Zoom")); m_zoomSlider->setAccessibleDescription(i18nc("Description for zoom-slider (accessibility)", "Sets the size of the file icons.")); m_zoomSlider->setPageStep(1); m_zoomSlider->setRange(ZoomLevelInfo::minimumLevel(), ZoomLevelInfo::maximumLevel()); connect(m_zoomSlider, &QSlider::valueChanged, this, &DolphinStatusBar::zoomLevelChanged); connect(m_zoomSlider, &QSlider::valueChanged, this, &DolphinStatusBar::updateZoomSliderToolTip); connect(m_zoomSlider, &QSlider::sliderMoved, this, &DolphinStatusBar::showZoomSliderToolTip); // Initialize space information m_spaceInfo = new StatusBarSpaceInfo(this); // Initialize progress information m_stopButton = new QToolButton(this); m_stopButton->setIcon(QIcon::fromTheme(QStringLiteral("process-stop"))); m_stopButton->setAccessibleName(i18n("Stop")); m_stopButton->setAutoRaise(true); m_stopButton->setToolTip(i18nc("@tooltip", "Stop loading")); m_stopButton->hide(); connect(m_stopButton, &QToolButton::clicked, this, &DolphinStatusBar::stopPressed); m_progressTextLabel = new QLabel(this); m_progressTextLabel->hide(); m_progressBar = new QProgressBar(this); m_progressBar->hide(); m_showProgressBarTimer = new QTimer(this); m_showProgressBarTimer->setInterval(500); m_showProgressBarTimer->setSingleShot(true); connect(m_showProgressBarTimer, &QTimer::timeout, this, &DolphinStatusBar::updateProgressInfo); m_resetToDefaultTextTimer = new QTimer(this); m_resetToDefaultTextTimer->setInterval(ResetToDefaultTimeout); m_resetToDefaultTextTimer->setSingleShot(true); connect(m_resetToDefaultTextTimer, &QTimer::timeout, this, &DolphinStatusBar::slotResetToDefaultText); // Initialize top layout and size policies const int fontHeight = QFontMetrics(m_label->font()).height(); const int zoomSliderHeight = m_zoomSlider->minimumSizeHint().height(); const int buttonHeight = m_stopButton->height(); const int contentHeight = qMax(qMax(fontHeight, zoomSliderHeight), buttonHeight); QFontMetrics fontMetrics(m_label->font()); m_label->setFixedHeight(contentHeight); m_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_zoomSlider->setMaximumWidth(fontMetrics.averageCharWidth() * 25); m_spaceInfo->setFixedHeight(zoomSliderHeight); m_spaceInfo->setMaximumWidth(fontMetrics.averageCharWidth() * 25); m_spaceInfo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_progressBar->setFixedHeight(zoomSliderHeight); m_progressBar->setMaximumWidth(fontMetrics.averageCharWidth() * 25); QHBoxLayout* topLayout = new QHBoxLayout(this); topLayout->setContentsMargins(2, 0, 2, 0); topLayout->setSpacing(4); topLayout->addWidget(m_label, 1); topLayout->addWidget(m_zoomSlider, 1); topLayout->addWidget(m_spaceInfo, 1); topLayout->addWidget(m_stopButton); topLayout->addWidget(m_progressTextLabel); topLayout->addWidget(m_progressBar); setExtensionsVisible(true); + setWhatsThis(xi18nc("@info:whatsthis Statusbar", "This is " + "the Statusbar. It contains three elements " + "by default (left to right):A text field" + " that displays the size of selected items. If only " + "one item is selected the name and type is shown as well." + "A zoom slider that allows you " + "to adjust the size of the icons in the view." + "Space information about the " + "current storage device.")); } DolphinStatusBar::~DolphinStatusBar() { } void DolphinStatusBar::setText(const QString& text) { if (m_text == text) { return; } m_textTimestamp = QTime::currentTime(); if (text.isEmpty()) { // Assure that the previous set text won't get // cleared immediately. m_resetToDefaultTextTimer->start(); } else { m_text = text; if (m_resetToDefaultTextTimer->isActive()) { m_resetToDefaultTextTimer->start(); } updateLabelText(); } } QString DolphinStatusBar::text() const { return m_text; } void DolphinStatusBar::setProgressText(const QString& text) { m_progressTextLabel->setText(text); } QString DolphinStatusBar::progressText() const { return m_progressTextLabel->text(); } void DolphinStatusBar::setProgress(int percent) { // Show a busy indicator if a value < 0 is provided: m_progressBar->setMaximum((percent < 0) ? 0 : 100); percent = qBound(0, percent, 100); const bool progressRestarted = (percent < 100) && (percent < m_progress); m_progress = percent; if (progressRestarted && !m_progressBar->isVisible()) { // Show the progress bar delayed: In the case if 100 % are reached within // a short time, no progress bar will be shown at all. m_showProgressBarTimer->start(); } m_progressBar->setValue(m_progress); if (percent == 100) { // The end of the progress has been reached. Assure that the progress bar // gets hidden and the extensions widgets get visible again. m_showProgressBarTimer->stop(); updateProgressInfo(); } } int DolphinStatusBar::progress() const { return m_progress; } void DolphinStatusBar::resetToDefaultText() { QTime currentTime; if (currentTime.msecsTo(m_textTimestamp) < ResetToDefaultTimeout) { m_resetToDefaultTextTimer->start(); } else { m_resetToDefaultTextTimer->stop(); slotResetToDefaultText(); } } void DolphinStatusBar::setDefaultText(const QString& text) { m_defaultText = text; updateLabelText(); } QString DolphinStatusBar::defaultText() const { return m_defaultText; } void DolphinStatusBar::setUrl(const QUrl& url) { m_spaceInfo->setUrl(url); } QUrl DolphinStatusBar::url() const { return m_spaceInfo->url(); } void DolphinStatusBar::setZoomLevel(int zoomLevel) { if (zoomLevel != m_zoomSlider->value()) { m_zoomSlider->setValue(zoomLevel); } } int DolphinStatusBar::zoomLevel() const { return m_zoomSlider->value(); } void DolphinStatusBar::readSettings() { setExtensionsVisible(true); } void DolphinStatusBar::updateSpaceInfo() { m_spaceInfo->update(); } void DolphinStatusBar::contextMenuEvent(QContextMenuEvent* event) { Q_UNUSED(event); QMenu menu(this); QAction* showZoomSliderAction = menu.addAction(i18nc("@action:inmenu", "Show Zoom Slider")); showZoomSliderAction->setCheckable(true); showZoomSliderAction->setChecked(GeneralSettings::showZoomSlider()); QAction* showSpaceInfoAction = menu.addAction(i18nc("@action:inmenu", "Show Space Information")); showSpaceInfoAction->setCheckable(true); showSpaceInfoAction->setChecked(GeneralSettings::showSpaceInfo()); const QAction* action = menu.exec(QCursor::pos()); if (action == showZoomSliderAction) { const bool visible = showZoomSliderAction->isChecked(); GeneralSettings::setShowZoomSlider(visible); m_zoomSlider->setVisible(visible); } else if (action == showSpaceInfoAction) { const bool visible = showSpaceInfoAction->isChecked(); GeneralSettings::setShowSpaceInfo(visible); m_spaceInfo->setVisible(visible); } } void DolphinStatusBar::showZoomSliderToolTip(int zoomLevel) { updateZoomSliderToolTip(zoomLevel); QPoint global = m_zoomSlider->rect().topLeft(); global.ry() += m_zoomSlider->height() / 2; QHelpEvent toolTipEvent(QEvent::ToolTip, QPoint(0, 0), m_zoomSlider->mapToGlobal(global)); QApplication::sendEvent(m_zoomSlider, &toolTipEvent); } void DolphinStatusBar::updateProgressInfo() { if (m_progress < 100) { // Show the progress information and hide the extensions m_stopButton->show(); m_progressTextLabel->show(); m_progressBar->show(); setExtensionsVisible(false); } else { // Hide the progress information and show the extensions m_stopButton->hide(); m_progressTextLabel->hide(); m_progressBar->hide(); setExtensionsVisible(true); } } void DolphinStatusBar::updateLabelText() { const QString text = m_text.isEmpty() ? m_defaultText : m_text; m_label->setText(text); } void DolphinStatusBar::slotResetToDefaultText() { m_text.clear(); updateLabelText(); } void DolphinStatusBar::updateZoomSliderToolTip(int zoomLevel) { const int size = ZoomLevelInfo::iconSizeForZoomLevel(zoomLevel); m_zoomSlider->setToolTip(i18ncp("@info:tooltip", "Size: 1 pixel", "Size: %1 pixels", size)); } void DolphinStatusBar::setExtensionsVisible(bool visible) { bool showSpaceInfo = visible; bool showZoomSlider = visible; if (visible) { showSpaceInfo = GeneralSettings::showSpaceInfo(); showZoomSlider = GeneralSettings::showZoomSlider(); } m_spaceInfo->setVisible(showSpaceInfo); m_zoomSlider->setVisible(showZoomSlider); } diff --git a/src/views/dolphinviewactionhandler.cpp b/src/views/dolphinviewactionhandler.cpp index 6e5468cd5..6169ec2c1 100644 --- a/src/views/dolphinviewactionhandler.cpp +++ b/src/views/dolphinviewactionhandler.cpp @@ -1,599 +1,651 @@ /*************************************************************************** * Copyright (C) 2008 by David Faure * * Copyright (C) 2012 by Peter Penz * * * * 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 "dolphinviewactionhandler.h" #include "dolphindebug.h" #include "kitemviews/kfileitemmodel.h" #include "settings/viewpropertiesdialog.h" #include "views/zoomlevelinfo.h" #ifdef HAVE_BALOO #include #endif #include #include #include #include #include #include #include #include DolphinViewActionHandler::DolphinViewActionHandler(KActionCollection* collection, QObject* parent) : QObject(parent), m_actionCollection(collection), m_currentView(nullptr), m_sortByActions(), m_visibleRoles() { Q_ASSERT(m_actionCollection); createActions(); } void DolphinViewActionHandler::setCurrentView(DolphinView* view) { Q_ASSERT(view); if (m_currentView) { disconnect(m_currentView, nullptr, this, nullptr); } m_currentView = view; connect(view, &DolphinView::modeChanged, this, &DolphinViewActionHandler::updateViewActions); connect(view, &DolphinView::previewsShownChanged, this, &DolphinViewActionHandler::slotPreviewsShownChanged); connect(view, &DolphinView::sortOrderChanged, this, &DolphinViewActionHandler::slotSortOrderChanged); connect(view, &DolphinView::sortFoldersFirstChanged, this, &DolphinViewActionHandler::slotSortFoldersFirstChanged); connect(view, &DolphinView::visibleRolesChanged, this, &DolphinViewActionHandler::slotVisibleRolesChanged); connect(view, &DolphinView::groupedSortingChanged, this, &DolphinViewActionHandler::slotGroupedSortingChanged); connect(view, &DolphinView::hiddenFilesShownChanged, this, &DolphinViewActionHandler::slotHiddenFilesShownChanged); connect(view, &DolphinView::sortRoleChanged, this, &DolphinViewActionHandler::slotSortRoleChanged); connect(view, &DolphinView::zoomLevelChanged, this, &DolphinViewActionHandler::slotZoomLevelChanged); connect(view, &DolphinView::writeStateChanged, this, &DolphinViewActionHandler::slotWriteStateChanged); } DolphinView* DolphinViewActionHandler::currentView() { return m_currentView; } void DolphinViewActionHandler::createActions() { // This action doesn't appear in the GUI, it's for the shortcut only. // KNewFileMenu takes care of the GUI stuff. QAction* newDirAction = m_actionCollection->addAction(QStringLiteral("create_dir")); newDirAction->setText(i18nc("@action", "Create Folder...")); m_actionCollection->setDefaultShortcut(newDirAction, Qt::Key_F10); newDirAction->setIcon(QIcon::fromTheme(QStringLiteral("folder-new"))); newDirAction->setEnabled(false); // Will be enabled in slotWriteStateChanged(bool) if the current URL is writable connect(newDirAction, &QAction::triggered, this, &DolphinViewActionHandler::createDirectoryTriggered); // File menu - KStandardAction::renameFile(this, &DolphinViewActionHandler::slotRename, m_actionCollection); + auto renameAction = KStandardAction::renameFile(this, &DolphinViewActionHandler::slotRename, m_actionCollection); + renameAction->setWhatsThis(xi18nc("@info:whatsthis", "This renames the " + "items in your current selection.Renaming multiple items " + "at once amounts to their new names differing only in a number.")); auto trashAction = KStandardAction::moveToTrash(this, &DolphinViewActionHandler::slotTrashActivated, m_actionCollection); auto trashShortcuts = trashAction->shortcuts(); if (!trashShortcuts.contains(QKeySequence::Delete)) { trashShortcuts.append(QKeySequence::Delete); m_actionCollection->setDefaultShortcuts(trashAction, trashShortcuts); } + trashAction->setWhatsThis(xi18nc("@info:whatsthis", "This moves the " + "items in your current selection to the Trash" + ".The trash is a temporary storage where " + "items can be deleted from if disk space is needed.")); auto deleteAction = KStandardAction::deleteFile(this, &DolphinViewActionHandler::slotDeleteItems, m_actionCollection); auto deleteShortcuts = deleteAction->shortcuts(); if (!deleteShortcuts.contains(Qt::SHIFT | Qt::Key_Delete)) { deleteShortcuts.append(Qt::SHIFT | Qt::Key_Delete); m_actionCollection->setDefaultShortcuts(deleteAction, deleteShortcuts); } + deleteAction->setWhatsThis(xi18nc("@info:whatsthis", "This deletes " + "the items in your current selection completely. They can " + "not be recovered by normal means.")); // This action is useful for being enabled when KStandardAction::MoveToTrash should be // disabled and KStandardAction::DeleteFile is enabled (e.g. non-local files), so that Key_Del // can be used for deleting the file (#76016). It needs to be a separate action // so that the Edit menu isn't affected. QAction* deleteWithTrashShortcut = m_actionCollection->addAction(QStringLiteral("delete_shortcut")); // The descriptive text is just for the shortcuts editor. deleteWithTrashShortcut->setText(i18nc("@action \"Move to Trash\" for non-local files, etc.", "Delete (using shortcut for Trash)")); m_actionCollection->setDefaultShortcuts(deleteWithTrashShortcut, KStandardShortcut::moveToTrash()); deleteWithTrashShortcut->setEnabled(false); connect(deleteWithTrashShortcut, &QAction::triggered, this, &DolphinViewActionHandler::slotDeleteItems); QAction *propertiesAction = m_actionCollection->addAction( QStringLiteral("properties") ); // Well, it's the File menu in dolphinmainwindow and the Edit menu in dolphinpart... :) propertiesAction->setText( i18nc("@action:inmenu File", "Properties") ); + propertiesAction->setWhatsThis(xi18nc("@info:whatsthis properties", + "This shows a complete list of properties of the currently " + "selected items in a new window.If nothing is selected the " + "window will be about the currently viewed folder instead." + "You can configure advanced options there like managing " + "read- and write-permissions.")); propertiesAction->setIcon(QIcon::fromTheme(QStringLiteral("document-properties"))); m_actionCollection->setDefaultShortcuts(propertiesAction, {Qt::ALT + Qt::Key_Return, Qt::ALT + Qt::Key_Enter}); connect(propertiesAction, &QAction::triggered, this, &DolphinViewActionHandler::slotProperties); // View menu KToggleAction* iconsAction = iconsModeAction(); KToggleAction* compactAction = compactModeAction(); KToggleAction* detailsAction = detailsModeAction(); + iconsAction->setWhatsThis(xi18nc("@info:whatsthis Icons view mode", + "This switches to a view mode that focuses on the folder " + "and file icons. This mode makes it easy to distinguish folders " + "from files and to detect items with distinctive " + "file types. This mode is handy to " + "browse through pictures when the Preview" + " option is enabled.")); + compactAction->setWhatsThis(xi18nc("@info:whatsthis Compact view mode", + "This switches to a compact view mode that lists the folders " + "and files in columns with the names beside the icons. " + "This helps to keep the overview in folders with many items.")); + detailsAction->setWhatsThis(xi18nc("@info:whatsthis Details view mode", + "This switches to a list view mode that focuses on folder " + "and file details.Click on a detail in the column " + "header to sort the items by it. Click again to sort the other " + "way around. To select which details should be displayed click " + "the header with the right mouse button.You can " + "view the contents of a folder without leaving the current " + "location by clicking to the left of it. This way you can view " + "the contents of multiple folders in the same list.")); + KSelectAction* viewModeActions = m_actionCollection->add(QStringLiteral("view_mode")); viewModeActions->setText(i18nc("@action:intoolbar", "View Mode")); viewModeActions->addAction(iconsAction); viewModeActions->addAction(compactAction); viewModeActions->addAction(detailsAction); viewModeActions->setToolBarMode(KSelectAction::MenuMode); connect(viewModeActions, QOverload::of(&KSelectAction::triggered), this, &DolphinViewActionHandler::slotViewModeActionTriggered); - KStandardAction::zoomIn(this, + QAction* zoomInAction = KStandardAction::zoomIn(this, &DolphinViewActionHandler::zoomIn, m_actionCollection); + zoomInAction->setWhatsThis(i18nc("@info:whatsthis zoom in", "This increases the icon size.")); - KStandardAction::zoomOut(this, + QAction* zoomOutAction = KStandardAction::zoomOut(this, &DolphinViewActionHandler::zoomOut, m_actionCollection); + zoomOutAction->setWhatsThis(i18nc("@info:whatsthis zoom in", "This reduces the icon size.")); KToggleAction* showPreview = m_actionCollection->add(QStringLiteral("show_preview")); showPreview->setText(i18nc("@action:intoolbar", "Preview")); showPreview->setToolTip(i18nc("@info", "Show preview of files and folders")); + showPreview->setWhatsThis(xi18nc("@info:whatsthis", "When this is " + "enabled, the icons are based on the actual file or folder " + "contents.For example the icons of images become scaled " + "down versions of the images.")); showPreview->setIcon(QIcon::fromTheme(QStringLiteral("view-preview"))); connect(showPreview, &KToggleAction::triggered, this, &DolphinViewActionHandler::togglePreview); KToggleAction* sortDescending = m_actionCollection->add(QStringLiteral("descending")); sortDescending->setText(i18nc("@action:inmenu Sort", "Descending")); connect(sortDescending, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleSortOrder); KToggleAction* sortFoldersFirst = m_actionCollection->add(QStringLiteral("folders_first")); sortFoldersFirst->setText(i18nc("@action:inmenu Sort", "Folders First")); connect(sortFoldersFirst, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleSortFoldersFirst); // View -> Sort By QActionGroup* sortByActionGroup = createFileItemRolesActionGroup(QStringLiteral("sort_by_")); KActionMenu* sortByActionMenu = m_actionCollection->add(QStringLiteral("sort")); sortByActionMenu->setIcon(QIcon::fromTheme(QStringLiteral("view-sort"))); sortByActionMenu->setText(i18nc("@action:inmenu View", "Sort By")); sortByActionMenu->setDelayed(false); foreach (QAction* action, sortByActionGroup->actions()) { sortByActionMenu->addAction(action); } sortByActionMenu->addSeparator(); sortByActionMenu->addAction(sortDescending); sortByActionMenu->addAction(sortFoldersFirst); // View -> Additional Information QActionGroup* visibleRolesGroup = createFileItemRolesActionGroup(QStringLiteral("show_")); KActionMenu* visibleRolesMenu = m_actionCollection->add(QStringLiteral("additional_info")); visibleRolesMenu->setText(i18nc("@action:inmenu View", "Additional Information")); visibleRolesMenu->setDelayed(false); foreach (QAction* action, visibleRolesGroup->actions()) { visibleRolesMenu->addAction(action); } KToggleAction* showInGroups = m_actionCollection->add(QStringLiteral("show_in_groups")); showInGroups->setIcon(QIcon::fromTheme(QStringLiteral("view-group"))); showInGroups->setText(i18nc("@action:inmenu View", "Show in Groups")); + showInGroups->setWhatsThis(i18nc("@info:whatsthis", "This groups files and folders by their first letter.")); connect(showInGroups, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleGroupedSorting); KToggleAction* showHiddenFiles = m_actionCollection->add(QStringLiteral("show_hidden_files")); showHiddenFiles->setText(i18nc("@action:inmenu View", "Hidden Files")); showHiddenFiles->setToolTip(i18nc("@info", "Visibility of hidden files and folders")); + showHiddenFiles->setWhatsThis(xi18nc("@info:whatsthis", "When " + "this is enabled hidden files and folders " + "are visible. They will be displayed semi-transparent." + "Hidden items only differ from other ones in that their " + "name starts with a \".\". In general there is no need for " + "users to access them which is why they are hidden.")); m_actionCollection->setDefaultShortcuts(showHiddenFiles, {Qt::ALT + Qt::Key_Period, Qt::CTRL + Qt::Key_H, Qt::Key_F8}); connect(showHiddenFiles, &KToggleAction::triggered, this, &DolphinViewActionHandler::toggleShowHiddenFiles); QAction* adjustViewProps = m_actionCollection->addAction(QStringLiteral("view_properties")); adjustViewProps->setText(i18nc("@action:inmenu View", "Adjust View Properties...")); + adjustViewProps->setWhatsThis(i18nc("@info:whatsthis", "This opens a window " + "in which all folder view properties can be adjusted.")); connect(adjustViewProps, &QAction::triggered, this, &DolphinViewActionHandler::slotAdjustViewProperties); } QActionGroup* DolphinViewActionHandler::createFileItemRolesActionGroup(const QString& groupPrefix) { const bool isSortGroup = (groupPrefix == QLatin1String("sort_by_")); Q_ASSERT(isSortGroup || (!isSortGroup && groupPrefix == QLatin1String("show_"))); QActionGroup* rolesActionGroup = new QActionGroup(m_actionCollection); rolesActionGroup->setExclusive(isSortGroup); if (isSortGroup) { connect(rolesActionGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::slotSortTriggered); } else { connect(rolesActionGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::toggleVisibleRole); } QString groupName; KActionMenu* groupMenu = nullptr; QActionGroup* groupMenuGroup = nullptr; bool indexingEnabled = false; #ifdef HAVE_BALOO Baloo::IndexerConfig config; indexingEnabled = config.fileIndexingEnabled(); #endif const QList rolesInfo = KFileItemModel::rolesInformation(); foreach (const KFileItemModel::RoleInfo& info, rolesInfo) { if (!isSortGroup && info.role == "text") { // It should not be possible to hide the "text" role continue; } KToggleAction* action = nullptr; const QString name = groupPrefix + info.role; if (info.group.isEmpty()) { action = m_actionCollection->add(name); action->setActionGroup(rolesActionGroup); } else { if (!groupMenu || info.group != groupName) { groupName = info.group; groupMenu = m_actionCollection->add(groupName); groupMenu->setText(groupName); groupMenu->setActionGroup(rolesActionGroup); groupMenuGroup = new QActionGroup(groupMenu); groupMenuGroup->setExclusive(isSortGroup); if (isSortGroup) { connect(groupMenuGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::slotSortTriggered); } else { connect(groupMenuGroup, &QActionGroup::triggered, this, &DolphinViewActionHandler::toggleVisibleRole); } } action = new KToggleAction(groupMenu); action->setActionGroup(groupMenuGroup); groupMenu->addAction(action); } action->setText(info.translation); action->setData(info.role); const bool enable = (!info.requiresBaloo && !info.requiresIndexer) || (info.requiresBaloo) || (info.requiresIndexer && indexingEnabled); action->setEnabled(enable); if (isSortGroup) { m_sortByActions.insert(info.role, action); } else { m_visibleRoles.insert(info.role, action); } } return rolesActionGroup; } void DolphinViewActionHandler::slotViewModeActionTriggered(QAction* action) { const DolphinView::Mode mode = action->data().value(); m_currentView->setMode(mode); QAction* viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode")); viewModeMenu->setIcon(action->icon()); } void DolphinViewActionHandler::slotRename() { emit actionBeingHandled(); m_currentView->renameSelectedItems(); } void DolphinViewActionHandler::slotTrashActivated() { emit actionBeingHandled(); m_currentView->trashSelectedItems(); } void DolphinViewActionHandler::slotDeleteItems() { emit actionBeingHandled(); m_currentView->deleteSelectedItems(); } void DolphinViewActionHandler::togglePreview(bool show) { emit actionBeingHandled(); m_currentView->setPreviewsShown(show); } void DolphinViewActionHandler::slotPreviewsShownChanged(bool shown) { Q_UNUSED(shown); // It is not enough to update the 'Show Preview' action, also // the 'Zoom In' and 'Zoom Out' actions must be adapted. updateViewActions(); } QString DolphinViewActionHandler::currentViewModeActionName() const { switch (m_currentView->mode()) { case DolphinView::IconsView: return QStringLiteral("icons"); case DolphinView::DetailsView: return QStringLiteral("details"); case DolphinView::CompactView: return QStringLiteral("compact"); default: Q_ASSERT(false); break; } return QString(); // can't happen } KActionCollection* DolphinViewActionHandler::actionCollection() { return m_actionCollection; } void DolphinViewActionHandler::updateViewActions() { QAction* viewModeAction = m_actionCollection->action(currentViewModeActionName()); if (viewModeAction) { viewModeAction->setChecked(true); QAction* viewModeMenu = m_actionCollection->action(QStringLiteral("view_mode")); viewModeMenu->setIcon(viewModeAction->icon()); } QAction* showPreviewAction = m_actionCollection->action(QStringLiteral("show_preview")); showPreviewAction->setChecked(m_currentView->previewsShown()); slotSortOrderChanged(m_currentView->sortOrder()); slotSortFoldersFirstChanged(m_currentView->sortFoldersFirst()); slotVisibleRolesChanged(m_currentView->visibleRoles(), QList()); slotGroupedSortingChanged(m_currentView->groupedSorting()); slotSortRoleChanged(m_currentView->sortRole()); slotZoomLevelChanged(m_currentView->zoomLevel(), -1); // Updates the "show_hidden_files" action state and icon slotHiddenFilesShownChanged(m_currentView->hiddenFilesShown()); } void DolphinViewActionHandler::zoomIn() { const int level = m_currentView->zoomLevel(); m_currentView->setZoomLevel(level + 1); updateViewActions(); } void DolphinViewActionHandler::zoomOut() { const int level = m_currentView->zoomLevel(); m_currentView->setZoomLevel(level - 1); updateViewActions(); } void DolphinViewActionHandler::toggleSortOrder() { const Qt::SortOrder order = (m_currentView->sortOrder() == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder; m_currentView->setSortOrder(order); } void DolphinViewActionHandler::toggleSortFoldersFirst() { const bool sortFirst = m_currentView->sortFoldersFirst(); m_currentView->setSortFoldersFirst(!sortFirst); } void DolphinViewActionHandler::slotSortOrderChanged(Qt::SortOrder order) { QAction* descending = m_actionCollection->action(QStringLiteral("descending")); const bool sortDescending = (order == Qt::DescendingOrder); descending->setChecked(sortDescending); } void DolphinViewActionHandler::slotSortFoldersFirstChanged(bool foldersFirst) { m_actionCollection->action(QStringLiteral("folders_first"))->setChecked(foldersFirst); } void DolphinViewActionHandler::toggleVisibleRole(QAction* action) { emit actionBeingHandled(); const QByteArray toggledRole = action->data().toByteArray(); QList roles = m_currentView->visibleRoles(); const bool show = action->isChecked(); const int index = roles.indexOf(toggledRole); const bool containsInfo = (index >= 0); if (show && !containsInfo) { roles.append(toggledRole); m_currentView->setVisibleRoles(roles); } else if (!show && containsInfo) { roles.removeAt(index); m_currentView->setVisibleRoles(roles); Q_ASSERT(roles.indexOf(toggledRole) < 0); } } void DolphinViewActionHandler::slotVisibleRolesChanged(const QList& current, const QList& previous) { Q_UNUSED(previous); const QSet checkedRoles = current.toSet(); QHashIterator it(m_visibleRoles); while (it.hasNext()) { it.next(); const QByteArray& role = it.key(); KToggleAction* action = it.value(); action->setChecked(checkedRoles.contains(role)); } } void DolphinViewActionHandler::toggleGroupedSorting(bool grouped) { m_currentView->setGroupedSorting(grouped); } void DolphinViewActionHandler::slotGroupedSortingChanged(bool groupedSorting) { QAction* showInGroupsAction = m_actionCollection->action(QStringLiteral("show_in_groups")); showInGroupsAction->setChecked(groupedSorting); } void DolphinViewActionHandler::toggleShowHiddenFiles(bool show) { emit actionBeingHandled(); m_currentView->setHiddenFilesShown(show); } void DolphinViewActionHandler::slotHiddenFilesShownChanged(bool shown) { QAction* showHiddenFilesAction = m_actionCollection->action(QStringLiteral("show_hidden_files")); showHiddenFilesAction->setChecked(shown); // #374508: don't overwrite custom icons. const QString iconName = showHiddenFilesAction->icon().name(); if (!iconName.isEmpty() && iconName != QLatin1String("visibility") && iconName != QLatin1String("hint")) { return; } showHiddenFilesAction->setIcon(QIcon::fromTheme(shown ? QStringLiteral("visibility") : QStringLiteral("hint"))); } void DolphinViewActionHandler::slotWriteStateChanged(bool isFolderWritable) { m_actionCollection->action(QStringLiteral("create_dir"))->setEnabled(isFolderWritable && KProtocolManager::supportsMakeDir(currentView()->url())); } KToggleAction* DolphinViewActionHandler::iconsModeAction() { KToggleAction* iconsView = m_actionCollection->add(QStringLiteral("icons")); iconsView->setText(i18nc("@action:inmenu View Mode", "Icons")); iconsView->setToolTip(i18nc("@info", "Icons view mode")); m_actionCollection->setDefaultShortcut(iconsView, Qt::CTRL + Qt::Key_1); iconsView->setIcon(QIcon::fromTheme(QStringLiteral("view-list-icons"))); iconsView->setData(QVariant::fromValue(DolphinView::IconsView)); return iconsView; } KToggleAction* DolphinViewActionHandler::compactModeAction() { KToggleAction* iconsView = m_actionCollection->add(QStringLiteral("compact")); iconsView->setText(i18nc("@action:inmenu View Mode", "Compact")); iconsView->setToolTip(i18nc("@info", "Compact view mode")); m_actionCollection->setDefaultShortcut(iconsView, Qt::CTRL + Qt::Key_2); iconsView->setIcon(QIcon::fromTheme(QStringLiteral("view-list-details"))); // TODO: discuss with Oxygen-team the wrong (?) name iconsView->setData(QVariant::fromValue(DolphinView::CompactView)); return iconsView; } KToggleAction* DolphinViewActionHandler::detailsModeAction() { KToggleAction* detailsView = m_actionCollection->add(QStringLiteral("details")); detailsView->setText(i18nc("@action:inmenu View Mode", "Details")); detailsView->setToolTip(i18nc("@info", "Details view mode")); m_actionCollection->setDefaultShortcut(detailsView, Qt::CTRL + Qt::Key_3); detailsView->setIcon(QIcon::fromTheme(QStringLiteral("view-list-tree"))); detailsView->setData(QVariant::fromValue(DolphinView::DetailsView)); return detailsView; } void DolphinViewActionHandler::slotSortRoleChanged(const QByteArray& role) { KToggleAction* action = m_sortByActions.value(role); if (action) { action->setChecked(true); if (!action->icon().isNull()) { QAction* sortByMenu = m_actionCollection->action(QStringLiteral("sort")); sortByMenu->setIcon(action->icon()); } } } void DolphinViewActionHandler::slotZoomLevelChanged(int current, int previous) { Q_UNUSED(previous); QAction* zoomInAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomIn)); if (zoomInAction) { zoomInAction->setEnabled(current < ZoomLevelInfo::maximumLevel()); } QAction* zoomOutAction = m_actionCollection->action(KStandardAction::name(KStandardAction::ZoomOut)); if (zoomOutAction) { zoomOutAction->setEnabled(current > ZoomLevelInfo::minimumLevel()); } } void DolphinViewActionHandler::slotSortTriggered(QAction* action) { // The radiobuttons of the "Sort By"-menu are split between the main-menu // and several sub-menus. Because of this they don't have a common // action-group that assures an exclusive toggle-state between the main-menu // actions and the sub-menu-actions. If an action gets checked, it must // be assured that all other actions get unchecked. QAction* sortByMenu = m_actionCollection->action(QStringLiteral("sort")); foreach (QAction* groupAction, sortByMenu->menu()->actions()) { KActionMenu* actionMenu = qobject_cast(groupAction); if (actionMenu) { foreach (QAction* subAction, actionMenu->menu()->actions()) { subAction->setChecked(false); } } else if (groupAction->actionGroup()) { groupAction->setChecked(false); } } action->setChecked(true); // Apply the activated sort-role to the view const QByteArray role = action->data().toByteArray(); m_currentView->setSortRole(role); } void DolphinViewActionHandler::slotAdjustViewProperties() { emit actionBeingHandled(); QPointer dialog = new ViewPropertiesDialog(m_currentView); dialog->exec(); delete dialog; } void DolphinViewActionHandler::slotProperties() { KPropertiesDialog* dialog = nullptr; const KFileItemList list = m_currentView->selectedItems(); if (list.isEmpty()) { const QUrl url = m_currentView->url(); dialog = new KPropertiesDialog(url, m_currentView); } else { dialog = new KPropertiesDialog(list, m_currentView); } dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); dialog->raise(); dialog->activateWindow(); } diff --git a/src/views/dolphinviewactionhandler.h b/src/views/dolphinviewactionhandler.h index 537adb4da..001a93d78 100644 --- a/src/views/dolphinviewactionhandler.h +++ b/src/views/dolphinviewactionhandler.h @@ -1,259 +1,259 @@ /*************************************************************************** * Copyright (C) 2008 by David Faure * * Copyright (C) 2012 by Peter Penz * * * * 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 DOLPHINVIEWACTIONHANDLER_H #define DOLPHINVIEWACTIONHANDLER_H #include "dolphin_export.h" #include "views/dolphinview.h" #include class KToggleAction; class QAction; class QActionGroup; class DolphinView; class KActionCollection; /** * @short Handles all actions for DolphinView * * The action handler owns all the actions and slots related to DolphinView, - * but can the view that is acts upon can be switched to another one + * but the view that it acts upon can be switched to another one * (this is used in the case of split views). * * The purpose of this class is also to share this code between DolphinMainWindow * and DolphinPart. * * @see DolphinView * @see DolphinMainWindow * @see DolphinPart */ class DOLPHIN_EXPORT DolphinViewActionHandler : public QObject { Q_OBJECT public: explicit DolphinViewActionHandler(KActionCollection* collection, QObject* parent); /** * Sets the view that this action handler should work on. */ void setCurrentView(DolphinView* view); /** * Returns the view that this action handler should work on. */ DolphinView* currentView(); /** * Returns the name of the action for the current viewmode */ QString currentViewModeActionName() const; /** * Returns m_actionCollection */ KActionCollection* actionCollection(); public Q_SLOTS: /** * Update all actions in the 'View' menu, i.e. those that depend on the * settings in the current view. */ void updateViewActions(); Q_SIGNALS: /** * Emitted by DolphinViewActionHandler when the user triggered an action. * This is only used for clearing the statusbar in DolphinMainWindow. */ void actionBeingHandled(); /** * Emitted if the user requested creating a new directory by the F10 key. * The receiver of the signal (DolphinMainWindow or DolphinPart) invokes * the method createDirectory of their KNewFileMenu instance. */ void createDirectoryTriggered(); private Q_SLOTS: /** * Emitted when the user requested a change of view mode */ void slotViewModeActionTriggered(QAction*); /** * Let the user input a name for the selected item(s) and trigger * a renaming afterwards. */ void slotRename(); /** * Moves the selected items of the active view to the trash. * This methods adds "shift means del" handling. */ void slotTrashActivated(); /** * Deletes the selected items of the active view. */ void slotDeleteItems(); /** * Switches between showing a preview of the file content and showing the icon. */ void togglePreview(bool); /** Updates the state of the 'Show preview' menu action. */ void slotPreviewsShownChanged(bool shown); /** Increases the size of the current set view mode. */ void zoomIn(); /** Decreases the size of the current set view mode. */ void zoomOut(); /** Switches between an ascending and descending sorting order. */ void toggleSortOrder(); /** Switches between a separate sorting and a mixed sorting of files and folders. */ void toggleSortFoldersFirst(); /** * Updates the state of the 'Sort Ascending/Descending' action. */ void slotSortOrderChanged(Qt::SortOrder order); /** * Updates the state of the 'Sort Folders First' action. */ void slotSortFoldersFirstChanged(bool foldersFirst); /** * Updates the state of the 'Sort by' actions. */ void slotSortRoleChanged(const QByteArray& role); /** * Updates the state of the 'Zoom In' and 'Zoom Out' actions. */ void slotZoomLevelChanged(int current, int previous); /** * Switches on or off the displaying of additional information * as specified by \a action. */ void toggleVisibleRole(QAction* action); /** * Changes the sorting of the current view. */ void slotSortTriggered(QAction*); /** * Updates the state of the 'Additional Information' actions. */ void slotVisibleRolesChanged(const QList& current, const QList& previous); /** * Switches between sorting by groups or not. */ void toggleGroupedSorting(bool); /** * Updates the state of the 'Categorized sorting' menu action. */ void slotGroupedSortingChanged(bool sortCategorized); /** * Switches between showing and hiding of hidden marked files */ void toggleShowHiddenFiles(bool); /** * Updates the state of the 'Show hidden files' menu action. */ void slotHiddenFilesShownChanged(bool shown); /** * Updates the state of the 'Create Folder...' action. */ void slotWriteStateChanged(bool isFolderWritable); /** * Opens the view properties dialog, which allows to modify the properties * of the currently active view. */ void slotAdjustViewProperties(); /** * Connected to the "properties" action. * Opens the properties dialog for the selected items of the * active view. The properties dialog shows information * like name, size and permissions. */ void slotProperties(); private: /** * Create all the actions. * This is called only once (by the constructor) */ void createActions(); /** * Creates an action-group out of all roles from KFileItemModel. * Dependent on the group-prefix either a radiobutton-group is * created for sorting (prefix is "sort_by_") or a checkbox-group * is created for additional information (prefix is "show_"). * The changes of actions are reported to slotSortTriggered() or * toggleAdditionalInfo(). */ QActionGroup* createFileItemRolesActionGroup(const QString& groupPrefix); /** * Returns the "switch to icons mode" action. * Helper method for createActions(); */ KToggleAction* iconsModeAction(); /** * Returns the "switch to compact mode" action. * Helper method for createActions(); */ KToggleAction* compactModeAction(); /** * Returns the "switch to details mode" action. * Helper method for createActions(); */ KToggleAction* detailsModeAction(); KActionCollection* m_actionCollection; DolphinView* m_currentView; QHash m_sortByActions; QHash m_visibleRoles; }; #endif /* DOLPHINVIEWACTIONHANDLER_H */