]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphincontextmenu.cpp
028fd98bd26269bb125f4e2bfcc372a3801f8960
[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 <KFileItemListProperties>
24 #include <KHamburgerMenu>
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 <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 KFileItemActions *fileItemActions) :
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 m_fileItemActions(fileItemActions)
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 QApplication::instance()->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 bool DolphinContextMenu::eventFilter(QObject* object, QEvent* event)
120 {
121 Q_UNUSED(object)
122
123 if(event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
124 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
125
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 }
133 }
134
135 return false;
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 if (exec(m_pos) == emptyTrashAction) {
152 Trash::empty(m_mainWindow);
153 }
154 }
155
156 void DolphinContextMenu::openTrashItemContextMenu()
157 {
158 Q_ASSERT(m_context & TrashContext);
159 Q_ASSERT(m_context & ItemContext);
160
161 QAction* restoreAction = new QAction(QIcon::fromTheme("restoration"), i18nc("@action:inmenu", "Restore"), m_mainWindow);
162 addAction(restoreAction);
163
164 QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile));
165 addAction(deleteAction);
166
167 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
168 addAction(propertiesAction);
169
170 if (exec(m_pos) == restoreAction) {
171 QList<QUrl> selectedUrls;
172 selectedUrls.reserve(m_selectedItems.count());
173 for (const KFileItem &item : qAsConst(m_selectedItems)) {
174 selectedUrls.append(item.url());
175 }
176
177 KIO::RestoreJob *job = KIO::restoreFromTrash(selectedUrls);
178 KJobWidgets::setWindow(job, m_mainWindow);
179 job->uiDelegate()->setAutoErrorHandlingEnabled(true);
180 }
181 }
182
183 void DolphinContextMenu::addDirectoryItemContextMenu()
184 {
185 // insert 'Open in new window' and 'Open in new tab' entries
186 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
187 if (ContextMenuSettings::showOpenInNewTab()) {
188 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
189 }
190 if (ContextMenuSettings::showOpenInNewWindow()) {
191 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
192 }
193
194 // Insert 'Open With' entries
195 addOpenWithActions();
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->checkUpToDate();
201 newFileMenu->setPopupFiles(QList<QUrl>() << m_fileInfo.url());
202 newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
203 connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
204 connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
205
206 QMenu* menu = newFileMenu->menu();
207 menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
208 menu->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
209 addMenu(menu);
210
211 addSeparator();
212 }
213
214 void DolphinContextMenu::openItemContextMenu()
215 {
216 Q_ASSERT(!m_fileInfo.isNull());
217
218 QAction* openParentAction = nullptr;
219 QAction* openParentInNewWindowAction = nullptr;
220 QAction* openParentInNewTabAction = nullptr;
221 const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();
222
223
224 m_fileItemActions->setItemListProperties(selectedItemsProps);
225
226 if (m_selectedItems.count() == 1) {
227 // single files
228 if (m_fileInfo.isDir()) {
229 addDirectoryItemContextMenu();
230 } else if (m_context & TimelineContext || m_context & SearchContext) {
231 addOpenWithActions();
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();
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();
277 }
278
279 insertDefaultItemActions(selectedItemsProps);
280
281 addAdditionalActions(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 m_fileItemActions->setItemListProperties(baseUrlProperties);
314
315 // Set up and insert 'Create New' menu
316 KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu();
317 newFileMenu->checkUpToDate();
318 newFileMenu->setPopupFiles(QList<QUrl>() << m_baseUrl);
319 addMenu(newFileMenu->menu());
320
321 // Show "open with" menu items even if the dir is empty, because there are legitimate
322 // use cases for this, such as opening an empty dir in Kate or VSCode or something
323 addOpenWithActions();
324
325 QAction* pasteAction = createPasteAction();
326 if (pasteAction) {
327 addAction(pasteAction);
328 }
329
330 // Insert 'Add to Places' entry if it's not already in the places panel
331 if (ContextMenuSettings::showAddToPlaces() &&
332 !placeExists(m_mainWindow->activeViewContainer()->url())) {
333 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
334 }
335 addSeparator();
336
337 // Insert 'Sort By' and 'View Mode'
338 if (ContextMenuSettings::showSortBy()) {
339 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("sort")));
340 }
341 if (ContextMenuSettings::showViewMode()) {
342 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("view_mode")));
343 }
344 if (ContextMenuSettings::showSortBy() || ContextMenuSettings::showViewMode()) {
345 addSeparator();
346 }
347
348 addAdditionalActions(baseUrlProperties);
349 addCustomActions();
350
351 addSeparator();
352
353 QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
354 addAction(propertiesAction);
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 if (ContextMenuSettings::showCopyLocation()) {
367 QAction* copyPathAction = collection->action(QString("copy_location"));
368 copyPathAction->setEnabled(m_selectedItems.size() == 1);
369 addAction(copyPathAction);
370 }
371 QAction* pasteAction = createPasteAction();
372 if (pasteAction) {
373 addAction(pasteAction);
374 }
375
376 // Insert 'Duplicate Here'
377 if (ContextMenuSettings::showDuplicateHere()) {
378 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("duplicate")));
379 }
380
381 // Insert 'Rename'
382 addAction(collection->action(KStandardAction::name(KStandardAction::RenameFile)));
383
384 // Insert 'Add to Places' entry if appropriate
385 if (ContextMenuSettings::showAddToPlaces() &&
386 m_selectedItems.count() == 1 &&
387 m_fileInfo.isDir() &&
388 !placeExists(m_fileInfo.url())) {
389 addAction(m_mainWindow->actionCollection()->action(QStringLiteral("add_to_places")));
390 }
391
392 addSeparator();
393
394 // Insert 'Move to Trash' and/or 'Delete'
395 const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
396 !properties.isLocal());
397 const bool showMoveToTrashAction = (properties.isLocal() &&
398 properties.supportsMoving());
399
400 if (showDeleteAction && showMoveToTrashAction) {
401 delete m_removeAction;
402 m_removeAction = nullptr;
403 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)));
404 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
405 } else if (showDeleteAction && !showMoveToTrashAction) {
406 addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
407 } else {
408 if (!m_removeAction) {
409 m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
410 }
411 addAction(m_removeAction);
412 m_removeAction->update();
413 }
414 }
415
416 bool DolphinContextMenu::placeExists(const QUrl& url) const
417 {
418 const KFilePlacesModel* placesModel = DolphinPlacesModelSingleton::instance().placesModel();
419
420 const auto& matchedPlaces = placesModel->match(placesModel->index(0,0), KFilePlacesModel::UrlRole, url, 1, Qt::MatchExactly);
421
422 return !matchedPlaces.isEmpty();
423 }
424
425 QAction* DolphinContextMenu::createPasteAction()
426 {
427 QAction* action = nullptr;
428 KFileItem destItem;
429 if (!m_fileInfo.isNull() && m_selectedItems.count() <= 1) {
430 destItem = m_fileInfo;
431 } else {
432 destItem = baseFileItem();
433 }
434
435 if (!destItem.isNull() && destItem.isDir()) {
436 const QMimeData *mimeData = QApplication::clipboard()->mimeData();
437 bool canPaste;
438 const QString text = KIO::pasteActionText(mimeData, &canPaste, destItem);
439 if (canPaste) {
440 if (destItem == m_fileInfo) {
441 // if paste destination is a selected folder
442 action = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
443 connect(action, &QAction::triggered, m_mainWindow, &DolphinMainWindow::pasteIntoFolder);
444 } else {
445 action = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
446 }
447 }
448 }
449
450 return action;
451 }
452
453 KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
454 {
455 if (!m_selectedItemsProperties) {
456 m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
457 }
458 return *m_selectedItemsProperties;
459 }
460
461 KFileItem DolphinContextMenu::baseFileItem()
462 {
463 if (!m_baseFileItem) {
464 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
465 KFileItem baseItem = view->rootItem();
466 if (baseItem.isNull() || baseItem.url() != m_baseUrl) {
467 m_baseFileItem = new KFileItem(m_baseUrl);
468 } else {
469 m_baseFileItem = new KFileItem(baseItem);
470 }
471 }
472 return *m_baseFileItem;
473 }
474
475 void DolphinContextMenu::addOpenWithActions()
476 {
477 // insert 'Open With...' action or sub menu
478 m_fileItemActions->insertOpenWithActionsTo(nullptr, this, QStringList{qApp->desktopFileName()});
479 }
480
481 void DolphinContextMenu::addCustomActions()
482 {
483 addActions(m_customActions);
484 }
485
486 void DolphinContextMenu::addAdditionalActions(const KFileItemListProperties &props)
487 {
488 addSeparator();
489
490 QList<QAction *> additionalActions;
491 if (props.isDirectory() && props.isLocal() && ContextMenuSettings::showOpenTerminal()) {
492 additionalActions << m_mainWindow->actionCollection()->action(QStringLiteral("open_terminal"));
493 }
494 m_fileItemActions->addActionsTo(this, KFileItemActions::MenuActionSource::All, additionalActions);
495
496 const DolphinView* view = m_mainWindow->activeViewContainer()->view();
497 const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
498 if (!versionControlActions.isEmpty()) {
499 addActions(versionControlActions);
500 addSeparator();
501 }
502 }
503