dolphincontextmenu.cpp 19 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 <KPluginMetaData>
41
#include <KService>
Laurent Montel's avatar
Laurent Montel committed
42
#include <KLocalizedString>
43
#include <KStandardAction>
44
#include <KToolBar>
45

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

53 54 55
#include <panels/places/placesitem.h>
#include <panels/places/placesitemmodel.h>

56

57 58 59
#include "views/dolphinview.h"
#include "views/viewmodecontroller.h"

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

84
DolphinContextMenu::~DolphinContextMenu()
Peter Penz's avatar
Peter Penz committed
85
{
86 87
    delete m_selectedItemsProperties;
    m_selectedItemsProperties = 0;
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();
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();
136
    }
137
    QMenu::keyReleaseEvent(ev);
138 139
}

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

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

149
    addCustomActions();
150

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

154 155
    addShowMenuBarAction();

156
    if (exec(m_pos) == emptyTrashAction) {
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);
162
            job->uiDelegate()->setAutoErrorHandlingEnabled(true);
163
        }
164 165 166 167 168 169 170 171
    }
}

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

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

175
    QAction* deleteAction = m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile));
176
    addAction(deleteAction);
177

178
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
179
    addAction(propertiesAction);
180

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

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

void DolphinContextMenu::openItemContextMenu()
{
196
    Q_ASSERT(!m_fileInfo.isNull());
197

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

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

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

            // insert 'Open in new window' and 'Open in new tab' entries
223 224
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_window")));
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("open_in_new_tab")));
225 226 227

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

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

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

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

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

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

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

278
    insertDefaultItemActions(selectedItemsProps);
279

280
    addSeparator();
281

Peter Penz's avatar
Peter Penz committed
282
    KFileItemActions fileItemActions;
283
    fileItemActions.setItemListProperties(selectedItemsProps);
284
    addServiceActions(fileItemActions);
285

Elvis Angelaccio's avatar
Elvis Angelaccio committed
286
    fileItemActions.addPluginActionsTo(this);
287 288

    addVersionControlPluginActions();
289

290
    // insert 'Copy To' and 'Move To' sub menus
291
    if (GeneralSettings::showCopyMoveMenu()) {
292
        m_copyToMenu.setUrls(m_selectedItems.urlList());
293
        m_copyToMenu.setReadOnly(!selectedItemsProps.supportsWriting());
294
        m_copyToMenu.setAutoErrorHandlingEnabled(true);
295
        m_copyToMenu.addActionsTo(this);
Peter Penz's avatar
Peter Penz committed
296 297
    }

298
    // insert 'Properties...' entry
299
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
300
    addAction(propertiesAction);
301

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

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

334 335
    // 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.
336 337
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("new_window")));
    addAction(m_mainWindow->actionCollection()->action(QStringLiteral("new_tab")));
338 339 340 341

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

346
    addSeparator();
347

348
    QAction* pasteAction = createPasteAction();
349 350
    addAction(pasteAction);
    addSeparator();
351

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

Elvis Angelaccio's avatar
Elvis Angelaccio committed
358
    fileItemActions.addPluginActionsTo(this);
359 360

    addVersionControlPluginActions();
361

362
    addCustomActions();
363

364
    QAction* propertiesAction = m_mainWindow->actionCollection()->action(QStringLiteral("properties"));
365
    addAction(propertiesAction);
366

367 368
    addShowMenuBarAction();

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

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

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

392
    addSeparator();
393 394

    // Insert 'Rename'
395
    QAction* renameAction = collection->action(QStringLiteral("rename"));
396
    addAction(renameAction);
397

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

        if (showDeleteAction && showMoveToTrashAction) {
            delete m_removeAction;
            m_removeAction = 0;
408
            addAction(m_mainWindow->actionCollection()->action(QStringLiteral("move_to_trash")));
409
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
410
        } else if (showDeleteAction && !showMoveToTrashAction) {
411
            addAction(m_mainWindow->actionCollection()->action(KStandardAction::name(KStandardAction::DeleteFile)));
412 413 414 415 416 417 418
        } else {
            if (!m_removeAction) {
                m_removeAction = new DolphinRemoveAction(this, m_mainWindow->actionCollection());
            }
            addAction(m_removeAction);
            m_removeAction->update();
        }
419 420 421
    }
}

422 423 424 425 426
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()) {
427 428
        addSeparator();
        addAction(showMenuBar);
429 430 431
    }
}

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

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

    return action;
}

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

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

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

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

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

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

497
void DolphinContextMenu::addCustomActions()
498
{
499
    addActions(m_customActions);
500 501
}