]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphincontextmenu.cpp
e78f3ec1c4358f4c280100f61ee8055a10d10084
[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 <konqmimedata.h>
40 #include <konq_operations.h>
41 #include <klocale.h>
42 #include <kpropertiesdialog.h>
43 #include <krun.h>
44 #include <kstandardaction.h>
45 #include <kstandarddirs.h>
46
47 #include <QApplication>
48 #include <QClipboard>
49 #include <QDir>
50
51 DolphinContextMenu::DolphinContextMenu(DolphinMainWindow* parent,
52 KFileItem* fileInfo,
53 const KUrl& baseUrl) :
54 m_mainWindow(parent),
55 m_fileInfo(fileInfo),
56 m_baseUrl(baseUrl),
57 m_context(NoContext)
58 {
59 // The context menu either accesses the URLs of the selected items
60 // or the items itself. To increase the performance both lists are cached.
61 DolphinView* view = m_mainWindow->activeView();
62 m_selectedUrls = view->selectedUrls();
63 m_selectedItems = view->selectedItems();
64 }
65
66 DolphinContextMenu::~DolphinContextMenu()
67 {
68 }
69
70 void DolphinContextMenu::open()
71 {
72 // get the context information
73 if (m_baseUrl.protocol() == "trash") {
74 m_context |= TrashContext;
75 }
76
77 if (m_fileInfo != 0) {
78 m_context |= ItemContext;
79 // TODO: handle other use cases like devices + desktop files
80 }
81
82 // open the corresponding popup for the context
83 if (m_context & TrashContext) {
84 if (m_context & ItemContext) {
85 openTrashItemContextMenu();
86 }
87 else {
88 openTrashContextMenu();
89 }
90 }
91 else if (m_context & ItemContext) {
92 openItemContextMenu();
93 }
94 else {
95 Q_ASSERT(m_context == NoContext);
96 openViewportContextMenu();
97 }
98 }
99
100
101 void DolphinContextMenu::openTrashContextMenu()
102 {
103 Q_ASSERT(m_context & TrashContext);
104
105 KMenu* popup = new KMenu(m_mainWindow);
106
107 QAction* emptyTrashAction = new QAction(KIcon("emptytrash"), i18n("Emtpy Trash"), popup);
108 KConfig trashConfig("trashrc", KConfig::OnlyLocal);
109 emptyTrashAction->setEnabled(!trashConfig.group("Status").readEntry("Empty", true));
110 popup->addAction(emptyTrashAction);
111
112 QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
113 popup->addAction(propertiesAction);
114
115 if (popup->exec(QCursor::pos()) == emptyTrashAction) {
116 const QString text(i18n("Do you really want to empty the Trash? All items will get deleted."));
117 const bool del = KMessageBox::warningContinueCancel(m_mainWindow,
118 text,
119 QString(),
120 KGuiItem(i18n("Empty Trash"), KIcon("user-trash"))
121 ) == KMessageBox::Continue;
122 if (del) {
123 KonqOperations::emptyTrash(m_mainWindow);
124 }
125 }
126
127 popup->deleteLater();
128 }
129
130 void DolphinContextMenu::openTrashItemContextMenu()
131 {
132 Q_ASSERT(m_context & TrashContext);
133 Q_ASSERT(m_context & ItemContext);
134
135 KMenu* popup = new KMenu(m_mainWindow);
136
137 QAction* restoreAction = new QAction(i18n("Restore"), m_mainWindow);
138 popup->addAction(restoreAction);
139
140 QAction* deleteAction = m_mainWindow->actionCollection()->action("delete");
141 popup->addAction(deleteAction);
142
143 QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
144 popup->addAction(propertiesAction);
145
146 if (popup->exec(QCursor::pos()) == restoreAction) {
147 KonqOperations::restoreTrashedItems(m_selectedUrls, m_mainWindow);
148 }
149
150 popup->deleteLater();
151 }
152
153 void DolphinContextMenu::openItemContextMenu()
154 {
155 Q_ASSERT(m_fileInfo != 0);
156
157 KMenu* popup = new KMenu(m_mainWindow);
158 insertDefaultItemActions(popup);
159
160 popup->addSeparator();
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 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 const KActionCollection* collection = m_mainWindow->actionCollection();
279
280 // insert 'Cut', 'Copy' and 'Paste'
281 QAction* cutAction = collection->action(KStandardAction::stdName(KStandardAction::Cut));
282 QAction* copyAction = collection->action(KStandardAction::stdName(KStandardAction::Copy));
283 QAction* pasteAction = collection->action(KStandardAction::stdName(KStandardAction::Paste));
284
285 popup->addAction(cutAction);
286 popup->addAction(copyAction);
287 popup->addAction(pasteAction);
288 popup->addSeparator();
289
290 // insert 'Rename'
291 QAction* renameAction = collection->action("rename");
292 popup->addAction(renameAction);
293
294 // insert 'Move to Trash' and (optionally) 'Delete'
295 const KSharedConfig::Ptr globalConfig = KSharedConfig::openConfig("kdeglobals", KConfig::NoGlobals);
296 const KConfigGroup kdeConfig(globalConfig, "KDE");
297 bool showDeleteCommand = kdeConfig.readEntry("ShowDeleteCommand", false);
298 const KUrl& url = m_mainWindow->activeView()->url();
299 if (url.isLocalFile()) {
300 QAction* moveToTrashAction = collection->action("move_to_trash");
301 popup->addAction(moveToTrashAction);
302 }
303 else {
304 showDeleteCommand = true;
305 }
306
307 if (showDeleteCommand) {
308 QAction* deleteAction = collection->action("delete");
309 popup->addAction(deleteAction);
310 }
311 }
312
313 QList<QAction*> DolphinContextMenu::insertOpenWithItems(KMenu* popup,
314 QVector<KService::Ptr>& openWithVector)
315 {
316 // Parts of the following code have been taken
317 // from the class KonqOperations located in
318 // libqonq/konq_operations.h of Konqueror.
319 // (Copyright (C) 2000 David Faure <faure@kde.org>)
320
321 // Prepare 'Open With' sub menu. Usually a sub menu is created, where all applications
322 // are listed which are registered to open the item. As last entry "Other..." will be
323 // attached which allows to select a custom application. If no applications are registered
324 // no sub menu is created at all, only "Open With..." will be offered.
325 bool insertOpenWithItems = true;
326 const QString contextMimeType(m_fileInfo->mimetype());
327
328 QListIterator<KFileItem*> mimeIt(m_selectedItems);
329 while (insertOpenWithItems && mimeIt.hasNext()) {
330 KFileItem* item = mimeIt.next();
331 insertOpenWithItems = (contextMimeType == item->mimetype());
332 }
333
334 QList<QAction*> openWithActions;
335 if (insertOpenWithItems) {
336 // fill the 'Open with' sub menu with application types
337 const KMimeType::Ptr mimePtr = KMimeType::findByUrl(m_fileInfo->url());
338 KService::List offers = KMimeTypeTrader::self()->query(mimePtr->name(),
339 "Application",
340 "Type == 'Application'");
341 if (offers.count() > 0) {
342 KService::List::Iterator it;
343 KMenu* openWithMenu = new KMenu(i18n("Open With"));
344 for(it = offers.begin(); it != offers.end(); ++it) {
345 // The offer list from the KTrader returns duplicate
346 // application entries. Although this seems to be a configuration
347 // problem outside the scope of Dolphin, duplicated entries just
348 // will be skipped here.
349 const QString appName((*it)->name());
350 if (!containsEntry(openWithMenu, appName)) {
351 const KIcon icon((*it)->icon());
352 QAction* action = openWithMenu->addAction(icon, appName);
353 openWithVector.append(*it);
354 openWithActions << action;
355 }
356 }
357
358 openWithMenu->addSeparator();
359 QAction* action = openWithMenu->addAction(i18n("&Other..."));
360
361 openWithActions << action;
362 popup->addMenu(openWithMenu);
363 }
364 else {
365 // No applications are registered, hence just offer
366 // a "Open With..." item instead of a sub menu containing
367 // only one entry.
368 QAction* action = popup->addAction(i18n("Open With..."));
369 openWithActions << action;
370 }
371 }
372 else {
373 // At least one of the selected items has a different MIME type. In this case
374 // just show a disabled "Open With..." entry.
375 QAction* action = popup->addAction(i18n("Open With..."));
376 action->setEnabled(false);
377 }
378
379 return openWithActions;
380 }
381
382 QList<QAction*> DolphinContextMenu::insertActionItems(KMenu* popup,
383 QVector<KDEDesktopMimeType::Service>& actionsVector)
384 {
385 // Parts of the following code have been taken
386 // from the class KonqOperations located in
387 // libqonq/konq_operations.h of Konqueror.
388 // (Copyright (C) 2000 David Faure <faure@kde.org>)
389
390 KMenu* actionsMenu = new KMenu(i18n("Actions"));
391
392 QList<QAction*> serviceActions;
393
394 QStringList dirs = KGlobal::dirs()->findDirs("data", "dolphin/servicemenus/");
395
396 KMenu* menu = 0;
397 for (QStringList::ConstIterator dirIt = dirs.begin(); dirIt != dirs.end(); ++dirIt) {
398 QDir dir(*dirIt);
399 QStringList filters;
400 filters << "*.desktop";
401 dir.setNameFilters(filters);
402 QStringList entries = dir.entryList(QDir::Files);
403
404 for (QStringList::ConstIterator entryIt = entries.begin(); entryIt != entries.end(); ++entryIt) {
405 KConfigGroup cfg(KSharedConfig::openConfig( *dirIt + *entryIt, KConfig::OnlyLocal), "Desktop Entry" );
406 if ((cfg.hasKey("Actions") || cfg.hasKey("X-KDE-GetActionMenu")) && cfg.hasKey("ServiceTypes")) {
407 //const QStringList types = cfg.readListEntry("ServiceTypes");
408 QStringList types;
409 types = cfg.readEntry("ServiceTypes", types);
410 for (QStringList::ConstIterator it = types.begin(); it != types.end(); ++it) {
411 // check whether the mime type is equal or whether the
412 // mimegroup (e. g. image/*) is supported
413
414 bool insert = false;
415 if ((*it) == "all/allfiles") {
416 // The service type is valid for all files, but not for directories.
417 // Check whether the selected items only consist of files...
418 QListIterator<KFileItem*> mimeIt(m_selectedItems);
419 insert = true;
420 while (insert && mimeIt.hasNext()) {
421 KFileItem* item = mimeIt.next();
422 insert = !item->isDir();
423 }
424 }
425
426 if (!insert) {
427 // Check whether the MIME types of all selected files match
428 // to the mimetype of the service action. As soon as one MIME
429 // type does not match, no service menu is shown at all.
430 QListIterator<KFileItem*> mimeIt(m_selectedItems);
431 insert = true;
432 while (insert && mimeIt.hasNext()) {
433 KFileItem* item = mimeIt.next();
434 const QString mimeType(item->mimetype());
435 const QString mimeGroup(mimeType.left(mimeType.indexOf('/')));
436
437 insert = (*it == mimeType) ||
438 ((*it).right(1) == "*") &&
439 ((*it).left((*it).indexOf('/')) == mimeGroup);
440 }
441 }
442
443 if (insert) {
444 menu = actionsMenu;
445
446 const QString submenuName = cfg.readEntry( "X-KDE-Submenu" );
447 if (!submenuName.isEmpty()) {
448 menu = new KMenu(submenuName);
449 actionsMenu->addMenu(menu);
450 }
451
452 Q3ValueList<KDEDesktopMimeType::Service> userServices =
453 KDEDesktopMimeType::userDefinedServices(*dirIt + *entryIt, true);
454
455 Q3ValueList<KDEDesktopMimeType::Service>::Iterator serviceIt;
456 for (serviceIt = userServices.begin(); serviceIt != userServices.end(); ++serviceIt) {
457 KDEDesktopMimeType::Service service = (*serviceIt);
458 if (!service.m_strIcon.isEmpty()) {
459 QAction* action = menu->addAction(SmallIcon(service.m_strIcon),
460 service.m_strName);
461 serviceActions << action;
462 }
463 else {
464 QAction *action = menu->addAction(service.m_strName);
465 serviceActions << action;
466 }
467 actionsVector.append(service);
468 }
469 }
470 }
471 }
472 }
473 }
474
475 const int itemsCount = actionsMenu->actions().count();
476 if (itemsCount == 0) {
477 // no actions are available at all, hence show the "Actions"
478 // submenu disabled
479 actionsMenu->setEnabled(false);
480 }
481
482 if (itemsCount == 1) {
483 // Exactly one item is available. Instead of showing a sub menu with
484 // only one item, show the item directly in the root menu.
485 if (menu == actionsMenu) {
486 // The item is an action, hence show the action in the root menu.
487 const QList<QAction*> actions = actionsMenu->actions();
488 Q_ASSERT(actions.count() == 1);
489
490 const QString text = actions[0]->text();
491 const QIcon icon = actions[0]->icon();
492 if (icon.isNull()) {
493 QAction* action = popup->addAction(text);
494 serviceActions.clear();
495 serviceActions << action;
496 }
497 else {
498 QAction* action = popup->addAction(icon, text);
499 serviceActions.clear();
500 serviceActions << action;
501 }
502 }
503 else {
504 // The item is a sub menu, hence show the sub menu in the root menu.
505 popup->addMenu(menu);
506 }
507 actionsMenu->deleteLater();
508 actionsMenu = 0;
509 }
510 else {
511 popup->addMenu(actionsMenu);
512 }
513
514 return serviceActions;
515 }
516
517 bool DolphinContextMenu::containsEntry(const KMenu* menu,
518 const QString& entryName) const
519 {
520 Q_ASSERT(menu != 0);
521
522 const QList<QAction*> list = menu->actions();
523 const uint count = list.count();
524 for (uint i = 0; i < count; ++i) {
525 const QAction* action = list.at(i);
526 if (action->text() == entryName) {
527 return true;
528 }
529 }
530
531 return false;
532 }
533
534 #include "dolphincontextmenu.moc"