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