]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphincontextmenu.cpp
Fix shift-action modifier in context menu
[dolphin.git] / src / dolphincontextmenu.cpp
1 /*
2 * SPDX-FileCopyrightText: 2006 Peter Penz (peter.penz@gmx.at) and Cvetoslav Ludmiloff
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 */
6
7 #include "dolphincontextmenu.h"
8
9 #include "dolphin_generalsettings.h"
10 #include "dolphin_contextmenusettings.h"
11 #include "dolphinmainwindow.h"
12 #include "dolphinnewfilemenu.h"
13 #include "dolphinplacesmodelsingleton.h"
14 #include "dolphinremoveaction.h"
15 #include "dolphinviewcontainer.h"
16 #include "panels/places/placesitem.h"
17 #include "panels/places/placesitemmodel.h"
18 #include "trash/dolphintrash.h"
19 #include "views/dolphinview.h"
20 #include "views/viewmodecontroller.h"
21
22 #include <KActionCollection>
23 #include <KFileItemActions>
24 #include <KFileItemListProperties>
25 #include <KIO/EmptyTrashJob>
26 #include <KIO/JobUiDelegate>
27 #include <KIO/Paste>
28 #include <KIO/RestoreJob>
29 #include <KJobWidgets>
30 #include <KLocalizedString>
31 #include <KNewFileMenu>
32 #include <KPluginMetaData>
33 #include <KService>
34 #include <KStandardAction>
35 #include <KToolBar>
36
37 #include <QApplication>
38 #include <QClipboard>
39 #include <QKeyEvent>
40 #include <QMenuBar>
41 #include <QMimeDatabase>
42
43 DolphinContextMenu::DolphinContextMenu(DolphinMainWindow* parent,
44 const QPoint& pos,
45 const KFileItem& fileInfo,
46 const QUrl& baseUrl) :
47 QMenu(parent),
48 m_pos(pos),
49 m_mainWindow(parent),
50 m_fileInfo(fileInfo),
51 m_baseUrl(baseUrl),
52 m_baseFileItem(nullptr),
53 m_selectedItems(),
54 m_selectedItemsProperties(nullptr),
55 m_context(NoContext),
56 m_copyToMenu(parent),
57 m_customActions(),
58 m_command(None),
59 m_removeAction(nullptr)
60 {
61 // The context menu either accesses the URLs of the selected items
62 // or the items itself. To increase the performance both lists are cached.
63 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
64 m_selectedItems = view->selectedItems();
65
66 QApplication::instance()->installEventFilter(this);
67 }
68
69 DolphinContextMenu::~DolphinContextMenu()
70 {
71 delete m_baseFileItem;
72 m_baseFileItem = nullptr;
73 delete m_selectedItemsProperties;
74 m_selectedItemsProperties = nullptr;
75 }
76
77 void DolphinContextMenu::setCustomActions(const QList<QAction*>& actions)
78 {
79 m_customActions = actions;
80 }
81
82 DolphinContextMenu::Command DolphinContextMenu::open()
83 {
84 // get the context information
85 const auto scheme = m_baseUrl.scheme();
86 if (scheme == QLatin1String("trash")) {
87 m_context |= TrashContext;
88 } else if (scheme.contains(QLatin1String("search"))) {
89 m_context |= SearchContext;
90 } else if (scheme.contains(QLatin1String("timeline"))) {
91 m_context |= TimelineContext;
92 }
93
94 if (!m_fileInfo.isNull() && !m_selectedItems.isEmpty()) {
95 m_context |= ItemContext;
96 // TODO: handle other use cases like devices + desktop files
97 }
98
99 // open the corresponding popup for the context
100 if (m_context & TrashContext) {
101 if (m_context & ItemContext) {
102 openTrashItemContextMenu();
103 } else {
104 openTrashContextMenu();
105 }
106 } else if (m_context & ItemContext) {
107 openItemContextMenu();
108 } else {
109 openViewportContextMenu();
110 }
111
112 return m_command;
113 }
114
115 bool DolphinContextMenu::eventFilter(QObject* object, QEvent* event)
116 {
117 Q_UNUSED(object)
118
119 if(event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
120 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
121
122 if (m_removeAction && keyEvent->key() == Qt::Key_Shift) {
123 if (event->type() == QEvent::KeyPress) {
124 m_removeAction->update(DolphinRemoveAction::ShiftState::Pressed);
125 } else {
126 m_removeAction->update(DolphinRemoveAction::ShiftState::Released);
127 }
128 }
129 }
130
131 return false;
132 }
133
134 void DolphinContextMenu::openTrashContextMenu()
135 {
136 Q_ASSERT(m_context & TrashContext);
137
138 QAction* emptyTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"), this);
139 emptyTrashAction->setEnabled(!Trash::isEmpty());
140 addAction(emptyTrashAction);
141
142 addCustomActions();
143
144 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
145 addAction(propertiesAction);
146
147 addShowMenuBarAction();
148
149 if (exec(m_pos) == emptyTrashAction) {
150 Trash::empty(m_mainWindow);
151 }
152 }
153
154 void DolphinContextMenu::openTrashItemContextMenu()
155 {
156 Q_ASSERT(m_context & TrashContext);
157 Q_ASSERT(m_context & ItemContext);
158
159 QAction* restoreAction = new QAction(QIcon::fromTheme("restoration"), i18nc("@action:inmenu", "Restore"), m_mainWindow);
160 addAction(restoreAction);
161
162 QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile));
163 addAction(deleteAction);
164
165 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
166 addAction(propertiesAction);
167
168 if (exec(m_pos) == restoreAction) {
169 QList<QUrl> selectedUrls;
170 selectedUrls.reserve(m_selectedItems.count());
171 for (const KFileItem &item : qAsConst(m_selectedItems)) {
172 selectedUrls.append(item.url());
173 }
174
175 KIO::RestoreJob *job = KIO::restoreFromTrash(selectedUrls);
176 KJobWidgets::setWindow(job, m_mainWindow);
177 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
178 }
179 }
180
181 void DolphinContextMenu::addDirectoryItemContextMenu(KFileItemActions &fileItemActions)
182 {
183 // insert 'Open in new window' and 'Open in new tab' entries
184 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
185 if (ContextMenuSettings::showOpenInNewTab()) {
186 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
187 }
188 if (ContextMenuSettings::showOpenInNewWindow()) {
189 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
190 }
191
192 // Insert 'Open With' entries
193 addOpenWithActions(fileItemActions);
194
195 // set up 'Create New' menu
196 DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow);
197 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
198 newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
199 newFileMenu->checkUpToDate();
200 newFileMenu->setPopupFiles(QList<QUrl>() << m_fileInfo.url());
201 newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
202 connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
203 connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
204
205 QMenu* menu = newFileMenu->menu();
206 menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
207 menu->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
208 addMenu(menu);
209
210 addSeparator();
211 }
212
213 void DolphinContextMenu::openItemContextMenu()
214 {
215 Q_ASSERT(!m_fileInfo.isNull());
216
217 QAction* openParentAction = nullptr;
218 QAction* openParentInNewWindowAction = nullptr;
219 QAction* openParentInNewTabAction = nullptr;
220 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
221
222 KFileItemActions fileItemActions;
223 fileItemActions.setParentWidget(m_mainWindow);
224 fileItemActions.setItemListProperties(selectedItemsProps);
225
226 if (m_selectedItems.count() == 1) {
227 // single files
228 if (m_fileInfo.isDir()) {
229 addDirectoryItemContextMenu(fileItemActions);
230 } else if (m_context & TimelineContext || m_context & SearchContext) {
231 addOpenWithActions(fileItemActions);
232
233 openParentAction = new QAction(QIcon::fromTheme(QStringLiteral("document-open-folder")),
234 i18nc("@action:inmenu",
235 "Open Path"),
236 this);
237 addAction(openParentAction);
238
239 openParentInNewWindowAction = new QAction(QIcon::fromTheme(QStringLiteral("window-new")),
240 i18nc("@action:inmenu",
241 "Open Path in New Window"),
242 this);
243 addAction(openParentInNewWindowAction);
244
245 openParentInNewTabAction = new QAction(QIcon::fromTheme(QStringLiteral("tab-new")),
246 i18nc("@action:inmenu",
247 "Open Path in New Tab"),
248 this);
249 addAction(openParentInNewTabAction);
250
251 addSeparator();
252 } else {
253 // Insert 'Open With" entries
254 addOpenWithActions(fileItemActions);
255 }
256 if (m_fileInfo.isLink()) {
257 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("show_target")));
258 addSeparator();
259 }
260 } else {
261 // multiple files
262 bool selectionHasOnlyDirs = true;
263 for (const auto &item : qAsConst(m_selectedItems)) {
264 const QUrl& url = DolphinView::openItemAsFolderUrl(item);
265 if (url.isEmpty()) {
266 selectionHasOnlyDirs = false;
267 break;
268 }
269 }
270
271 if (selectionHasOnlyDirs && ContextMenuSettings::showOpenInNewTab()) {
272 // insert 'Open in new tab' entry
273 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tabs")));
274 }
275 // Insert 'Open With" entries
276 addOpenWithActions(fileItemActions);
277 }
278
279 insertDefaultItemActions(selectedItemsProps);
280
281 addAdditionalActions(fileItemActions, selectedItemsProps);
282
283 // insert 'Copy To' and 'Move To' sub menus
284 if (ContextMenuSettings::showCopyMoveMenu()) {
285 m_copyToMenu.setUrls(m_selectedItems.urlList());
286 m_copyToMenu.setReadOnly(!selectedItemsProps.supportsWriting());
287 m_copyToMenu.setAutoErrorHandlingEnabled(true);
288 m_copyToMenu.addActionsTo(this);
289 }
290
291 // insert 'Properties...' entry
292 addSeparator();
293 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
294 addAction(propertiesAction);
295
296 QAction* activatedAction = exec(m_pos);
297 if (activatedAction) {
298 if (activatedAction == openParentAction) {
299 m_command = OpenParentFolder;
300 } else if (activatedAction == openParentInNewWindowAction) {
301 m_command = OpenParentFolderInNewWindow;
302 } else if (activatedAction == openParentInNewTabAction) {
303 m_command = OpenParentFolderInNewTab;
304 }
305 }
306 }
307
308 void DolphinContextMenu::openViewportContextMenu()
309 {
310 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
311
312 const KFileItemListProperties baseUrlProperties(KFileItemList() << baseFileItem());
313 KFileItemActions fileItemActions;
314 fileItemActions.setParentWidget(m_mainWindow);
315 fileItemActions.setItemListProperties(baseUrlProperties);
316
317 // Set up and insert 'Create New' menu
318 KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu();
319 newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
320 newFileMenu->checkUpToDate();
321 newFileMenu->setPopupFiles(QList<QUrl>() << m_baseUrl);
322 addMenu(newFileMenu->menu());
323
324 // Show "open with" menu items even if the dir is empty, because there are legitimate
325 // use cases for this, such as opening an empty dir in Kate or VSCode or something
326 addOpenWithActions(fileItemActions);
327
328 QAction* pasteAction = createPasteAction();
329 if (pasteAction) {
330 addAction(pasteAction);
331 }
332
333 // Insert 'Add to Places' entry if it's not already in the places panel
334 if (ContextMenuSettings::showAddToPlaces() &&
335 !placeExists(m_mainWindow->activeViewContainer()->url())) {
336 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
337 }
338 addSeparator();
339
340 // Insert 'Sort By' and 'View Mode'
341 if (ContextMenuSettings::showSortBy()) {
342 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("sort")));
343 }
344 if (ContextMenuSettings::showViewMode()) {
345 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("view_mode")));
346 }
347 if (ContextMenuSettings::showSortBy() || ContextMenuSettings::showViewMode()) {
348 addSeparator();
349 }
350
351 addAdditionalActions(fileItemActions, baseUrlProperties);
352 addCustomActions();
353
354 addSeparator();
355
356 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
357 addAction(propertiesAction);
358
359 addShowMenuBarAction();
360
361 exec(m_pos);
362 }
363
364 void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& properties)
365 {
366 const KActionCollection* collection = m_mainWindow->actionCollection();
367
368 // Insert 'Cut', 'Copy', 'Copy Location' and 'Paste'
369 addAction(collection->action(KStandardAction::name(KStandardAction::Cut)));
370 addAction(collection->action(KStandardAction::name(KStandardAction::Copy)));
371 if (ContextMenuSettings::showCopyLocation()) {
372 QAction* copyPathAction = collection->action(QString("copy_location"));
373 copyPathAction->setEnabled(m_selectedItems.size() == 1);
374 addAction(copyPathAction);
375 }
376 QAction* pasteAction = createPasteAction();
377 if (pasteAction) {
378 addAction(pasteAction);
379 }
380
381 // Insert 'Duplicate Here'
382 if (ContextMenuSettings::showDuplicateHere()) {
383 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("duplicate")));
384 }
385
386 // Insert 'Rename'
387 addAction(collection->action(KStandardAction::name(KStandardAction::RenameFile)));
388
389 // Insert 'Add to Places' entry if appropriate
390 if (ContextMenuSettings::showAddToPlaces() &&
391 m_selectedItems.count() == 1 &&
392 m_fileInfo.isDir() &&
393 !placeExists(m_fileInfo.url())) {
394 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
395 }
396
397 addSeparator();
398
399 // Insert 'Move to Trash' and/or 'Delete'
400 const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
401 !properties.isLocal());
402 const bool showMoveToTrashAction = (properties.isLocal() &&
403 properties.supportsMoving());
404
405 if (showDeleteAction && showMoveToTrashAction) {
406 delete m_removeAction;
407 m_removeAction = nullptr;
408 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)));
409 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
410 } else if (showDeleteAction && !showMoveToTrashAction) {
411 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
412 } else {
413 if (!m_removeAction) {
414 m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
415 }
416 addAction(m_removeAction);
417 m_removeAction->update();
418 }
419 }
420
421 void DolphinContextMenu::addShowMenuBarAction()
422 {
423 const KActionCollection* ac = m_mainWindow->actionCollection();
424 QAction* showMenuBar = ac->action(KStandardAction::name(KStandardAction::ShowMenubar));
425 if (!m_mainWindow->menuBar()->isVisible() && !m_mainWindow->toolBar()->isVisible()) {
426 addSeparator();
427 addAction(showMenuBar);
428 }
429 }
430
431 bool DolphinContextMenu::placeExists(const QUrl& url) const
432 {
433 const KFilePlacesModel* placesModel = DolphinPlacesModelSingleton::instance().placesModel();
434
435 const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, url, 1, Qt::MatchExactly);
436
437 return !matchedPlaces.isEmpty();
438 }
439
440 QAction* DolphinContextMenu::createPasteAction()
441 {
442 QAction* action = nullptr;
443 KFileItem destItem;
444 if (!m_fileInfo.isNull() && m_selectedItems.count() <= 1) {
445 destItem = m_fileInfo;
446 } else {
447 destItem = baseFileItem();
448 }
449
450 if (!destItem.isNull() && destItem.isDir()) {
451 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
452 bool canPaste;
453 const QString text = KIO::pasteActionText(mimeData, &canPaste, destItem);
454 if (canPaste) {
455 if (destItem == m_fileInfo) {
456 // if paste destination is a selected folder
457 action = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
458 connect(action, &QAction::triggered, m_mainWindow, &DolphinMainWindow::pasteIntoFolder);
459 } else {
460 action = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
461 }
462 }
463 }
464
465 return action;
466 }
467
468 KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
469 {
470 if (!m_selectedItemsProperties) {
471 m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
472 }
473 return *m_selectedItemsProperties;
474 }
475
476 KFileItem DolphinContextMenu::baseFileItem()
477 {
478 if (!m_baseFileItem) {
479 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
480 KFileItem baseItem = view->rootItem();
481 if (baseItem.isNull() || baseItem.url() != m_baseUrl) {
482 m_baseFileItem = new KFileItem(m_baseUrl);
483 } else {
484 m_baseFileItem = new KFileItem(baseItem);
485 }
486 }
487 return *m_baseFileItem;
488 }
489
490 void DolphinContextMenu::addOpenWithActions(KFileItemActions& fileItemActions)
491 {
492 // insert 'Open With...' action or sub menu
493 fileItemActions.addOpenWithActionsTo(this, QStringLiteral("DesktopEntryName != '%1'").arg(qApp->desktopFileName()));
494 }
495
496 void DolphinContextMenu::addCustomActions()
497 {
498 addActions(m_customActions);
499 }
500
501 void DolphinContextMenu::addAdditionalActions(KFileItemActions &fileItemActions, const KFileItemListProperties &props)
502 {
503 addSeparator();
504
505 QList<QAction *> additionalActions;
506 if (props.isDirectory() && props.isLocal()) {
507 additionalActions << m_mainWindow->actionCollection()->action(QStringLiteral("open_terminal"));
508 }
509 fileItemActions.addActionsTo(this, KFileItemActions::MenuActionSource::All, additionalActions);
510
511 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
512 const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
513 if (!versionControlActions.isEmpty()) {
514 addActions(versionControlActions);
515 addSeparator();
516 }
517 }
518