dolphincontextmenu.cpp 18.8 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
    delete m_selectedItemsProperties;
85
    m_selectedItemsProperties = nullptr;
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(DolphinRemoveAction::ShiftState::Pressed);
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(DolphinRemoveAction::ShiftState::Released);
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(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 152
    addShowMenuBarAction();

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

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

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

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

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

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

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

void DolphinContextMenu::openItemContextMenu()
{
187
    Q_ASSERT(!m_fileInfo.isNull());
188

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

195
    if (m_selectedItems.count() == 1) {
196
        if (m_fileInfo.isLink()) {
197
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("show_target")));
198 199
            addSeparator();
        } else if (m_fileInfo.isDir()) {
200
            // setup 'Create New' menu
201
            DolphinNewFileMenu* newFileMenu = new DolphinNewFileMenu(m_mainWindow->actionCollection(), m_mainWindow);
202
            const DolphinView* view = m_mainWindow->activeViewContainer()->view();
203
            newFileMenu->setViewShowsHiddenFiles(view->hiddenFilesShown());
204 205
            newFileMenu->checkUpToDate();
            newFileMenu->setPopupFiles(m_fileInfo.url());
206
            newFileMenu->setEnabled(selectedItemsProps.supportsWriting());
207 208
            connect(newFileMenu, &DolphinNewFileMenu::fileCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
            connect(newFileMenu, &DolphinNewFileMenu::directoryCreated, newFileMenu, &DolphinNewFileMenu::deleteLater);
209

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

            // insert 'Open in new window' and 'Open in new tab' entries
217 218
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
219 220 221

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

227
            addSeparator();
228 229
        } else if (m_baseUrl.scheme().contains(QStringLiteral("search")) || m_baseUrl.scheme().contains(QStringLiteral("timeline"))) {
            openParentAction = new QAction(QIcon::fromTheme(QStringLiteral("document-open-folder")),
230 231 232 233 234
                                           i18nc("@action:inmenu",
                                                 "Open Path"),
                                           this);
            addAction(openParentAction);

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

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

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

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

        if (selectionHasOnlyDirs) {
            // insert 'Open in new tab' entry
267
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tabs")));
268
            addSeparator();
Peter Penz's avatar
Peter Penz committed
269
        }
270
    }
271

272
    insertDefaultItemActions(selectedItemsProps);
273

274
    addSeparator();
275

Peter Penz's avatar
Peter Penz committed
276
    KFileItemActions fileItemActions;
277
    fileItemActions.setItemListProperties(selectedItemsProps);
278
    addServiceActions(fileItemActions);
279

Elvis Angelaccio's avatar
Elvis Angelaccio committed
280
    fileItemActions.addPluginActionsTo(this);
281 282

    addVersionControlPluginActions();
283

284
    // insert 'Copy To' and 'Move To' sub menus
285
    if (GeneralSettings::showCopyMoveMenu()) {
286
        m_copyToMenu.setUrls(m_selectedItems.urlList());
287
        m_copyToMenu.setReadOnly(!selectedItemsProps.supportsWriting());
288
        m_copyToMenu.setAutoErrorHandlingEnabled(true);
289
        m_copyToMenu.addActionsTo(this);
Peter Penz's avatar
Peter Penz committed
290 291
    }

292
    // insert 'Properties...' entry
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 == addToPlacesAction) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
299
            const QUrl selectedUrl(m_fileInfo.url());
300
            if (selectedUrl.isValid()) {
301
                PlacesItemModel model;
302
                const QString text = selectedUrl.fileName();
303
                model.createPlacesItem(text, selectedUrl, KIO::iconNameForUrl(selectedUrl));
304
            }
305 306
        } else if (activatedAction == openParentAction) {
            m_command = OpenParentFolder;
307 308 309 310
        } else if (activatedAction == openParentInNewWindowAction) {
            m_command = OpenParentFolderInNewWindow;
        } else if (activatedAction == openParentInNewTabAction) {
            m_command = OpenParentFolderInNewTab;
311 312 313 314
        }
    }
}

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

326 327
    // 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.
328 329
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("new_window")));
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("new_tab")));
330 331

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

338
    addSeparator();
339

340
    QAction* pasteAction = createPasteAction();
341 342
    addAction(pasteAction);
    addSeparator();
343

344 345
    // Insert service actions
    const KFileItemListProperties baseUrlProperties(KFileItemList() << baseFileItem());
Peter Penz's avatar
Peter Penz committed
346 347
    KFileItemActions fileItemActions;
    fileItemActions.setItemListProperties(baseUrlProperties);
348
    addServiceActions(fileItemActions);
349

Elvis Angelaccio's avatar
Elvis Angelaccio committed
350
    fileItemActions.addPluginActionsTo(this);
351 352

    addVersionControlPluginActions();
353

354
    addCustomActions();
355

356
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
357
    addAction(propertiesAction);
358

359 360
    addShowMenuBarAction();

361
    QAction* action = exec(m_pos);
362
    if (addToPlacesAction && (action == addToPlacesAction)) {
363
        const DolphinViewContainer* container =  m_mainWindow->activeViewContainer();
364 365
        const QUrl url = container->url();
        if (url.isValid()) {
366
            PlacesItemModel model;
367 368 369 370 371 372
            QString icon;
            if (container->isSearchModeEnabled()) {
                icon = QStringLiteral("folder-saved-search-symbolic");
            } else {
                icon = KIO::iconNameForUrl(url);
            }
373
            model.createPlacesItem(container->placesText(), url, icon);
374 375 376 377
        }
    }
}

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

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

387
    addSeparator();
388 389

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

392
    // Insert 'Move to Trash' and/or 'Delete'
393
    if (properties.supportsDeleting()) {
Laurent Montel's avatar
Laurent Montel committed
394
        const bool showDeleteAction = (KSharedConfig::openConfig()->group("KDE").readEntry("ShowDeleteCommand", false) ||
395 396 397 398 399 400
                                       !properties.isLocal());
        const bool showMoveToTrashAction = (properties.isLocal() &&
                                            properties.supportsMoving());

        if (showDeleteAction && showMoveToTrashAction) {
            delete m_removeAction;
Kevin Funk's avatar
Kevin Funk committed
401
            m_removeAction = nullptr;
402
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::MoveToTrash)));
403
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
404
        } else if (showDeleteAction && !showMoveToTrashAction) {
405
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
406 407 408 409 410 411 412
        } else {
            if (!m_removeAction) {
                m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
            }
            addAction(m_removeAction);
            m_removeAction->update();
        }
413 414 415
    }
}

416 417 418 419 420
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()) {
421 422
        addSeparator();
        addAction(showMenuBar);
423 424 425
    }
}

Lukáš Tinkl's avatar
Lukáš Tinkl committed
426
bool DolphinContextMenu::placeExists(const QUrl& url) const
Harsh J Chouraria's avatar
Harsh J Chouraria committed
427
{
Roman Inflianskas's avatar
Roman Inflianskas committed
428
    Q_UNUSED(url)
429 430 431 432 433
    // 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
434 435 436
    return false;
}

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

    return action;
}

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

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

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

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

    // insert 'Actions' sub menu
479
    fileItemActions.addServiceActionsTo(this);
480 481 482
}

void DolphinContextMenu::addVersionControlPluginActions()
483 484
{
    const DolphinView* view = m_mainWindow->activeViewContainer()->view();
485 486
    const QList<QAction*> versionControlActions = view->versionControlActions(m_selectedItems);
    if (!versionControlActions.isEmpty()) {
487
        addActions(versionControlActions);
488
        addSeparator();
489 490 491
    }
}

492
void DolphinContextMenu::addCustomActions()
493
{
494
    addActions(m_customActions);
495 496
}