]> 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 Q_ASSERT(m_context == NoContext);
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
190 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
191
192 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
193 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
194
195 // Insert 'Open With' entries
196 addOpenWithActions(fileItemActions);
197
198 // set up 'Create New' menu
199 DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow);
200 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
201 newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
202 newFileMenu->checkUpToDate();
203 newFileMenu->setPopupFiles(QList<QUrl>() << m_fileInfo.url());
204 newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
205 connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
206 connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
207
208 QMenu* menu = newFileMenu->menu();
209 menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
210 menu->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
211 menu->setParent(this, Qt::Popup);
212 addMenu(menu);
213
214 addSeparator();
215 }
216
217 void DolphinContextMenu::openItemContextMenu()
218 {
219 Q_ASSERT(!m_fileInfo.isNull());
220
221 QAction* openParentAction = nullptr;
222 QAction* openParentInNewWindowAction = nullptr;
223 QAction* openParentInNewTabAction = nullptr;
224 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
225
226 KFileItemActions fileItemActions;
227 fileItemActions.setParentWidget(m_mainWindow);
228 fileItemActions.setItemListProperties(selectedItemsProps);
229
230 if (m_selectedItems.count() == 1) {
231 // single files
232 if (m_fileInfo.isDir()) {
233 addDirectoryItemContextMenu(fileItemActions);
234 } else if (m_context & TimelineContext || m_context & SearchContext) {
235 addOpenWithActions(fileItemActions);
236
237 openParentAction = new QAction(QIcon::fromTheme(QStringLiteral("document-open-folder")),
238 i18nc("@action:inmenu",
239 "Open Path"),
240 this);
241 addAction(openParentAction);
242
243 openParentInNewWindowAction = new QAction(QIcon::fromTheme(QStringLiteral("window-new")),
244 i18nc("@action:inmenu",
245 "Open Path in New Window"),
246 this);
247 addAction(openParentInNewWindowAction);
248
249 openParentInNewTabAction = new QAction(QIcon::fromTheme(QStringLiteral("tab-new")),
250 i18nc("@action:inmenu",
251 "Open Path in New Tab"),
252 this);
253 addAction(openParentInNewTabAction);
254
255 addSeparator();
256 } else {
257 // Insert 'Open With" entries
258 addOpenWithActions(fileItemActions);
259 }
260 if (m_fileInfo.isLink()) {
261 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("show_target")));
262 addSeparator();
263 }
264 } else {
265 // multiple files
266 bool selectionHasOnlyDirs = true;
267 for (const auto &item : qAsConst(m_selectedItems)) {
268 const QUrl& url = DolphinView::openItemAsFolderUrl(item);
269 if (url.isEmpty()) {
270 selectionHasOnlyDirs = false;
271 break;
272 }
273 }
274
275 if (selectionHasOnlyDirs) {
276 // insert 'Open in new tab' entry
277 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tabs")));
278 }
279 // Insert 'Open With" entries
280 addOpenWithActions(fileItemActions);
281 }
282
283 insertDefaultItemActions(selectedItemsProps);
284
285 addAdditionalActions(fileItemActions, selectedItemsProps);
286
287 // insert 'Copy To' and 'Move To' sub menus
288 if (GeneralSettings::showCopyMoveMenu()) {
289 m_copyToMenu.setUrls(m_selectedItems.urlList());
290 m_copyToMenu.setReadOnly(!selectedItemsProps.supportsWriting());
291 m_copyToMenu.setAutoErrorHandlingEnabled(true);
292 m_copyToMenu.addActionsTo(this);
293 }
294
295 // insert 'Properties...' entry
296 addSeparator();
297 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
298 addAction(propertiesAction);
299
300 QAction* activatedAction = exec(m_pos);
301 if (activatedAction) {
302 if (activatedAction == openParentAction) {
303 m_command = OpenParentFolder;
304 } else if (activatedAction == openParentInNewWindowAction) {
305 m_command = OpenParentFolderInNewWindow;
306 } else if (activatedAction == openParentInNewTabAction) {
307 m_command = OpenParentFolderInNewTab;
308 }
309 }
310 }
311
312 void DolphinContextMenu::openViewportContextMenu()
313 {
314 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
315
316 const KFileItemListProperties baseUrlProperties(KFileItemList() << baseFileItem());
317 KFileItemActions fileItemActions;
318 fileItemActions.setParentWidget(m_mainWindow);
319 fileItemActions.setItemListProperties(baseUrlProperties);
320
321 // Set up and insert 'Create New' menu
322 KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu();
323 newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
324 newFileMenu->checkUpToDate();
325 newFileMenu->setPopupFiles(QList<QUrl>() << m_baseUrl);
326 addMenu(newFileMenu->menu());
327
328 // Show "open with" menu items even if the dir is empty, because there are legitimate
329 // use cases for this, such as opening an empty dir in Kate or VSCode or something
330 addOpenWithActions(fileItemActions);
331
332 QAction* pasteAction = createPasteAction();
333 if (pasteAction) {
334 addAction(pasteAction);
335 }
336
337 // Insert 'Add to Places' entry if it's not already in the places panel
338 if (!placeExists(m_mainWindow->activeViewContainer()->url())) {
339 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
340 }
341 addSeparator();
342
343 // Insert 'Sort By' and 'View Mode'
344 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("sort")));
345 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("view_mode")));
346
347 addAdditionalActions(fileItemActions, baseUrlProperties);
348 addCustomActions();
349
350 addSeparator();
351
352 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
353 addAction(propertiesAction);
354
355 addShowMenuBarAction();
356
357 exec(m_pos);
358 }
359
360 void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& properties)
361 {
362 const KActionCollection* collection = m_mainWindow->actionCollection();
363
364 // Insert 'Cut', 'Copy', 'Copy Location' and 'Paste'
365 addAction(collection->action(KStandardAction::name(KStandardAction::Cut)));
366 addAction(collection->action(KStandardAction::name(KStandardAction::Copy)));
367 QAction* copyPathAction = collection->action(QString("copy_location"));
368 copyPathAction->setEnabled(m_selectedItems.size() == 1);
369 addAction(copyPathAction);
370 QAction* pasteAction = createPasteAction();
371 if (pasteAction) {
372 addAction(pasteAction);
373 }
374 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("duplicate")));
375
376 // Insert 'Rename'
377 addAction(collection->action(KStandardAction::name(KStandardAction::RenameFile)));
378
379 // insert 'Add to Places' entry if appropriate
380 if (m_selectedItems.count() == 1) {
381 if (m_fileInfo.isDir()) {
382 if (!placeExists(m_fileInfo.url())) {
383 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
384 }
385 }
386 }
387
388 addSeparator();
389
390 // Insert 'Move to Trash' and/or 'Delete'
391 const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
392 !properties.isLocal());
393 const bool showMoveToTrashAction = (properties.isLocal() &&
394 properties.supportsMoving());
395
396 if (showDeleteAction && showMoveToTrashAction) {
397 delete m_removeAction;
398 m_removeAction = nullptr;
399 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)));
400 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
401 } else if (showDeleteAction && !showMoveToTrashAction) {
402 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
403 } else {
404 if (!m_removeAction) {
405 m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
406 }
407 addAction(m_removeAction);
408 m_removeAction->update();
409 }
410 }
411
412 void DolphinContextMenu::addShowMenuBarAction()
413 {
414 const KActionCollection* ac = m_mainWindow->actionCollection();
415 QAction* showMenuBar = ac->action(KStandardAction::name(KStandardAction::ShowMenubar));
416 if (!m_mainWindow->menuBar()->isVisible() && !m_mainWindow->toolBar()->isVisible()) {
417 addSeparator();
418 addAction(showMenuBar);
419 }
420 }
421
422 bool DolphinContextMenu::placeExists(const QUrl& url) const
423 {
424 const KFilePlacesModel* placesModel = DolphinPlacesModelSingleton::instance().placesModel();
425
426 const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, url, 1, Qt::MatchExactly);
427
428 return !matchedPlaces.isEmpty();
429 }
430
431 QAction* DolphinContextMenu::createPasteAction()
432 {
433 QAction* action = nullptr;
434 KFileItem destItem;
435 if (!m_fileInfo.isNull() && m_selectedItems.count() <= 1) {
436 destItem = m_fileInfo;
437 } else {
438 destItem = baseFileItem();
439 }
440
441 if (!destItem.isNull() && destItem.isDir()) {
442 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
443 bool canPaste;
444 const QString text = KIO::pasteActionText(mimeData, &canPaste, destItem);
445 if (canPaste) {
446 if (destItem == m_fileInfo) {
447 // if paste destination is a selected folder
448 action = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
449 connect(action, &QAction::triggered, m_mainWindow, &DolphinMainWindow::pasteIntoFolder);
450 } else {
451 action = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
452 }
453 }
454 }
455
456 return action;
457 }
458
459 KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
460 {
461 if (!m_selectedItemsProperties) {
462 m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
463 }
464 return *m_selectedItemsProperties;
465 }
466
467 KFileItem DolphinContextMenu::baseFileItem()
468 {
469 if (!m_baseFileItem) {
470 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
471 KFileItem baseItem = view->rootItem();
472 if (baseItem.isNull() || baseItem.url() != m_baseUrl) {
473 m_baseFileItem = new KFileItem(m_baseUrl);
474 } else {
475 m_baseFileItem = new KFileItem(baseItem);
476 }
477 }
478 return *m_baseFileItem;
479 }
480
481 void DolphinContextMenu::addOpenWithActions(KFileItemActions& fileItemActions)
482 {
483 // insert 'Open With...' action or sub menu
484 fileItemActions.addOpenWithActionsTo(this, QStringLiteral("DesktopEntryName != '%1'").arg(qApp->desktopFileName()));
485 }
486
487 void DolphinContextMenu::addCustomActions()
488 {
489 addActions(m_customActions);
490 }
491
492 void DolphinContextMenu::addAdditionalActions(KFileItemActions &fileItemActions, const KFileItemListProperties &props)
493 {
494 addSeparator();
495
496 QList<QAction *> additionalActions;
497 if (props.isDirectory() && props.isLocal()) {
498 additionalActions << m_mainWindow->actionCollection()->action(QStringLiteral("open_terminal"));
499 }
500 fileItemActions.addActionsTo(this, KFileItemActions::MenuActionSource::All, additionalActions);
501
502 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
503 const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
504 if (!versionControlActions.isEmpty()) {
505 addActions(versionControlActions);
506 addSeparator();
507 }
508 }
509