dolphincontextmenu.cpp 19.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/***************************************************************************
 *   Copyright (C) 2006 by Peter Penz (peter.penz@gmx.at) and              *
 *   Cvetoslav Ludmiloff                                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
18
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
19 20 21 22
 ***************************************************************************/

#include "dolphincontextmenu.h"

Peter Penz's avatar
Peter Penz committed
23
#include "dolphinmainwindow.h"
Peter Penz's avatar
Peter Penz committed
24
#include "dolphinnewfilemenu.h"
25
#include "dolphinviewcontainer.h"
26
#include "dolphin_generalsettings.h"
27
#include "dolphinremoveaction.h"
Peter Penz's avatar
Peter Penz committed
28

29
#include <KActionCollection>
30
#include <KAbstractFileItemActionPlugin>
31 32
#include <KFileItemActions>
#include <KFileItemListProperties>
33
#include <KIO/RestoreJob>
34 35
#include <KIO/EmptyTrashJob>
#include <KIO/JobUiDelegate>
36
#include <KIO/Paste>
37
#include <KJobWidgets>
38
#include <KMimeTypeTrader>
39
#include <KNewFileMenu>
40
#include <KService>
Laurent Montel's avatar
Laurent Montel committed
41
#include <KLocalizedString>
42
#include <KStandardAction>
43
#include <KToolBar>
44

45 46
#include <QApplication>
#include <QClipboard>
David Faure's avatar
David Faure committed
47
#include <QKeyEvent>
Laurent Montel's avatar
Laurent Montel committed
48
#include <QMenuBar>
49 50
#include <QMenu>

51 52 53
#include <panels/places/placesitem.h>
#include <panels/places/placesitemmodel.h>

54

55 56 57
#include "views/dolphinview.h"
#include "views/viewmodecontroller.h"

58
DolphinContextMenu::DolphinContextMenu(DolphinMainWindow* parent,
Peter Penz's avatar
Peter Penz committed
59
                                       const QPoint& pos,
60
                                       const KFileItem& fileInfo,
Lukáš Tinkl's avatar
Lukáš Tinkl committed
61
                                       const QUrl& baseUrl) :
62
    QMenu(parent),
Peter Penz's avatar
Peter Penz committed
63
    m_pos(pos),
64 65 66
    m_mainWindow(parent),
    m_fileInfo(fileInfo),
    m_baseUrl(baseUrl),
67 68 69
    m_baseFileItem(0),
    m_selectedItems(),
    m_selectedItemsProperties(0),
70
    m_context(NoContext),
71
    m_copyToMenu(parent),
72
    m_customActions(),
73 74
    m_command(None),
    m_removeAction(0)
75
{
76 77
    // The context menu either accesses the URLs of the selected items
    // or the items itself. To increase the performance both lists are cached.
78
    const DolphinView* view = m_mainWindow->activeViewContainer()->view();
79
    m_selectedItems = view->selectedItems();
80 81
}

82
DolphinContextMenu::~DolphinContextMenu()
Peter Penz's avatar
Peter Penz committed
83
{
84 85
    delete m_selectedItemsProperties;
    m_selectedItemsProperties = 0;
Peter Penz's avatar
Peter Penz committed
86
}
87

88 89 90 91 92
void DolphinContextMenu::setCustomActions(const QList<QAction*>& actions)
{
    m_customActions = actions;
}

93
DolphinContextMenu::Command DolphinContextMenu::open()
94
{
95
    // get the context information
Lukáš Tinkl's avatar
Lukáš Tinkl committed
96
    if (m_baseUrl.scheme() == QLatin1String("trash")) {
97
        m_context |= TrashContext;
98
    }
99

100
    if (!m_fileInfo.isNull() && !m_selectedItems.isEmpty()) {
101 102
        m_context |= ItemContext;
        // TODO: handle other use cases like devices + desktop files
103
    }
104 105 106 107 108

    // open the corresponding popup for the context
    if (m_context & TrashContext) {
        if (m_context & ItemContext) {
            openTrashItemContextMenu();
109
        } else {
110 111
            openTrashContextMenu();
        }
112
    } else if (m_context & ItemContext) {
113
        openItemContextMenu();
114
    } else {
115 116 117
        Q_ASSERT(m_context == NoContext);
        openViewportContextMenu();
    }
118 119

    return m_command;
120 121
}

122
void DolphinContextMenu::keyPressEvent(QKeyEvent *ev)
123
{
124
    if (m_removeAction && ev->key() == Qt::Key_Shift) {
125
        m_removeAction->update();
126
    }
127
    QMenu::keyPressEvent(ev);
128 129
}

130
void DolphinContextMenu::keyReleaseEvent(QKeyEvent *ev)
131
{
132
    if (m_removeAction && ev->key() == Qt::Key_Shift) {
133
        m_removeAction->update();
134
    }
135
    QMenu::keyReleaseEvent(ev);
136 137
}

138 139 140 141
void DolphinContextMenu::openTrashContextMenu()
{
    Q_ASSERT(m_context & TrashContext);

142
    QAction* emptyTrashAction = new QAction(QIcon::fromTheme("trash-empty"), i18nc("@action:inmenu", "Empty Trash"), this);
143
    KConfig trashConfig("trashrc", KConfig::SimpleConfig);
144
    emptyTrashAction->setEnabled(!trashConfig.group("Status").readEntry("Empty", true));
145
    addAction(emptyTrashAction);
146

147
    addCustomActions();
148

149
    QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
150
    addAction(propertiesAction);
151

152 153
    addShowMenuBarAction();

154
    if (exec(m_pos) == emptyTrashAction) {
155 156 157 158 159 160 161
        KIO::JobUiDelegate uiDelegate;
        uiDelegate.setWindow(m_mainWindow);
        if (uiDelegate.askDeleteConfirmation(QList<QUrl>(), KIO::JobUiDelegate::EmptyTrash, KIO::JobUiDelegate::DefaultConfirmation)) {
            KIO::Job* job = KIO::emptyTrash();
            KJobWidgets::setWindow(job, m_mainWindow);
            job->ui()->setAutoErrorHandlingEnabled(true);
        }
162 163 164 165 166 167 168 169
    }
}

void DolphinContextMenu::openTrashItemContextMenu()
{
    Q_ASSERT(m_context & TrashContext);
    Q_ASSERT(m_context & ItemContext);

Peter Penz's avatar
Peter Penz committed
170
    QAction* restoreAction = new QAction(i18nc("@action:inmenu", "Restore"), m_mainWindow);
171
    addAction(restoreAction);
172

173
    QAction* deleteAction = m_mainWindow->actionCollection()->action("delete");
174
    addAction(deleteAction);
175

176
    QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
177
    addAction(propertiesAction);
178

179
    if (exec(m_pos) == restoreAction) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
180
        QList<QUrl> selectedUrls;
181 182 183 184
        foreach (const KFileItem &item, m_selectedItems) {
            selectedUrls.append(item.url());
        }

185 186 187
        KIO::RestoreJob *job = KIO::restoreFromTrash(selectedUrls);
        KJobWidgets::setWindow(job, m_mainWindow);
        job->uiDelegate()->setAutoErrorHandlingEnabled(true);
188 189 190 191 192
    }
}

void DolphinContextMenu::openItemContextMenu()
{
193
    Q_ASSERT(!m_fileInfo.isNull());
194

195
    QAction* openParentAction = 0;
196 197
    QAction* openParentInNewWindowAction = 0;
    QAction* openParentInNewTabAction = 0;
Peter Penz's avatar
Peter Penz committed
198
    QAction* addToPlacesAction = 0;
199 200
    const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();

201
    if (m_selectedItems.count() == 1) {
202 203
        if (m_fileInfo.isDir()) {
            // setup 'Create New' menu
204
            DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow);
205
            const DolphinView* view = m_mainWindow->activeViewContainer()->view();
206
            newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
207 208
            newFileMenu->checkUpToDate();
            newFileMenu->setPopupFiles(m_fileInfo.url());
209
            newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
210 211
            connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
            connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
212

213
            QMenu* menu = newFileMenu->menu();
214
            menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
215
            menu->setIcon(QIcon::fromTheme("document-new"));
216 217
            addMenu(menu);
            addSeparator();
218 219

            // insert 'Open in new window' and 'Open in new tab' entries
220 221
            addAction(m_mainWindow->actionCollection()->action("open_in_new_window"));
            addAction(m_mainWindow->actionCollection()->action("open_in_new_tab"));
222 223 224

            // insert 'Add to Places' entry
            if (!placeExists(m_fileInfo.url())) {
225
                addToPlacesAction = addAction(QIcon::fromTheme("bookmark-new"),
226 227 228 229
                                                       i18nc("@action:inmenu Add selected folder to places",
                                                             "Add to Places"));
            }

230
            addSeparator();
Lukáš Tinkl's avatar
Lukáš Tinkl committed
231
        } else if (m_baseUrl.scheme().contains("search") || m_baseUrl.scheme().contains("timeline")) {
232 233 234 235 236 237
            openParentAction = new QAction(QIcon::fromTheme("document-open-folder"),
                                           i18nc("@action:inmenu",
                                                 "Open Path"),
                                           this);
            addAction(openParentAction);

238
            openParentInNewWindowAction = new QAction(QIcon::fromTheme("window-new"),
239
                                                    i18nc("@action:inmenu",
240
                                                          "Open Path in New Window"),
241
                                                    this);
242
            addAction(openParentInNewWindowAction);
243

244
            openParentInNewTabAction = new QAction(QIcon::fromTheme("tab-new"),
245
                                                   i18nc("@action:inmenu",
246
                                                         "Open Path in New Tab"),
247
                                                   this);
248
            addAction(openParentInNewTabAction);
249

250 251 252 253 254 255
            addSeparator();
        } else if (!DolphinView::openItemAsFolderUrl(m_fileInfo).isEmpty()) {
            // insert 'Open in new window' and 'Open in new tab' entries
            addAction(m_mainWindow->actionCollection()->action("open_in_new_window"));
            addAction(m_mainWindow->actionCollection()->action("open_in_new_tab"));

256 257 258 259 260
            addSeparator();
        }
    } else {
        bool selectionHasOnlyDirs = true;
        foreach (const KFileItem& item, m_selectedItems) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
261
            const QUrl& url = DolphinView::openItemAsFolderUrl(item);
262
            if (url.isEmpty()) {
263 264 265 266 267 268 269 270
                selectionHasOnlyDirs = false;
                break;
            }
        }

        if (selectionHasOnlyDirs) {
            // insert 'Open in new tab' entry
            addAction(m_mainWindow->actionCollection()->action("open_in_new_tabs"));
271
            addSeparator();
Peter Penz's avatar
Peter Penz committed
272
        }
273
    }
274

275
    insertDefaultItemActions(selectedItemsProps);
276

277
    addSeparator();
278

Peter Penz's avatar
Peter Penz committed
279
    KFileItemActions fileItemActions;
280
    fileItemActions.setItemListProperties(selectedItemsProps);
281
    addServiceActions(fileItemActions);
282

283 284 285
    addFileItemPluginActions();

    addVersionControlPluginActions();
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);
Peter Penz's avatar
Peter Penz committed
293 294
    }

295
    // insert 'Properties...' entry
296
    QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
297
    addAction(propertiesAction);
298

299
    QAction* activatedAction = exec(m_pos);
300
    if (activatedAction) {
301
        if (activatedAction == addToPlacesAction) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
302
            const QUrl selectedUrl(m_fileInfo.url());
303
            if (selectedUrl.isValid()) {
304
                PlacesItemModel model;
305
                const QString text = selectedUrl.fileName();
306
                PlacesItem* item = model.createPlacesItem(text, selectedUrl);
307
                model.appendItemToGroup(item);
308
                model.saveBookmarks();
309
            }
310 311
        } else if (activatedAction == openParentAction) {
            m_command = OpenParentFolder;
312 313 314 315
        } else if (activatedAction == openParentInNewWindowAction) {
            m_command = OpenParentFolderInNewWindow;
        } else if (activatedAction == openParentInNewTabAction) {
            m_command = OpenParentFolderInNewTab;
316 317 318 319
        }
    }
}

320 321 322
void DolphinContextMenu::openViewportContextMenu()
{
    // setup 'Create New' menu
Peter Penz's avatar
Peter Penz committed
323
    KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu();
324
    const DolphinView* view = m_mainWindow->activeViewContainer()->view();
325
    newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
Peter Penz's avatar
Peter Penz committed
326 327
    newFileMenu->checkUpToDate();
    newFileMenu->setPopupFiles(m_baseUrl);
328 329
    addMenu(newFileMenu->menu());
    addSeparator();
Peter Penz's avatar
Peter Penz committed
330

331 332
    // Insert 'New Window' and 'New Tab' entries. Don't use "open_in_new_window" and
    // "open_in_new_tab" here, as the current selection should get ignored.
333 334
    addAction(m_mainWindow->actionCollection()->action("new_window"));
    addAction(m_mainWindow->actionCollection()->action("new_tab"));
335 336 337 338

    // Insert 'Add to Places' entry if exactly one item is selected
    QAction* addToPlacesAction = 0;
    if (!placeExists(m_mainWindow->activeViewContainer()->url())) {
339
        addToPlacesAction = addAction(QIcon::fromTheme("bookmark-new"),
340 341 342
                                             i18nc("@action:inmenu Add current folder to places", "Add to Places"));
    }

343
    addSeparator();
344

345
    QAction* pasteAction = createPasteAction();
346 347
    addAction(pasteAction);
    addSeparator();
348

349 350
    // Insert service actions
    const KFileItemListProperties baseUrlProperties(KFileItemList() << baseFileItem());
Peter Penz's avatar
Peter Penz committed
351 352
    KFileItemActions fileItemActions;
    fileItemActions.setItemListProperties(baseUrlProperties);
353
    addServiceActions(fileItemActions);
354

355 356 357
    addFileItemPluginActions();

    addVersionControlPluginActions();
358

359
    addCustomActions();
360

361
    QAction* propertiesAction = m_mainWindow->actionCollection()->action("properties");
362
    addAction(propertiesAction);
363

364 365
    addShowMenuBarAction();

366
    QAction* action = exec(m_pos);
367
    if (addToPlacesAction && (action == addToPlacesAction)) {
368 369
        const DolphinViewContainer* container =  m_mainWindow->activeViewContainer();
        if (container->url().isValid()) {
370
            PlacesItemModel model;
371 372
            PlacesItem* item = model.createPlacesItem(container->placesText(),
                                                      container->url());
373
            model.appendItemToGroup(item);
374
            model.saveBookmarks();
375 376 377 378
        }
    }
}

379
void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& properties)
380
{
381
    const KActionCollection* collection = m_mainWindow->actionCollection();
382

383
    // Insert 'Cut', 'Copy' and 'Paste'
384 385 386
    addAction(collection->action(KStandardAction::name(KStandardAction::Cut)));
    addAction(collection->action(KStandardAction::name(KStandardAction::Copy)));
    addAction(createPasteAction());
387

388
    addSeparator();
389 390

    // Insert 'Rename'
391
    QAction* renameAction = collection->action("rename");
392
    addAction(renameAction);
393

394
    // Insert 'Move to Trash' and/or 'Delete'
395
    if (properties.supportsDeleting()) {
Laurent Montel's avatar
Laurent Montel committed
396
        const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
                                       !properties.isLocal());
        const bool showMoveToTrashAction = (properties.isLocal() &&
                                            properties.supportsMoving());

        if (showDeleteAction && showMoveToTrashAction) {
            delete m_removeAction;
            m_removeAction = 0;
            addAction(m_mainWindow->actionCollection()->action("move_to_trash"));
            addAction(m_mainWindow->actionCollection()->action("delete"));
        } else if (showDeleteAction && !showMoveToTrashAction) {
            addAction(m_mainWindow->actionCollection()->action("delete"));
        } else {
            if (!m_removeAction) {
                m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
            }
            addAction(m_removeAction);
            m_removeAction->update();
        }
415 416 417
    }
}

418 419 420 421 422
void DolphinContextMenu::addShowMenuBarAction()
{
    const KActionCollection* ac = m_mainWindow->actionCollection();
    QAction* showMenuBar = ac->action(KStandardAction::name(KStandardAction::ShowMenubar));
    if (!m_mainWindow->menuBar()->isVisible() && !m_mainWindow->toolBar()->isVisible()) {
423 424
        addSeparator();
        addAction(showMenuBar);
425 426 427
    }
}

Lukáš Tinkl's avatar
Lukáš Tinkl committed
428
bool DolphinContextMenu::placeExists(const QUrl& url) const
Harsh J Chouraria's avatar
Harsh J Chouraria committed
429
{
430 431 432 433 434
    // Creating up a PlacesItemModel to find out if 'url' is one of the Places
    // can be expensive because the model asks Solid for the devices which are
    // available, which can take some time.
    // TODO: Consider restoring this check if the handling of Places and devices
    // will be decoupled in the future.
Harsh J Chouraria's avatar
Harsh J Chouraria committed
435 436 437
    return false;
}

438 439 440
QAction* DolphinContextMenu::createPasteAction()
{
    QAction* action = 0;
441 442
    const bool isDir = !m_fileInfo.isNull() && m_fileInfo.isDir();
    if (isDir && (m_selectedItems.count() == 1)) {
443 444 445 446 447
        const QMimeData *mimeData = QApplication::clipboard()->mimeData();
        bool canPaste;
        const QString text = KIO::pasteActionText(mimeData, &canPaste, m_fileInfo);
        action = new QAction(QIcon::fromTheme("edit-paste"), text, this);
        action->setEnabled(canPaste);
448
        connect(action, &QAction::triggered, m_mainWindow, &DolphinMainWindow::pasteIntoFolder);
449 450 451 452 453 454 455
    } else {
        action = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
    }

    return action;
}

456
KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
457
{
458
    if (!m_selectedItemsProperties) {
459 460 461 462 463 464
        m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
    }
    return *m_selectedItemsProperties;
}

KFileItem DolphinContextMenu::baseFileItem()
465
{
466
    if (!m_baseFileItem) {
467
        m_baseFileItem = new KFileItem(m_baseUrl);
468
    }
469
    return *m_baseFileItem;
470 471
}

472
void DolphinContextMenu::addServiceActions(KFileItemActions& fileItemActions)
Peter Penz's avatar
Peter Penz committed
473 474 475 476
{
    fileItemActions.setParentWidget(m_mainWindow);

    // insert 'Open With...' action or sub menu
477
    fileItemActions.addOpenWithActionsTo(this, "DesktopEntryName != 'dolphin'");
Peter Penz's avatar
Peter Penz committed
478 479

    // insert 'Actions' sub menu
480
    fileItemActions.addServiceActionsTo(this);
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
}

void DolphinContextMenu::addFileItemPluginActions()
{
    KFileItemListProperties props;
    if (m_selectedItems.isEmpty()) {
        props.setItems(KFileItemList() << baseFileItem());
    } else {
        props = selectedItemsProperties();
    }

    QString commonMimeType = props.mimeType();
    if (commonMimeType.isEmpty()) {
        commonMimeType = QLatin1String("application/octet-stream");
    }

    const KService::List pluginServices = KMimeTypeTrader::self()->query(commonMimeType, "KFileItemAction/Plugin", "exist Library");
    if (pluginServices.isEmpty()) {
        return;
    }

    const KConfig config("kservicemenurc", KConfig::NoGlobals);
    const KConfigGroup showGroup = config.group("Show");

505
    foreach (const KService::Ptr& service, pluginServices) {
506 507 508 509 510
        if (!showGroup.readEntry(service->desktopEntryName(), true)) {
            // The plugin has been disabled
            continue;
        }

511 512
        KAbstractFileItemActionPlugin* abstractPlugin = service->createInstance<KAbstractFileItemActionPlugin>();
        if (abstractPlugin) {
513 514
            abstractPlugin->setParent(this);
            addActions(abstractPlugin->actions(props, m_mainWindow));
515 516
        }
    }
Peter Penz's avatar
Peter Penz committed
517 518
}

519
void DolphinContextMenu::addVersionControlPluginActions()
520 521
{
    const DolphinView* view = m_mainWindow->activeViewContainer()->view();
522 523
    const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
    if (!versionControlActions.isEmpty()) {
524
        addActions(versionControlActions);
525
        addSeparator();
526 527 528
    }
}

529
void DolphinContextMenu::addCustomActions()
530
{
531
    addActions(m_customActions);
532 533
}