dolphincontextmenu.cpp 19.1 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 30 31
#include "dolphinviewcontainer.h"
#include "panels/places/placesitem.h"
#include "panels/places/placesitemmodel.h"
#include "views/dolphinview.h"
#include "views/viewmodecontroller.h"
Peter Penz's avatar
Peter Penz committed
32

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

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

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

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

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

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

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

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

    return m_command;
119 120
}

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

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

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

141 142
    QAction* emptyTrashAction = new QAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"), this);
    KConfig trashConfig(QStringLiteral("trashrc"), KConfig::SimpleConfig);
143
    emptyTrashAction->setEnabled(!trashConfig.group("Status").readEntry("Empty", true));
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 155 156 157 158
        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);
159
            job->uiDelegate()->setAutoErrorHandlingEnabled(true);
160
        }
161 162 163 164 165 166 167 168
    }
}

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

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

172
    QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile));
173
    addAction(deleteAction);
174

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

178
    if (exec(m_pos) == restoreAction) {
Lukáš Tinkl's avatar
Lukáš Tinkl committed
179
        QList<QUrl> selectedUrls;
180
        selectedUrls.reserve(m_selectedItems.count());
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 196 197 198
    QAction* openParentAction = nullptr;
    QAction* openParentInNewWindowAction = nullptr;
    QAction* openParentInNewTabAction = nullptr;
    QAction* addToPlacesAction = nullptr;
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(QStringLiteral("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(QStringLiteral("open_in_new_window")));
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
222 223 224

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

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

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

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

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

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
                selectionHasOnlyDirs = false;
                break;
            }
        }

        if (selectionHasOnlyDirs) {
            // insert 'Open in new tab' entry
270
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("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

Elvis Angelaccio's avatar
Elvis Angelaccio committed
283
    fileItemActions.addPluginActionsTo(this);
284 285

    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(QStringLiteral("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
                model.createPlacesItem(text, selectedUrl, KIO::iconNameForUrl(selectedUrl));
307
            }
308 309
        } else if (activatedAction == openParentAction) {
            m_command = OpenParentFolder;
310 311 312 313
        } else if (activatedAction == openParentInNewWindowAction) {
            m_command = OpenParentFolderInNewWindow;
        } else if (activatedAction == openParentInNewTabAction) {
            m_command = OpenParentFolderInNewTab;
314 315 316 317
        }
    }
}

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

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

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

341
    addSeparator();
342

343
    QAction* pasteAction = createPasteAction();
344 345
    addAction(pasteAction);
    addSeparator();
346

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

Elvis Angelaccio's avatar
Elvis Angelaccio committed
353
    fileItemActions.addPluginActionsTo(this);
354 355

    addVersionControlPluginActions();
356

357
    addCustomActions();
358

359
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
360
    addAction(propertiesAction);
361

362 363
    addShowMenuBarAction();

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

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

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

390
    addSeparator();
391 392

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

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

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

419 420 421 422 423
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()) {
424 425
        addSeparator();
        addAction(showMenuBar);
426 427 428
    }
}

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

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

    return action;
}

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

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

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

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

    // insert 'Actions' sub menu
482
    fileItemActions.addServiceActionsTo(this);
483 484 485
}

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

495
void DolphinContextMenu::addCustomActions()
496
{
497
    addActions(m_customActions);
498 499
}