]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphincontextmenu.cpp
Don't force the context menu to be valid only for DolphinView instances, make it...
[dolphin.git] / src / dolphincontextmenu.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz (peter.penz@gmx.at) and *
3 * Cvetoslav Ludmiloff *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "dolphincontextmenu.h"
22
23 #include "dolphinmainwindow.h"
24 #include "dolphinsettings.h"
25 #include "dolphinview.h"
26 #include "editbookmarkdialog.h"
27
28 #include <kactioncollection.h>
29 #include <kbookmarkmanager.h>
30 #include <kbookmark.h>
31 #include <kdesktopfile.h>
32 #include <kglobal.h>
33 #include <kiconloader.h>
34 #include <kio/netaccess.h>
35 #include <kmenu.h>
36 #include <kmessagebox.h>
37 #include <kmimetypetrader.h>
38 #include <knewmenu.h>
39 #include <konq_operations.h>
40 #include <klocale.h>
41 #include <kpropertiesdialog.h>
42 #include <krun.h>
43 #include <kstandardaction.h>
44 #include <kstandarddirs.h>
45
46 #include <QDir>
47
48 DolphinContextMenu::DolphinContextMenu(DolphinMainWindow* parent,
49 KFileItem* fileInfo,
50 const KUrl& baseUrl,
51 KFileItemList selectedItems) :
52 m_mainWindow(parent),
53 m_fileInfo(fileInfo),
54 m_baseUrl(baseUrl),
55 m_selectedItems(selectedItems),
56 m_context(NoContext)
57 {
58 // The context menu either accesses the URLs of the selected items
59 // or the items itself. To increase the performance the URLs are cached.
60 KFileItemList::const_iterator it = selectedItems.begin();
61 const KFileItemList::const_iterator end = selectedItems.end();
62 while (it != end) {
63 KFileItem* item = *it;
64 m_selectedUrls.append(item->url());
65 ++it;
66 }
67 }
68
69 void DolphinContextMenu::open()
70 {
71 // get the context information
72 if (m_baseUrl.protocol() == "trash") {
73 m_context |= TrashContext;
74 }
75
76 if (m_fileInfo != 0) {
77 m_context |= ItemContext;
78 // TODO: handle other use cases like devices + desktop files
79 }
80
81 // open the corresponding popup for the context
82 if (m_context & TrashContext) {
83 if (m_context & ItemContext) {
84 openTrashItemContextMenu();
85 }
86 else {
87 openTrashContextMenu();
88 }
89 }
90 else if (m_context & ItemContext) {
91 openItemContextMenu();
92 }
93 else {
94 Q_ASSERT(m_context == NoContext);
95 openViewportContextMenu();
96 }
97 }
98
99 DolphinContextMenu::~DolphinContextMenu()
100 {
101 }
102
103 void DolphinContextMenu::openTrashContextMenu()
104 {
105 Q_ASSERT(m_context & TrashContext);
106
107 KMenu* popup = new KMenu(m_mainWindow);
108
109 QAction* emptyTrashAction = new QAction(KIcon("user-trash"), i18n("Emtpy Trash"), popup);
110 KConfig trashConfig("trashrc", KConfig::OnlyLocal);
111 emptyTrashAction->setEnabled(!trashConfig.group("Status").readEntry("Empty", true));
112 popup->addAction(emptyTrashAction);
113
114 QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
115 popup->addAction(propertiesAction);
116
117 if (popup->exec(QCursor::pos()) == emptyTrashAction) {
118 const QString text(i18n("Do you really want to empty the Trash? All items will get deleted."));
119 const bool del = KMessageBox::warningContinueCancel(m_mainWindow,
120 text,
121 QString(),
122 KGuiItem(i18n("Empty Trash"), KIcon("user-trash"))
123 ) == KMessageBox::Continue;
124 if (del) {
125 KonqOperations::emptyTrash(m_mainWindow);
126 }
127 }
128
129 popup->deleteLater();
130 }
131
132 void DolphinContextMenu::openTrashItemContextMenu()
133 {
134 Q_ASSERT(m_context & TrashContext);
135 Q_ASSERT(m_context & ItemContext);
136
137 KMenu* popup = new KMenu(m_mainWindow);
138
139 QAction* restoreAction = new QAction(i18n("Restore"), m_mainWindow);
140 popup->addAction(restoreAction);
141
142 QAction* deleteAction = m_mainWindow->actionCollection()->action("delete");
143 popup->addAction(deleteAction);
144
145 QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
146 popup->addAction(propertiesAction);
147
148 if (popup->exec(QCursor::pos()) == restoreAction) {
149 KonqOperations::restoreTrashedItems(m_selectedUrls, m_mainWindow);
150 }
151
152 popup->deleteLater();
153 }
154
155 void DolphinContextMenu::openItemContextMenu()
156 {
157 Q_ASSERT(m_fileInfo != 0);
158
159 KMenu* popup = new KMenu(m_mainWindow);
160 insertDefaultItemActions(popup);
161
162 // insert 'Bookmark this folder' entry if exactly one item is selected
163 QAction* bookmarkAction = 0;
164 if (m_fileInfo->isDir() && (m_selectedUrls.count() == 1)) {
165 bookmarkAction = popup->addAction(KIcon("bookmark-folder"), i18n("Bookmark this folder"));
166 }
167
168 // Insert 'Open With...' sub menu
169 QVector<KService::Ptr> openWithVector;
170 const QList<QAction*> openWithActions = insertOpenWithItems(popup, openWithVector);
171
172 // Insert 'Actions' sub menu
173 QVector<KDEDesktopMimeType::Service> actionsVector;
174 const QList<QAction*> serviceActions = insertActionItems(popup, actionsVector);
175 popup->addSeparator();
176
177 // insert 'Properties...' entry
178 QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
179 popup->addAction(propertiesAction);
180
181 QAction* activatedAction = popup->exec(QCursor::pos());
182
183 if ((bookmarkAction!= 0) && (activatedAction == bookmarkAction)) {
184 const KUrl selectedUrl(m_fileInfo->url());
185 KBookmark bookmark = EditBookmarkDialog::getBookmark(i18n("Add folder as bookmark"),
186 selectedUrl.fileName(),
187 selectedUrl,
188 "bookmark");
189 if (!bookmark.isNull()) {
190 KBookmarkManager* manager = DolphinSettings::instance().bookmarkManager();
191 KBookmarkGroup root = manager->root();
192 root.addBookmark(manager, bookmark);
193 manager->emitChanged(root);
194 }
195 }
196 else if (serviceActions.contains(activatedAction)) {
197 // one of the 'Actions' items has been selected
198 int id = serviceActions.indexOf(activatedAction);
199 KDEDesktopMimeType::executeService(m_selectedUrls, actionsVector[id]);
200 }
201 else if (openWithActions.contains(activatedAction)) {
202 // one of the 'Open With' items has been selected
203 if (openWithActions.last() == activatedAction) {
204 // the item 'Other...' has been selected
205 KRun::displayOpenWithDialog(m_selectedUrls, m_mainWindow);
206 }
207 else {
208 int id = openWithActions.indexOf(activatedAction);
209 KService::Ptr servicePtr = openWithVector[id];
210 KRun::run(*servicePtr, m_selectedUrls, m_mainWindow);
211 }
212 }
213
214 openWithVector.clear();
215 actionsVector.clear();
216 popup->deleteLater();
217 }
218
219 void DolphinContextMenu::openViewportContextMenu()
220 {
221 Q_ASSERT(m_fileInfo == 0);
222 KMenu* popup = new KMenu(m_mainWindow);
223
224 // setup 'Create New' menu
225 KNewMenu* newMenu = m_mainWindow->newMenu();
226 newMenu->slotCheckUpToDate();
227 newMenu->setPopupFiles(m_baseUrl);
228 popup->addMenu(newMenu->menu());
229 popup->addSeparator();
230
231 QAction* pasteAction = m_mainWindow->actionCollection()->action(KStandardAction::stdName(KStandardAction::Paste));
232 popup->addAction(pasteAction);
233
234 // setup 'View Mode' menu
235 KMenu* viewModeMenu = new KMenu(i18n("View Mode"));
236
237 QAction* iconsMode = m_mainWindow->actionCollection()->action("icons");
238 viewModeMenu->addAction(iconsMode);
239
240 QAction* detailsMode = m_mainWindow->actionCollection()->action("details");
241 viewModeMenu->addAction(detailsMode);
242
243 QAction* previewsMode = m_mainWindow->actionCollection()->action("previews");
244 viewModeMenu->addAction(previewsMode);
245
246 popup->addMenu(viewModeMenu);
247 popup->addSeparator();
248
249 QAction* bookmarkAction = popup->addAction(KIcon("bookmark-folder"), i18n("Bookmark this folder"));
250 popup->addSeparator();
251
252 QAction* propertiesAction = popup->addAction(i18n("Properties..."));
253
254 QAction* activatedAction = popup->exec(QCursor::pos());
255 if (activatedAction == propertiesAction) {
256 new KPropertiesDialog(m_mainWindow->activeView()->url());
257 }
258 else if (activatedAction == bookmarkAction) {
259 const KUrl& url = m_mainWindow->activeView()->url();
260 KBookmark bookmark = EditBookmarkDialog::getBookmark(i18n("Add folder as bookmark"),
261 url.fileName(),
262 url,
263 "bookmark");
264 if (!bookmark.isNull()) {
265 KBookmarkManager* manager = DolphinSettings::instance().bookmarkManager();
266 KBookmarkGroup root = manager->root();
267 root.addBookmark(manager, bookmark);
268 manager->emitChanged(root);
269 }
270 }
271
272 popup->deleteLater();
273 }
274
275 void DolphinContextMenu::insertDefaultItemActions(KMenu* popup)
276 {
277 Q_ASSERT(popup != 0);
278
279 // insert 'Cut', 'Copy' and 'Paste'
280 const KStandardAction::StandardAction actionNames[] = {
281 KStandardAction::Cut,
282 KStandardAction::Copy,
283 KStandardAction::Paste
284 };
285
286 const int count = sizeof(actionNames) / sizeof(KStandardAction::StandardAction);
287 for (int i = 0; i < count; ++i) {
288 QAction* action = m_mainWindow->actionCollection()->action(KStandardAction::stdName(actionNames[i]));
289 if (action != 0) {
290 popup->addAction(action);
291 }
292 }
293 popup->addSeparator();
294
295 // insert 'Rename'
296 QAction* renameAction = m_mainWindow->actionCollection()->action("rename");
297 popup->addAction(renameAction);
298
299 // insert 'Move to Trash' and (optionally) 'Delete'
300 const KSharedConfig::Ptr globalConfig = KSharedConfig::openConfig("kdeglobals", KConfig::NoGlobals);
301 const KConfigGroup kdeConfig(globalConfig, "KDE");
302 bool showDeleteCommand = kdeConfig.readEntry("ShowDeleteCommand", false);
303 const KUrl& url = m_mainWindow->activeView()->url();
304 if (url.isLocalFile()) {
305 QAction* moveToTrashAction = m_mainWindow->actionCollection()->action("move_to_trash");
306 popup->addAction(moveToTrashAction);
307 }
308 else {
309 showDeleteCommand = true;
310 }
311
312 if (showDeleteCommand) {
313 QAction* deleteAction = m_mainWindow->actionCollection()->action("delete");
314 popup->addAction(deleteAction);
315 }
316 }
317
318 QList<QAction*> DolphinContextMenu::insertOpenWithItems(KMenu* popup,
319 QVector<KService::Ptr>& openWithVector)
320 {
321 // Parts of the following code have been taken
322 // from the class KonqOperations located in
323 // libqonq/konq_operations.h of Konqueror.
324 // (Copyright (C) 2000 David Faure <faure@kde.org>)
325
326 // Prepare 'Open With' sub menu. Usually a sub menu is created, where all applications
327 // are listed which are registered to open the item. As last entry "Other..." will be
328 // attached which allows to select a custom application. If no applications are registered
329 // no sub menu is created at all, only "Open With..." will be offered.
330 bool insertOpenWithItems = true;
331 const QString contextMimeType(m_fileInfo->mimetype());
332
333 QListIterator<KFileItem*> mimeIt(m_selectedItems);
334 while (insertOpenWithItems && mimeIt.hasNext()) {
335 KFileItem* item = mimeIt.next();
336 insertOpenWithItems = (contextMimeType == item->mimetype());
337 }
338
339 QList<QAction*> openWithActions;
340 if (insertOpenWithItems) {
341 // fill the 'Open with' sub menu with application types
342 const KMimeType::Ptr mimePtr = KMimeType::findByUrl(m_fileInfo->url());
343 KService::List offers = KMimeTypeTrader::self()->query(mimePtr->name(),
344 "Application",
345 "Type == 'Application'");
346 if (offers.count() > 0) {
347 KService::List::Iterator it;
348 KMenu* openWithMenu = new KMenu(i18n("Open With"));
349 for(it = offers.begin(); it != offers.end(); ++it) {
350 // The offer list from the KTrader returns duplicate
351 // application entries. Although this seems to be a configuration
352 // problem outside the scope of Dolphin, duplicated entries just
353 // will be skipped here.
354 const QString appName((*it)->name());
355 if (!containsEntry(openWithMenu, appName)) {
356 const KIcon icon((*it)->icon());
357 QAction *action = openWithMenu->addAction(icon, appName);
358 openWithVector.append(*it);
359 openWithActions << action;
360 }
361 }
362
363 openWithMenu->addSeparator();
364 QAction* action = openWithMenu->addAction(i18n("&Other..."));
365
366 openWithActions << action;
367 popup->addSeparator();
368 popup->addMenu(openWithMenu);
369 }
370 else {
371 // No applications are registered, hence just offer
372 // a "Open With..." item instead of a sub menu containing
373 // only one entry.
374 QAction* action = popup->addAction(i18n("Open With..."));
375 openWithActions << action;
376 }
377 }
378 else {
379 // At least one of the selected items has a different MIME type. In this case
380 // just show a disabled "Open With..." entry.
381 popup->addSeparator();
382 QAction* action = popup->addAction(i18n("Open With..."));
383 action->setEnabled(false);
384 }
385
386 return openWithActions;
387 }
388
389 QList<QAction*> DolphinContextMenu::insertActionItems(KMenu* popup,
390 QVector<KDEDesktopMimeType::Service>& actionsVector)
391 {
392 // Parts of the following code have been taken
393 // from the class KonqOperations located in
394 // libqonq/konq_operations.h of Konqueror.
395 // (Copyright (C) 2000 David Faure <faure@kde.org>)
396
397 KMenu* actionsMenu = new KMenu(i18n("Actions"));
398
399 QList<QAction*> serviceActions;
400
401 QStringList dirs = KGlobal::dirs()->findDirs("data", "dolphin/servicemenus/");
402
403 KMenu* menu = 0;
404 for (QStringList::ConstIterator dirIt = dirs.begin(); dirIt != dirs.end(); ++dirIt) {
405 QDir dir(*dirIt);
406 QStringList filters;
407 filters << "*.desktop";
408 dir.setNameFilters(filters);
409 QStringList entries = dir.entryList(QDir::Files);
410
411 for (QStringList::ConstIterator entryIt = entries.begin(); entryIt != entries.end(); ++entryIt) {
412 KConfigGroup cfg(KSharedConfig::openConfig( *dirIt + *entryIt, KConfig::OnlyLocal), "Desktop Entry" );
413 if ((cfg.hasKey("Actions") || cfg.hasKey("X-KDE-GetActionMenu")) && cfg.hasKey("ServiceTypes")) {
414 //const QStringList types = cfg.readListEntry("ServiceTypes");
415 QStringList types;
416 types = cfg.readEntry("ServiceTypes", types);
417 for (QStringList::ConstIterator it = types.begin(); it != types.end(); ++it) {
418 // check whether the mime type is equal or whether the
419 // mimegroup (e. g. image/*) is supported
420
421 bool insert = false;
422 if ((*it) == "all/allfiles") {
423 // The service type is valid for all files, but not for directories.
424 // Check whether the selected items only consist of files...
425 QListIterator<KFileItem*> mimeIt(m_selectedItems);
426 insert = true;
427 while (insert && mimeIt.hasNext()) {
428 KFileItem* item = mimeIt.next();
429 insert = !item->isDir();
430 }
431 }
432
433 if (!insert) {
434 // Check whether the MIME types of all selected files match
435 // to the mimetype of the service action. As soon as one MIME
436 // type does not match, no service menu is shown at all.
437 QListIterator<KFileItem*> mimeIt(m_selectedItems);
438 insert = true;
439 while (insert && mimeIt.hasNext()) {
440 KFileItem* item = mimeIt.next();
441 const QString mimeType(item->mimetype());
442 const QString mimeGroup(mimeType.left(mimeType.indexOf('/')));
443
444 insert = (*it == mimeType) ||
445 ((*it).right(1) == "*") &&
446 ((*it).left((*it).indexOf('/')) == mimeGroup);
447 }
448 }
449
450 if (insert) {
451 menu = actionsMenu;
452
453 const QString submenuName = cfg.readEntry( "X-KDE-Submenu" );
454 if (!submenuName.isEmpty()) {
455 menu = new KMenu(submenuName);
456 actionsMenu->addMenu(menu);
457 }
458
459 Q3ValueList<KDEDesktopMimeType::Service> userServices =
460 KDEDesktopMimeType::userDefinedServices(*dirIt + *entryIt, true);
461
462 Q3ValueList<KDEDesktopMimeType::Service>::Iterator serviceIt;
463 for (serviceIt = userServices.begin(); serviceIt != userServices.end(); ++serviceIt) {
464 KDEDesktopMimeType::Service service = (*serviceIt);
465 if (!service.m_strIcon.isEmpty()) {
466 QAction* action = menu->addAction(SmallIcon(service.m_strIcon),
467 service.m_strName);
468 serviceActions << action;
469 }
470 else {
471 QAction *action = menu->addAction(service.m_strName);
472 serviceActions << action;
473 }
474 actionsVector.append(service);
475 }
476 }
477 }
478 }
479 }
480 }
481
482 const int itemsCount = actionsMenu->actions().count();
483 if (itemsCount == 0) {
484 // no actions are available at all, hence show the "Actions"
485 // submenu disabled
486 actionsMenu->setEnabled(false);
487 }
488
489 if (itemsCount == 1) {
490 // Exactly one item is available. Instead of showing a sub menu with
491 // only one item, show the item directly in the root menu.
492 if (menu == actionsMenu) {
493 // The item is an action, hence show the action in the root menu.
494 const QList<QAction*> actions = actionsMenu->actions();
495 Q_ASSERT(actions.count() == 1);
496
497 const QString text = actions[0]->text();
498 const QIcon icon = actions[0]->icon();
499 if (icon.isNull()) {
500 QAction* action = popup->addAction(text);
501 serviceActions.clear();
502 serviceActions << action;
503 }
504 else {
505 QAction* action = popup->addAction(icon, text);
506 serviceActions.clear();
507 serviceActions << action;
508 }
509 }
510 else {
511 // The item is a sub menu, hence show the sub menu in the root menu.
512 popup->addMenu(menu);
513 }
514 actionsMenu->deleteLater();
515 actionsMenu = 0;
516 }
517 else {
518 popup->addMenu(actionsMenu);
519 }
520
521 return serviceActions;
522 }
523
524 bool DolphinContextMenu::containsEntry(const KMenu* menu,
525 const QString& entryName) const
526 {
527 Q_ASSERT(menu != 0);
528
529 const QList<QAction*> list = menu->actions();
530 const uint count = list.count();
531 for (uint i = 0; i < count; ++i) {
532 const QAction* action = list.at(i);
533 if (action->text() == entryName) {
534 return true;
535 }
536 }
537
538 return false;
539 }