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