dolphincontextmenu.cpp 19.6 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"

Roman Inflianskas's avatar
Roman Inflianskas committed
23
#include "dolphin_generalsettings.h"
Peter Penz's avatar
Peter Penz committed
24
#include "dolphinmainwindow.h"
Peter Penz's avatar
Peter Penz committed
25
#include "dolphinnewfilemenu.h"
26
#include "dolphinremoveaction.h"
Roman Inflianskas's avatar
Roman Inflianskas committed
27 28 29
#include "dolphinviewcontainer.h"
#include "panels/places/placesitem.h"
#include "panels/places/placesitemmodel.h"
30
#include "trash/dolphintrash.h"
Roman Inflianskas's avatar
Roman Inflianskas committed
31 32
#include "views/dolphinview.h"
#include "views/viewmodecontroller.h"
Peter Penz's avatar
Peter Penz committed
33

34
#include <KAbstractFileItemActionPlugin>
Roman Inflianskas's avatar
Roman Inflianskas committed
35
#include <KActionCollection>
36 37
#include <KFileItemActions>
#include <KFileItemListProperties>
38 39
#include <KIO/EmptyTrashJob>
#include <KIO/JobUiDelegate>
40
#include <KIO/Paste>
Roman Inflianskas's avatar
Roman Inflianskas committed
41
#include <KIO/RestoreJob>
42
#include <KJobWidgets>
Roman Inflianskas's avatar
Roman Inflianskas committed
43
#include <KLocalizedString>
44
#include <KMimeTypeTrader>
45
#include <KNewFileMenu>
46
#include <KPluginMetaData>
47 48
#include <KService>
#include <KStandardAction>
49
#include <KToolBar>
50

51 52
#include <QApplication>
#include <QClipboard>
David Faure's avatar
David Faure committed
53
#include <QKeyEvent>
54
#include <QMenu>
Roman Inflianskas's avatar
Roman Inflianskas committed
55
#include <QMenuBar>
56
#include <QMimeDatabase>
57

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),
Kevin Funk's avatar
Kevin Funk committed
67
    m_baseFileItem(nullptr),
68
    m_selectedItems(),
69
    m_selectedItemsProperties(nullptr),
70
    m_context(NoContext),
71
    m_copyToMenu(parent),
72
    m_customActions(),
73
    m_command(None),
Kevin Funk's avatar
Kevin Funk committed
74
    m_removeAction(nullptr)
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_baseFileItem;
    m_baseFileItem = nullptr;
86
    delete m_selectedItemsProperties;
87
    m_selectedItemsProperties = nullptr;
Peter Penz's avatar
Peter Penz committed
88
}
89

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

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

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

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

    return m_command;
122 123
}

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

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

140 141 142 143
void DolphinContextMenu::openTrashContextMenu()
{
    Q_ASSERT(m_context & TrashContext);

144
    QAction* emptyTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"), this);
145
    emptyTrashAction->setEnabled(!Trash::isEmpty());
146
    addAction(emptyTrashAction);
147

148
    addCustomActions();
149

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

153 154
    addShowMenuBarAction();

155
    if (exec(m_pos) == emptyTrashAction) {
156
        Trash::empty(m_mainWindow);
157 158 159 160 161 162 163 164
    }
}

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

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

168
    QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile));
169
    addAction(deleteAction);
170

171
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
172
    addAction(propertiesAction);
173

174
    if (exec(m_pos) == restoreAction) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
175
        QList<QUrl> selectedUrls;
176
        selectedUrls.reserve(m_selectedItems.count());
177 178 179 180
        foreach (const KFileItem &item, m_selectedItems) {
            selectedUrls.append(item.url());
        }

181 182 183
        KIO::RestoreJob *job = KIO::restoreFromTrash(selectedUrls);
        KJobWidgets::setWindow(job, m_mainWindow);
        job->uiDelegate()->setAutoErrorHandlingEnabled(true);
184 185 186 187 188
    }
}

void DolphinContextMenu::openItemContextMenu()
{
189
    Q_ASSERT(!m_fileInfo.isNull());
190

191 192 193 194
    QAction* openParentAction = nullptr;
    QAction* openParentInNewWindowAction = nullptr;
    QAction* openParentInNewTabAction = nullptr;
    QAction* addToPlacesAction = nullptr;
195 196
    const KFileItemListProperties& selectedItemsProps = selectedItemsProperties();

197 198 199 200
    KFileItemActions fileItemActions;
    fileItemActions.setParentWidget(m_mainWindow);
    fileItemActions.setItemListProperties(selectedItemsProps);

201
    if (m_selectedItems.count() == 1) {
202
        if (m_fileInfo.isDir()) {
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
            // insert 'Open in new window' and 'Open in new tab' entries
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));

            // Insert 'Open With' entries
            addOpenWithActions(fileItemActions);

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

            addSeparator();

            // set up 'Create New' menu
220
            DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow);
221
            const DolphinView* view = m_mainWindow->activeViewContainer()->view();
222
            newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
223 224
            newFileMenu->checkUpToDate();
            newFileMenu->setPopupFiles(m_fileInfo.url());
225
            newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
226 227
            connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
            connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
228

229
            QMenu* menu = newFileMenu->menu();
230
            menu->setTitle(i18nc("@title:menu Create new folder, file, link, etc.", "Create New"));
231
            menu->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
232
            addMenu(menu);
233

234
            addSeparator();
235
        } else if (m_baseUrl.scheme().contains(QStringLiteral("search")) || m_baseUrl.scheme().contains(QStringLiteral("timeline"))) {
236 237
            addOpenWithActions(fileItemActions);

238
            openParentAction = new QAction(QIcon::fromTheme(QStringLiteral("document-open-folder")),
239 240 241 242 243
                                           i18nc("@action:inmenu",
                                                 "Open Path"),
                                           this);
            addAction(openParentAction);

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

250
            openParentInNewTabAction = new QAction(QIcon::fromTheme(QStringLiteral("tab-new")),
251
                                                   i18nc("@action:inmenu",
252
                                                         "Open Path in New Tab"),
253
                                                   this);
254
            addAction(openParentInNewTabAction);
255

256 257
            addSeparator();
        } else if (!DolphinView::openItemAsFolderUrl(m_fileInfo).isEmpty()) {
258 259 260
            // Insert 'Open With" entries
            addOpenWithActions(fileItemActions);

261
            // insert 'Open in new window' and 'Open in new tab' entries
262 263
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
264

265 266 267 268 269 270 271
            addSeparator();
        } else {
            // Insert 'Open With" entries
            addOpenWithActions(fileItemActions);
        }
        if (m_fileInfo.isLink()) {
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("show_target")));
272 273 274 275 276
            addSeparator();
        }
    } else {
        bool selectionHasOnlyDirs = true;
        foreach (const KFileItem& item, m_selectedItems) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
277
            const QUrl& url = DolphinView::openItemAsFolderUrl(item);
278
            if (url.isEmpty()) {
279 280 281 282 283 284 285
                selectionHasOnlyDirs = false;
                break;
            }
        }

        if (selectionHasOnlyDirs) {
            // insert 'Open in new tab' entry
286
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tabs")));
Peter Penz's avatar
Peter Penz committed
287
        }
288 289
        // Insert 'Open With" entries
        addOpenWithActions(fileItemActions);
290
    }
291

292
    insertDefaultItemActions(selectedItemsProps);
293

294
    addSeparator();
295

296
    fileItemActions.addServiceActionsTo(this);
Elvis Angelaccio's avatar
Elvis Angelaccio committed
297
    fileItemActions.addPluginActionsTo(this);
298 299

    addVersionControlPluginActions();
300

301
    // insert 'Copy To' and 'Move To' sub menus
302
    if (GeneralSettings::showCopyMoveMenu()) {
303
        m_copyToMenu.setUrls(m_selectedItems.urlList());
304
        m_copyToMenu.setReadOnly(!selectedItemsProps.supportsWriting());
305
        m_copyToMenu.setAutoErrorHandlingEnabled(true);
306
        m_copyToMenu.addActionsTo(this);
Peter Penz's avatar
Peter Penz committed
307 308
    }

309
    // insert 'Properties...' entry
310
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
311
    addAction(propertiesAction);
312

313
    QAction* activatedAction = exec(m_pos);
314
    if (activatedAction) {
315
        if (activatedAction == addToPlacesAction) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
316
            const QUrl selectedUrl(m_fileInfo.url());
317
            if (selectedUrl.isValid()) {
318
                PlacesItemModel model;
319
                const QString text = selectedUrl.fileName();
320
                model.createPlacesItem(text, selectedUrl, KIO::iconNameForUrl(selectedUrl));
321
            }
322 323
        } else if (activatedAction == openParentAction) {
            m_command = OpenParentFolder;
324 325 326 327
        } else if (activatedAction == openParentInNewWindowAction) {
            m_command = OpenParentFolderInNewWindow;
        } else if (activatedAction == openParentInNewTabAction) {
            m_command = OpenParentFolderInNewTab;
328 329 330 331
        }
    }
}

332 333 334
void DolphinContextMenu::openViewportContextMenu()
{
    // setup 'Create New' menu
Peter Penz's avatar
Peter Penz committed
335
    KNewFileMenu* newFileMenu = m_mainWindow->newFileMenu();
336
    const DolphinView* view = m_mainWindow->activeViewContainer()->view();
337
    newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
Peter Penz's avatar
Peter Penz committed
338 339
    newFileMenu->checkUpToDate();
    newFileMenu->setPopupFiles(m_baseUrl);
340 341
    addMenu(newFileMenu->menu());
    addSeparator();
Peter Penz's avatar
Peter Penz committed
342

343 344 345 346 347 348 349
    // Insert 'Open With' entries
    const KFileItemListProperties baseUrlProperties(KFileItemList() << baseFileItem());
    KFileItemActions fileItemActions;
    fileItemActions.setParentWidget(m_mainWindow);
    fileItemActions.setItemListProperties(baseUrlProperties);
    addOpenWithActions(fileItemActions);

350 351
    // 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.
352
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("file_new")));
353
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("new_tab")));
354 355

    // Insert 'Add to Places' entry if exactly one item is selected
Kevin Funk's avatar
Kevin Funk committed
356
    QAction* addToPlacesAction = nullptr;
357
    if (!placeExists(m_mainWindow->activeViewContainer()->url())) {
358
        addToPlacesAction = addAction(QIcon::fromTheme(QStringLiteral("bookmark-new")),
359 360 361
                                             i18nc("@action:inmenu Add current folder to places", "Add to Places"));
    }

362
    addSeparator();
363

364
    QAction* pasteAction = createPasteAction();
365 366
    addAction(pasteAction);
    addSeparator();
367

368 369 370 371 372 373
    // Insert 'Sort By' and 'View Mode'
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("sort")));
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("view_mode")));

    addSeparator();

374
    // Insert service actions
375
    fileItemActions.addServiceActionsTo(this);
Elvis Angelaccio's avatar
Elvis Angelaccio committed
376
    fileItemActions.addPluginActionsTo(this);
377 378

    addVersionControlPluginActions();
379

380
    addCustomActions();
381

382
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
383
    addAction(propertiesAction);
384

385 386
    addShowMenuBarAction();

387
    QAction* action = exec(m_pos);
388
    if (addToPlacesAction && (action == addToPlacesAction)) {
389
        const DolphinViewContainer* container =  m_mainWindow->activeViewContainer();
390 391
        const QUrl url = container->url();
        if (url.isValid()) {
392
            PlacesItemModel model;
393 394 395 396 397 398
            QString icon;
            if (container->isSearchModeEnabled()) {
                icon = QStringLiteral("folder-saved-search-symbolic");
            } else {
                icon = KIO::iconNameForUrl(url);
            }
399
            model.createPlacesItem(container->placesText(), url, icon);
400 401 402 403
        }
    }
}

404
void DolphinContextMenu::insertDefaultItemActions(const KFileItemListProperties& properties)
405
{
406
    const KActionCollection* collection = m_mainWindow->actionCollection();
407

408
    // Insert 'Cut', 'Copy' and 'Paste'
409 410 411
    addAction(collection->action(KStandardAction::name(KStandardAction::Cut)));
    addAction(collection->action(KStandardAction::name(KStandardAction::Copy)));
    addAction(createPasteAction());
412

413
    addSeparator();
414 415

    // Insert 'Rename'
416
    addAction(collection->action(KStandardAction::name(KStandardAction::RenameFile)));
417

418
    // Insert 'Move to Trash' and/or 'Delete'
419
    if (properties.supportsDeleting()) {
Laurent Montel's avatar
Laurent Montel committed
420
        const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
421 422 423 424 425 426
                                       !properties.isLocal());
        const bool showMoveToTrashAction = (properties.isLocal() &&
                                            properties.supportsMoving());

        if (showDeleteAction && showMoveToTrashAction) {
            delete m_removeAction;
Kevin Funk's avatar
Kevin Funk committed
427
            m_removeAction = nullptr;
428
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)));
429
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
430
        } else if (showDeleteAction && !showMoveToTrashAction) {
431
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
432 433 434 435 436 437 438
        } else {
            if (!m_removeAction) {
                m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
            }
            addAction(m_removeAction);
            m_removeAction->update();
        }
439 440 441
    }
}

442 443 444 445 446
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()) {
447 448
        addSeparator();
        addAction(showMenuBar);
449 450 451
    }
}

Lukáš Tinkl's avatar
Lukáš Tinkl committed
452
bool DolphinContextMenu::placeExists(const QUrl& url) const
Harsh J Chouraria's avatar
Harsh J Chouraria committed
453
{
Roman Inflianskas's avatar
Roman Inflianskas committed
454
    Q_UNUSED(url)
455 456 457 458 459
    // 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
460 461 462
    return false;
}

463 464
QAction* DolphinContextMenu::createPasteAction()
{
Kevin Funk's avatar
Kevin Funk committed
465
    QAction* action = nullptr;
466 467
    const bool isDir = !m_fileInfo.isNull() && m_fileInfo.isDir();
    if (isDir && (m_selectedItems.count() == 1)) {
468 469 470
        const QMimeData *mimeData = QApplication::clipboard()->mimeData();
        bool canPaste;
        const QString text = KIO::pasteActionText(mimeData, &canPaste, m_fileInfo);
471
        action = new QAction(QIcon::fromTheme(QStringLiteral("edit-paste")), text, this);
472
        action->setEnabled(canPaste);
473
        connect(action, &QAction::triggered, m_mainWindow, &DolphinMainWindow::pasteIntoFolder);
474 475 476 477 478 479 480
    } else {
        action = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::Paste));
    }

    return action;
}

481
KFileItemListProperties& DolphinContextMenu::selectedItemsProperties() const
482
{
483
    if (!m_selectedItemsProperties) {
484 485 486 487 488 489
        m_selectedItemsProperties = new KFileItemListProperties(m_selectedItems);
    }
    return *m_selectedItemsProperties;
}

KFileItem DolphinContextMenu::baseFileItem()
490
{
491
    if (!m_baseFileItem) {
492
        m_baseFileItem = new KFileItem(m_baseUrl);
493
    }
494
    return *m_baseFileItem;
495 496
}

497
void DolphinContextMenu::addOpenWithActions(KFileItemActions& fileItemActions)
Peter Penz's avatar
Peter Penz committed
498 499
{
    // insert 'Open With...' action or sub menu
500
    fileItemActions.addOpenWithActionsTo(this, QStringLiteral("DesktopEntryName != '%1'").arg(qApp->desktopFileName()));
501 502 503
}

void DolphinContextMenu::addVersionControlPluginActions()
504 505
{
    const DolphinView* view = m_mainWindow->activeViewContainer()->view();
506 507
    const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
    if (!versionControlActions.isEmpty()) {
508
        addActions(versionControlActions);
509
        addSeparator();
510 511 512
    }
}

513
void DolphinContextMenu::addCustomActions()
514
{
515
    addActions(m_customActions);
516 517
}