]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphincontextmenu.cpp
Merge branch 'release/21.04'
[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 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 void DolphinContextMenu::childEvent(QChildEvent* event)
116 {
117 if(event->added()) {
118 event->child()->installEventFilter(this);
119 }
120 QMenu::childEvent(event);
121 }
122
123 bool DolphinContextMenu::eventFilter(QObject* dest, QEvent* event)
124 {
125 if(event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
126 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
127 if(m_removeAction && keyEvent->key() == Qt::Key_Shift) {
128 if(event->type() == QEvent::KeyPress) {
129 m_removeAction->update(DolphinRemoveAction::ShiftState::Pressed);
130 } else {
131 m_removeAction->update(DolphinRemoveAction::ShiftState::Released);
132 }
133 return true;
134 }
135 }
136 return QMenu::eventFilter(dest, event);
137 }
138
139 void DolphinContextMenu::openTrashContextMenu()
140 {
141 Q_ASSERT(m_context & TrashContext);
142
143 QAction* emptyTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"), this);
144 emptyTrashAction->setEnabled(!Trash::isEmpty());
145 addAction(emptyTrashAction);
146
147 addCustomActions();
148
149 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
150 addAction(propertiesAction);
151
152 addShowMenuBarAction();
153
154 if (exec(m_pos) == emptyTrashAction) {
155 Trash::empty(m_mainWindow);
156 }
157 }
158
159 void DolphinContextMenu::openTrashItemContextMenu()
160 {
161 Q_ASSERT(m_context & TrashContext);
162 Q_ASSERT(m_context & ItemContext);
163
164 QAction* restoreAction = new QAction(QIcon::fromTheme("restoration"), i18nc("@action:inmenu", "Restore"), m_mainWindow);
165 addAction(restoreAction);
166
167 QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile));
168 addAction(deleteAction);
169
170 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
171 addAction(propertiesAction);
172
173 if (exec(m_pos) == restoreAction) {
174 QList<QUrl> selectedUrls;
175 selectedUrls.reserve(m_selectedItems.count());
176 for (const KFileItem &item : qAsConst(m_selectedItems)) {
177 selectedUrls.append(item.url());
178 }
179
180 KIO::RestoreJob *job = KIO::restoreFromTrash(selectedUrls);
181 KJobWidgets::setWindow(job, m_mainWindow);
182 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
183 }
184 }
185
186 void DolphinContextMenu::addDirectoryItemContextMenu(KFileItemActions &fileItemActions)
187 {
188 // insert 'Open in new window' and 'Open in new tab' entries
189 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
190 if (ContextMenuSettings::showOpenInNewTab()) {
191 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
192 }
193 if (ContextMenuSettings::showOpenInNewWindow()) {
194 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
195 }
196
197 // Insert 'Open With' entries
198 addOpenWithActions(fileItemActions);
199
200 // set up 'Create New' menu
201 DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow);
202 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
203 newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
204 newFileMenu->checkUpToDate();
205 newFileMenu->setPopupFiles(QList<QUrl>() << m_fileInfo.url());
206 newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
207 connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
208 connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
209
210 QMenu* menu = newFileMenu->menu();
211 menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
212 menu->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
213 addMenu(menu);
214
215 addSeparator();
216 }
217
218 void DolphinContextMenu::openItemContextMenu()
219 {
220 Q_ASSERT(!m_fileInfo.isNull());
221
222 QAction* openParentAction = nullptr;
223 QAction* openParentInNewWindowAction = nullptr;
224 QAction* openParentInNewTabAction = nullptr;
225 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
226
227 KFileItemActions fileItemActions;
228 fileItemActions.setParentWidget(m_mainWindow);
229 fileItemActions.setItemListProperties(selectedItemsProps);
230
231 if (m_selectedItems.count() == 1) {
232 // single files
233 if (m_fileInfo.isDir()) {
234 addDirectoryItemContextMenu(fileItemActions);
235 } else if (m_context & TimelineContext || m_context & SearchContext) {
236 addOpenWithActions(fileItemActions);
237
238 openParentAction = new QAction(QIcon::fromTheme(QStringLiteral("document-open-folder")),
239 i18nc("@action:inmenu",
240 "Open Path"),
241 this);
242 addAction(openParentAction);
243
244 openParentInNewWindowAction = new QAction(QIcon::fromTheme(QStringLiteral("window-new")),
245 i18nc("@action:inmenu",
246 "Open Path in New Window"),
247 this);
248 addAction(openParentInNewWindowAction);
249
250 openParentInNewTabAction = new QAction(QIcon::fromTheme(QStringLiteral("tab-new")),
251 i18nc("@action:inmenu",
252 "Open Path in New Tab"),
253 this);
254 addAction(openParentInNewTabAction);
255
256 addSeparator();
257 } else {
258 // Insert 'Open With" entries
259 addOpenWithActions(fileItemActions);
260 }
261 if (m_fileInfo.isLink()) {
262 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("show_target")));
263 addSeparator();
264 }
265 } else {
266 // multiple files
267 bool selectionHasOnlyDirs = true;
268 for (const auto &item : qAsConst(m_selectedItems)) {
269 const QUrl& url = DolphinView::openItemAsFolderUrl(item);
270 if (url.isEmpty()) {
271 selectionHasOnlyDirs = false;
272 break;
273 }
274 }
275
276 if (selectionHasOnlyDirs && ContextMenuSettings::showOpenInNewTab()) {
277 // insert 'Open in new tab' entry
278 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tabs")));
279 }
280 // Insert 'Open With" entries
281 addOpenWithActions(fileItemActions);
282 }
283
284 insertDefaultItemActions(selectedItemsProps);
285
286 addAdditionalActions(fileItemActions, selectedItemsProps);
287
288 // insert 'Copy To' and 'Move To' sub menus
289 if (ContextMenuSettings::showCopyMoveMenu()) {
290 m_copyToMenu.setUrls(m_selectedItems.urlList());
291 m_copyToMenu.setReadOnly(!selectedItemsProps.supportsWriting());
292 m_copyToMenu.setAutoErrorHandlingEnabled(true);
293 m_copyToMenu.addActionsTo(this);
294 }
295
296 // insert 'Properties...' entry
297 addSeparator();
298 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
299 addAction(propertiesAction);
300
301 QAction* activatedAction = exec(m_pos);
302 if (activatedAction) {
303 if (activatedAction == openParentAction) {
304 m_command = OpenParentFolder;
305 } else if (activatedAction == openParentInNewWindowAction) {
306 m_command = OpenParentFolderInNewWindow;
307 } else if (activatedAction == openParentInNewTabAction) {
308 m_command = OpenParentFolderInNewTab;
309 }
310 }
311 }
312
313 void DolphinContextMenu::openViewportContextMenu()
314 {
315 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
316
317 const KFileItemListProperties baseUrlProperties(KFileItemList() << baseFileItem());
318 KFileItemActions fileItemActions;
319 fileItemActions.setParentWidget(m_mainWindow);
320 fileItemActions.setItemListProperties(baseUrlProperties);
321
322 // Set up and insert 'Create New' menu
323 KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu();
324 newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
325 newFileMenu->checkUpToDate();
326 newFileMenu->setPopupFiles(QList<QUrl>() << m_baseUrl);
327 addMenu(newFileMenu->menu());
328
329 // Show "open with" menu items even if the dir is empty, because there are legitimate
330 // use cases for this, such as opening an empty dir in Kate or VSCode or something
331 addOpenWithActions(fileItemActions);
332
333 QAction* pasteAction = createPasteAction();
334 if (pasteAction) {
335 addAction(pasteAction);
336 }
337
338 // Insert 'Add to Places' entry if it's not already in the places panel
339 if (ContextMenuSettings::showAddToPlaces() &&
340 !placeExists(m_mainWindow->activeViewContainer()->url())) {
341 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
342 }
343 addSeparator();
344
345 // Insert 'Sort By' and 'View Mode'
346 if (ContextMenuSettings::showSortBy()) {
347 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("sort")));
348 }
349 if (ContextMenuSettings::showViewMode()) {
350 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("view_mode")));
351 }
352 if (ContextMenuSettings::showSortBy() || ContextMenuSettings::showViewMode()) {
353 addSeparator();
354 }
355
356 addAdditionalActions(fileItemActions, baseUrlProperties);
357 addCustomActions();
358
359 addSeparator();
360
361 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
362 addAction(propertiesAction);
363
364 addShowMenuBarAction();
365
366 exec(m_pos);
367 }
368
369 void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& properties)
370 {
371 const KActionCollection* collection = m_mainWindow->actionCollection();
372
373 // Insert 'Cut', 'Copy', 'Copy Location' and 'Paste'
374 addAction(collection->action(KStandardAction::name(KStandardAction::Cut)));
375 addAction(collection->action(KStandardAction::name(KStandardAction::Copy)));
376 if (ContextMenuSettings::showCopyLocation()) {
377 QAction* copyPathAction = collection->action(QString("copy_location"));
378 copyPathAction->setEnabled(m_selectedItems.size() == 1);
379 addAction(copyPathAction);
380 }
381 QAction* pasteAction = createPasteAction();
382 if (pasteAction) {
383 addAction(pasteAction);
384 }
385
386 // Insert 'Duplicate Here'
387 if (ContextMenuSettings::showDuplicateHere()) {
388 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("duplicate")));
389 }
390
391 // Insert 'Rename'
392 addAction(collection->action(KStandardAction::name(KStandardAction::RenameFile)));
393
394 // Insert 'Add to Places' entry if appropriate
395 if (ContextMenuSettings::showAddToPlaces() &&
396 m_selectedItems.count() == 1 &&
397 m_fileInfo.isDir() &&
398 !placeExists(m_fileInfo.url())) {
399 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
400 }
401
402 addSeparator();
403
404 // Insert 'Move to Trash' and/or 'Delete'
405 const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
406 !properties.isLocal());
407 const bool showMoveToTrashAction = (properties.isLocal() &&
408 properties.supportsMoving());
409
410 if (showDeleteAction && showMoveToTrashAction) {
411 delete m_removeAction;
412 m_removeAction = nullptr;
413 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)));
414 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
415 } else if (showDeleteAction && !showMoveToTrashAction) {
416 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
417 } else {
418 if (!m_removeAction) {
419 m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
420 }
421 addAction(m_removeAction);
422 m_removeAction->update();
423 }
424 }
425
426 void DolphinContextMenu::addShowMenuBarAction()
427 {
428 const KActionCollection* ac = m_mainWindow->actionCollection();
429 QAction* showMenuBar = ac->action(KStandardAction::name(KStandardAction::ShowMenubar));
430 if (!m_mainWindow->menuBar()->isVisible() && !m_mainWindow->toolBar()->isVisible()) {
431 addSeparator();
432 addAction(showMenuBar);
433 }
434 }
435
436 bool DolphinContextMenu::placeExists(const QUrl& url) const
437 {
438 const KFilePlacesModel* placesModel = DolphinPlacesModelSingleton::instance().placesModel();
439
440 const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, url, 1, Qt::MatchExactly);
441
442 return !matchedPlaces.isEmpty();
443 }
444
445 QAction* DolphinContextMenu::createPasteAction()
446 {
447 QAction* action = nullptr;
448 KFileItem destItem;
449 if (!m_fileInfo.isNull() && m_selectedItems.count() <= 1) {
450 destItem = m_fileInfo;
451 } else {
452 destItem = baseFileItem();
453 }
454
455 if (!destItem.isNull() && destItem.isDir()) {
456 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
457 bool canPaste;
458 const QString text = KIO::pasteActionText(mimeData, &canPaste, destItem);
459 if (canPaste) {
460 if (destItem == m_fileInfo) {
461 // if paste destination is a selected folder
462 action = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
463 connect(action, &QAction::triggered, m_mainWindow, &DolphinMainWindow::pasteIntoFolder);
464 } else {
465 action = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
466 }
467 }
468 }
469
470 return action;
471 }
472
473 KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
474 {
475 if (!m_selectedItemsProperties) {
476 m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
477 }
478 return *m_selectedItemsProperties;
479 }
480
481 KFileItem DolphinContextMenu::baseFileItem()
482 {
483 if (!m_baseFileItem) {
484 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
485 KFileItem baseItem = view->rootItem();
486 if (baseItem.isNull() || baseItem.url() != m_baseUrl) {
487 m_baseFileItem = new KFileItem(m_baseUrl);
488 } else {
489 m_baseFileItem = new KFileItem(baseItem);
490 }
491 }
492 return *m_baseFileItem;
493 }
494
495 void DolphinContextMenu::addOpenWithActions(KFileItemActions& fileItemActions)
496 {
497 // insert 'Open With...' action or sub menu
498 fileItemActions.addOpenWithActionsTo(this, QStringLiteral("DesktopEntryName != '%1'").arg(qApp->desktopFileName()));
499 }
500
501 void DolphinContextMenu::addCustomActions()
502 {
503 addActions(m_customActions);
504 }
505
506 void DolphinContextMenu::addAdditionalActions(KFileItemActions &fileItemActions, const KFileItemListProperties &props)
507 {
508 addSeparator();
509
510 QList<QAction *> additionalActions;
511 if (props.isDirectory() && props.isLocal() && ContextMenuSettings::showOpenTerminal()) {
512 additionalActions << m_mainWindow->actionCollection()->action(QStringLiteral("open_terminal"));
513 }
514 fileItemActions.addActionsTo(this, KFileItemActions::MenuActionSource::All, additionalActions);
515
516 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
517 const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
518 if (!versionControlActions.isEmpty()) {
519 addActions(versionControlActions);
520 addSeparator();
521 }
522 }
523