summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/cocoa/qnsview_menus.mm
blob: 577f98fa8427eb87509c5c20a8fce072f0257fd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Qt-Security score:significant reason:default

// This file is included from qnsview.mm, and only used to organize the code

#include "qcocoaapplicationdelegate.h"
#include "qcocoansmenu.h"
#include "qcocoamenuitem.h"
#include "qcocoamenu.h"
#include "qcocoamenubar.h"

@implementation QNSView (Menus)

// Qt does not (yet) have a mechanism for propagating generic actions,
// so we can only support actions that originate from a QCocoaNSMenuItem,
// where we can forward the action by emitting QPlatformMenuItem::activated().
// But waiting for forwardInvocation to check that the sender is a
// QCocoaNSMenuItem is too late, as AppKit has at that point chosen
// our view as the target for the action, and if we can't handle it
// the action will not propagate up the responder chain as it should.
// Instead, we hook in early in the process of determining the target
// via the supplementalTargetForAction API, and if we can support the
// action we forward it to a helper. The helper must be tied to the
// view, as the menu validation logic depends on the view's state.

- (id)supplementalTargetForAction:(SEL)action sender:(id)sender
{
    qCDebug(lcQpaMenus) << "Resolving action target for" << action << "from" << sender << "via" << self;

    if (qt_objc_cast<QCocoaNSMenuItem *>(sender)) {
        // The supplemental target must support the selector, but we
        // determine so dynamically, so check here before continuing.
        if ([self.menuHelper respondsToSelector:action])
            return self.menuHelper;
    } else {
        qCDebug(lcQpaMenus) << "Ignoring action for menu item we didn't create";
    }

    return [super supplementalTargetForAction:action sender:sender];
}

#if QT_MACOS_PLATFORM_SDK_EQUAL_OR_ABOVE(150000)
- (void)showContextMenuForSelection:(id)sender
{
    QPointF windowPoint;
    QPointF screenPoint;
    [self convertFromScreen:[NSEvent mouseLocation]
        toWindowPoint:&windowPoint andScreenPoint:&screenPoint];

    auto *keyMapper = QCocoaIntegration::instance()->keyMapper();
    auto keyboardModifiers = keyMapper->queryKeyboardModifiers();

    // We currently propagate this as QContextMenuEvent::Reason::Keyboard,
    // but we can also get here via an accessibility ShowMenu action, in
    // which case QContextMenuEvent::Reason::Other reason might fit better.
    // Unfortunately QWSI/QGuiApplication/QWidgetWindow doesn't handle that
    // yet. FIXME: Teach other parts of Qt about QContextMenuEvent::Other.
    const bool mouseTriggered = false;

    qCDebug(lcQpaMenus) << "Initiating context menu at"
        << windowPoint.toPoint() << "in" << m_platformWindow
        << "with" << keyboardModifiers;

    bool accepted = QWindowSystemInterface::handleContextMenuEvent<
        QWindowSystemInterface::SynchronousDelivery>(
        m_platformWindow->window(), mouseTriggered,
        windowPoint.toPoint(), screenPoint.toPoint(),
        keyboardModifiers);

    qCDebug(lcQpaMenus) << "Context menu event accepted =" << accepted;

    // If the view does not support a context menu we should pass
    // the request up the responder chain.
    if (!accepted)
        [[self nextResponder] tryToPerform:_cmd with:sender];
}
#endif

@end

@interface QNSViewMenuHelper ()
@property (assign) QNSView* view;
@end

@implementation QNSViewMenuHelper

- (instancetype)initWithView:(QNSView *)theView
{
    if ((self = [super init]))
        self.view = theView;

    return self;
}

- (BOOL)validateMenuItem:(NSMenuItem*)item
{
    qCDebug(lcQpaMenus) << "Validating" << item << "for" << self.view;

    auto *nativeItem = qt_objc_cast<QCocoaNSMenuItem *>(item);
    if (!nativeItem)
        return item.enabled; // FIXME Test with with Qt as plugin or embedded QWindow.

    auto *platformItem = nativeItem.platformMenuItem;
    if (!platformItem)
        return NO;

    // Menu-holding items are always enabled, as it's conventional in Cocoa
    if (platformItem->menu())
        return YES;

    // Check if a modal dialog is active. If so, enable only menu
    // items explicitly belonging to this window's own menu bar, or to the window.
    if (QGuiApplication::modalWindow() && QGuiApplication::modalWindow()->isActive()) {
        QCocoaMenuBar *menubar = nullptr;
        QCocoaWindow *menuWindow = nullptr;

        QObject *menuParent = platformItem->menuParent();
        while (menuParent && !(menubar = qobject_cast<QCocoaMenuBar *>(menuParent))) {
            menuWindow = qobject_cast<QCocoaWindow *>(menuParent);
            auto *menuObject = dynamic_cast<QCocoaMenuObject *>(menuParent);
            menuParent = menuObject ? menuObject->menuParent() : nullptr;
        }

        if ((!menuWindow || menuWindow->window() != QGuiApplication::modalWindow())
            && (!menubar || menubar->cocoaWindow() != self.view.platformWindow))
            return NO;
    }

    return platformItem->isEnabled();
}

- (BOOL)respondsToSelector:(SEL)selector
{
    // See QCocoaMenuItem::resolveTargetAction()

    if (selector == @selector(cut:)
     || selector == @selector(copy:)
     || selector == @selector(paste:)
     || selector == @selector(selectAll:)) {
        // Not exactly true. Both copy: and selectAll: can work on non key views.
        return NSApp.keyWindow == self.view.window
            && self.view.window.firstResponder == self.view;
    }

    if (selector == @selector(qt_itemFired:))
        return YES;

    return [super respondsToSelector:selector];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
    // Double check, in case something has cached that we respond
    // to the selector, but the result has changed since then.
    if (![self respondsToSelector:selector])
        return nil;

    auto *appDelegate = [QCocoaApplicationDelegate sharedDelegate];
    return [appDelegate methodSignatureForSelector:@selector(qt_itemFired:)];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    NSObject *sender;
    [invocation getArgument:&sender atIndex:2];
    qCDebug(lcQpaMenus) << "Forwarding" << invocation.selector << "from" << sender;
    Q_ASSERT(qt_objc_cast<QCocoaNSMenuItem *>(sender));
    invocation.selector = @selector(qt_itemFired:);
    [invocation invokeWithTarget:[QCocoaApplicationDelegate sharedDelegate]];
}

@end