[macOS] Select element doesn't show popup if select element had lost focus while...
[WebKit-https.git] / Source / WebKit / UIProcess / mac / WebPopupMenuProxyMac.mm
1 /*
2  * Copyright (C) 2010-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WebPopupMenuProxyMac.h"
28
29 #if USE(APPKIT)
30
31 #import "NativeWebMouseEvent.h"
32 #import "PageClientImplMac.h"
33 #import "PlatformPopupMenuData.h"
34 #import "StringUtilities.h"
35 #import "WebPopupItem.h"
36 #import <pal/system/mac/PopupMenu.h>
37 #import <wtf/ProcessPrivilege.h>
38
39 namespace WebKit {
40 using namespace WebCore;
41
42 WebPopupMenuProxyMac::WebPopupMenuProxyMac(NSView *webView, WebPopupMenuProxy::Client& client)
43     : WebPopupMenuProxy(client)
44     , m_webView(webView)
45     , m_wasCanceled(false)
46 {
47 }
48
49 WebPopupMenuProxyMac::~WebPopupMenuProxyMac()
50 {
51     if (m_popup)
52         [m_popup setControlView:nil];
53 }
54
55 void WebPopupMenuProxyMac::populate(const Vector<WebPopupItem>& items, NSFont *font, TextDirection menuTextDirection)
56 {
57     if (m_popup)
58         [m_popup removeAllItems];
59     else {
60         m_popup = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]);
61         [m_popup setUsesItemFromMenu:NO];
62         [m_popup setAutoenablesItems:NO];
63     }
64
65     int size = items.size();
66
67     for (int i = 0; i < size; i++) {
68         if (items[i].m_type == WebPopupItem::Separator)
69             [[m_popup menu] addItem:[NSMenuItem separatorItem]];
70         else {
71             [m_popup addItemWithTitle:@""];
72             NSMenuItem *menuItem = [m_popup lastItem];
73
74             RetainPtr<NSMutableParagraphStyle> paragraphStyle = adoptNS([[NSParagraphStyle defaultParagraphStyle] mutableCopy]);
75             NSWritingDirection writingDirection = items[i].m_textDirection == TextDirection::LTR ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft;
76             [paragraphStyle setBaseWritingDirection:writingDirection];
77             [paragraphStyle setAlignment:menuTextDirection == TextDirection::LTR ? NSTextAlignmentLeft : NSTextAlignmentRight];
78             RetainPtr<NSMutableDictionary> attributes = adoptNS([[NSMutableDictionary alloc] initWithObjectsAndKeys:
79                 paragraphStyle.get(), NSParagraphStyleAttributeName,
80                 font, NSFontAttributeName,
81             nil]);
82             if (items[i].m_hasTextDirectionOverride) {
83                 RetainPtr<NSNumber> writingDirectionValue = adoptNS([[NSNumber alloc] initWithInteger:writingDirection + NSWritingDirectionOverride]);
84                 RetainPtr<NSArray> writingDirectionArray = adoptNS([[NSArray alloc] initWithObjects:writingDirectionValue.get(), nil]);
85                 [attributes setObject:writingDirectionArray.get() forKey:NSWritingDirectionAttributeName];
86             }
87             RetainPtr<NSAttributedString> string = adoptNS([[NSAttributedString alloc] initWithString:nsStringFromWebCoreString(items[i].m_text) attributes:attributes.get()]);
88
89             [menuItem setAttributedTitle:string.get()];
90             // We set the title as well as the attributed title here. The attributed title will be displayed in the menu,
91             // but typeahead will use the non-attributed string that doesn't contain any leading or trailing whitespace.
92             [menuItem setTitle:[[string string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
93             [menuItem setEnabled:items[i].m_isEnabled];
94             [menuItem setToolTip:nsStringFromWebCoreString(items[i].m_toolTip)];
95         }
96     }
97 }
98
99 void WebPopupMenuProxyMac::showPopupMenu(const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, const PlatformPopupMenuData& data, int32_t selectedIndex)
100 {
101     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanCommunicateWithWindowServer));
102     NSFont *font;
103     if (data.fontInfo.fontAttributeDictionary) {
104         NSFontDescriptor *fontDescriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:(__bridge NSDictionary *)data.fontInfo.fontAttributeDictionary.get()];
105         font = [NSFont fontWithDescriptor:fontDescriptor size:((pageScaleFactor != 1) ? [fontDescriptor pointSize] * pageScaleFactor : 0)];
106     } else
107         font = [NSFont menuFontOfSize:0];
108
109     populate(items, font, textDirection);
110
111     [m_popup attachPopUpWithFrame:rect inView:m_webView];
112     [m_popup selectItemAtIndex:selectedIndex];
113     [m_popup setUserInterfaceLayoutDirection:textDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
114
115     NSMenu *menu = [m_popup menu];
116     [menu setUserInterfaceLayoutDirection:textDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
117
118     // These values were borrowed from AppKit to match their placement of the menu.
119     const int popOverHorizontalAdjust = -13;
120     const int popUnderHorizontalAdjust = 6;
121     const int popUnderVerticalAdjust = 6;
122     
123     // Menus that pop-over directly obscure the node that generated the popup menu.
124     // Menus that pop-under are offset underneath it.
125     NSPoint location;
126     if (data.shouldPopOver) {
127         NSRect titleFrame = [m_popup  titleRectForBounds:rect];
128         if (titleFrame.size.width <= 0 || titleFrame.size.height <= 0)
129             titleFrame = rect;
130         float verticalOffset = roundf((NSMaxY(rect) - NSMaxY(titleFrame)) + NSHeight(titleFrame)) + 1;
131         if (textDirection == TextDirection::LTR)
132             location = NSMakePoint(NSMinX(rect) + popOverHorizontalAdjust, NSMaxY(rect) - verticalOffset);
133         else
134             location = NSMakePoint(NSMaxX(rect) - popOverHorizontalAdjust, NSMaxY(rect) - verticalOffset);
135     } else {
136         if (textDirection == TextDirection::LTR)
137             location = NSMakePoint(NSMinX(rect) + popUnderHorizontalAdjust, NSMaxY(rect) + popUnderVerticalAdjust);
138         else
139             location = NSMakePoint(NSMaxX(rect) - popUnderHorizontalAdjust, NSMaxY(rect) + popUnderVerticalAdjust);
140     }
141     RetainPtr<NSView> dummyView = adoptNS([[NSView alloc] initWithFrame:rect]);
142     [dummyView.get() setUserInterfaceLayoutDirection:textDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
143     [m_webView addSubview:dummyView.get()];
144     location = [dummyView convertPoint:location fromView:m_webView];
145
146     NSControlSize controlSize;
147     switch (data.menuSize) {
148     case WebCore::PopupMenuStyle::PopupMenuSizeNormal:
149         controlSize = NSControlSizeRegular;
150         break;
151     case WebCore::PopupMenuStyle::PopupMenuSizeSmall:
152         controlSize = NSControlSizeSmall;
153         break;
154     case WebCore::PopupMenuStyle::PopupMenuSizeMini:
155         controlSize = NSControlSizeMini;
156         break;
157     }
158
159     Ref<WebPopupMenuProxyMac> protect(*this);
160     PAL::popUpMenu(menu, location, roundf(NSWidth(rect)), dummyView.get(), selectedIndex, font, controlSize, data.hideArrows);
161
162     [m_popup dismissPopUp];
163     [dummyView removeFromSuperview];
164     
165     if (!m_client || m_wasCanceled)
166         return;
167     
168     m_client->valueChangedForPopupMenu(this, [m_popup indexOfSelectedItem]);
169     
170     // <https://bugs.webkit.org/show_bug.cgi?id=57904> This code is adopted from EventHandler::sendFakeEventsAfterWidgetTracking().
171     if (!m_client->currentlyProcessedMouseDownEvent())
172         return;
173     
174     NSEvent* initiatingNSEvent = m_client->currentlyProcessedMouseDownEvent()->nativeEvent();
175     if ([initiatingNSEvent type] != NSEventTypeLeftMouseDown)
176         return;
177
178     NSEvent *fakeEvent = [NSEvent mouseEventWithType:NSEventTypeLeftMouseUp
179                                             location:[initiatingNSEvent locationInWindow]
180                                        modifierFlags:[initiatingNSEvent modifierFlags]
181                                            timestamp:[initiatingNSEvent timestamp]
182                                         windowNumber:[initiatingNSEvent windowNumber]
183                                              context:nullptr
184                                          eventNumber:[initiatingNSEvent eventNumber]
185                                           clickCount:[initiatingNSEvent clickCount]
186                                             pressure:[initiatingNSEvent pressure]];
187
188     [NSApp postEvent:fakeEvent atStart:YES];
189     fakeEvent = [NSEvent mouseEventWithType:NSEventTypeMouseMoved
190                                    location:[[m_webView window]
191 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
192                         convertScreenToBase:[NSEvent mouseLocation]]
193 ALLOW_DEPRECATED_DECLARATIONS_END
194                               modifierFlags:[initiatingNSEvent modifierFlags]
195                                   timestamp:[initiatingNSEvent timestamp]
196                                windowNumber:[initiatingNSEvent windowNumber]
197                                     context:nullptr
198                                 eventNumber:0
199                                  clickCount:0
200                                    pressure:0];
201     [NSApp postEvent:fakeEvent atStart:YES];
202 }
203
204 void WebPopupMenuProxyMac::hidePopupMenu()
205 {
206     [[m_popup menu] cancelTracking];
207 }
208
209 void WebPopupMenuProxyMac::cancelTracking()
210 {
211     [[m_popup menu] cancelTracking];
212     m_wasCanceled = true;
213 }
214
215 } // namespace WebKit
216
217 #endif // USE(APPKIT)