Use a 1-byte enum class for TextDirection
[WebKit-https.git] / Source / WebKitLegacy / mac / WebCoreSupport / PopupMenuMac.mm
1 /*
2  * Copyright (C) 2006-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #import "PopupMenuMac.h"
22
23 #import "WebDelegateImplementationCaching.h"
24 #import "WebFrameInternal.h"
25 #import <WebCore/IntRect.h>
26 #import <WebCore/AXObjectCache.h>
27 #import <WebCore/Chrome.h>
28 #import <WebCore/ChromeClient.h>
29 #import <WebCore/EventHandler.h>
30 #import <WebCore/Font.h>
31 #import <WebCore/Frame.h>
32 #import <WebCore/FrameView.h>
33 #import <WebCore/Page.h>
34 #import <WebCore/PopupMenuClient.h>
35 #import <pal/system/mac/PopupMenu.h>
36 #import <wtf/BlockObjCExceptions.h>
37
38 using namespace WebCore;
39
40 PopupMenuMac::PopupMenuMac(PopupMenuClient* client)
41     : m_client(client)
42 {
43 }
44
45 PopupMenuMac::~PopupMenuMac()
46 {
47     [m_popup setControlView:nil];
48 }
49
50 void PopupMenuMac::clear()
51 {
52     [m_popup removeAllItems];
53 }
54
55 void PopupMenuMac::populate()
56 {
57     if (m_popup)
58         clear();
59     else {
60         m_popup = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:!m_client->shouldPopOver()]);
61         [m_popup setUsesItemFromMenu:NO];
62         [m_popup setAutoenablesItems:NO];
63     }
64     
65     // For pullDown menus the first item is hidden.
66     if (!m_client->shouldPopOver())
67         [m_popup addItemWithTitle:@""];
68
69     TextDirection menuTextDirection = m_client->menuStyle().textDirection();
70     [m_popup setUserInterfaceLayoutDirection:menuTextDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
71
72     ASSERT(m_client);
73     int size = m_client->listSize();
74
75     for (int i = 0; i < size; i++) {
76         if (m_client->itemIsSeparator(i)) {
77             [[m_popup menu] addItem:[NSMenuItem separatorItem]];
78             continue;
79         }
80
81         PopupMenuStyle style = m_client->itemStyle(i);
82         RetainPtr<NSMutableDictionary> attributes = adoptNS([[NSMutableDictionary alloc] init]);
83         if (style.font() != FontCascade()) {
84             RetainPtr<CTFontRef> font = style.font().primaryFont().getCTFont();
85             if (!font) {
86                 CGFloat size = style.font().primaryFont().platformData().size();
87                 font = adoptCF(CTFontCreateUIFontForLanguage(isFontWeightBold(style.font().weight()) ? kCTFontUIFontEmphasizedSystem : kCTFontUIFontSystem, size, nullptr));
88             }
89             [attributes setObject:toNSFont(font.get()) forKey:NSFontAttributeName];
90         }
91
92         RetainPtr<NSMutableParagraphStyle> paragraphStyle = adoptNS([[NSParagraphStyle defaultParagraphStyle] mutableCopy]);
93         [paragraphStyle setAlignment:menuTextDirection == TextDirection::LTR ? NSTextAlignmentLeft : NSTextAlignmentRight];
94         NSWritingDirection writingDirection = style.textDirection() == TextDirection::LTR ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft;
95         [paragraphStyle setBaseWritingDirection:writingDirection];
96         if (style.hasTextDirectionOverride()) {
97             RetainPtr<NSNumber> writingDirectionValue = adoptNS([[NSNumber alloc] initWithInteger:writingDirection + NSWritingDirectionOverride]);
98             RetainPtr<NSArray> writingDirectionArray = adoptNS([[NSArray alloc] initWithObjects:writingDirectionValue.get(), nil]);
99             [attributes setObject:writingDirectionArray.get() forKey:NSWritingDirectionAttributeName];
100         }
101         [attributes setObject:paragraphStyle.get() forKey:NSParagraphStyleAttributeName];
102
103         // FIXME: Add support for styling the foreground and background colors.
104         // FIXME: Find a way to customize text color when an item is highlighted.
105         RetainPtr<NSAttributedString> string = adoptNS([[NSAttributedString alloc] initWithString:m_client->itemText(i) attributes:attributes.get()]);
106
107         [m_popup addItemWithTitle:@""];
108         NSMenuItem *menuItem = [m_popup lastItem];
109         [menuItem setAttributedTitle:string.get()];
110         // We set the title as well as the attributed title here. The attributed title will be displayed in the menu,
111         // but typeahead will use the non-attributed string that doesn't contain any leading or trailing whitespace.
112         [menuItem setTitle:[[string string] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
113         [menuItem setEnabled:m_client->itemIsEnabled(i)];
114         [menuItem setToolTip:m_client->itemToolTip(i)];
115
116 #pragma clang diagnostic push
117 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
118         // Allow the accessible text of the item to be overridden if necessary.
119         if (AXObjectCache::accessibilityEnabled()) {
120             NSString *accessibilityOverride = m_client->itemAccessibilityText(i);
121             if ([accessibilityOverride length])
122                 [menuItem accessibilitySetOverrideValue:accessibilityOverride forAttribute:NSAccessibilityDescriptionAttribute];
123         }
124 #pragma clang diagnostic pop
125     }
126 }
127
128 void PopupMenuMac::show(const IntRect& r, FrameView* v, int index)
129 {
130     populate();
131     int numItems = [m_popup numberOfItems];
132     if (numItems <= 0) {
133         if (m_client)
134             m_client->popupDidHide();
135         return;
136     }
137     ASSERT(numItems > index);
138
139     // Workaround for crazy bug where a selected index of -1 for a menu with only 1 item will cause a blank menu.
140     if (index == -1 && numItems == 2 && !m_client->shouldPopOver() && ![[m_popup itemAtIndex:1] isEnabled])
141         index = 0;
142
143     NSView* view = v->documentView();
144
145     TextDirection textDirection = m_client->menuStyle().textDirection();
146
147     [m_popup attachPopUpWithFrame:r inView:view];
148     [m_popup selectItemAtIndex:index];
149     [m_popup setUserInterfaceLayoutDirection:textDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
150
151     NSMenu *menu = [m_popup menu];
152     [menu setUserInterfaceLayoutDirection:textDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
153
154     NSPoint location;
155     CTFontRef font = m_client->menuStyle().font().primaryFont().getCTFont();
156
157     // These values were borrowed from AppKit to match their placement of the menu.
158     const int popOverHorizontalAdjust = -13;
159     const int popUnderHorizontalAdjust = 6;
160     const int popUnderVerticalAdjust = 6;
161     if (m_client->shouldPopOver()) {
162         NSRect titleFrame = [m_popup titleRectForBounds:r];
163         if (titleFrame.size.width <= 0 || titleFrame.size.height <= 0)
164             titleFrame = r;
165         float vertOffset = roundf((NSMaxY(r) - NSMaxY(titleFrame)) + NSHeight(titleFrame));
166         // Adjust for fonts other than the system font.
167         auto defaultFont = adoptCF(CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, CTFontGetSize(font), nil));
168         vertOffset += CTFontGetDescent(font) - CTFontGetDescent(defaultFont.get());
169         vertOffset = fminf(NSHeight(r), vertOffset);
170 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
171         if (textDirection == TextDirection::LTR)
172             location = NSMakePoint(NSMinX(r) + popOverHorizontalAdjust, NSMaxY(r) - vertOffset);
173         else
174             location = NSMakePoint(NSMaxX(r) - popOverHorizontalAdjust, NSMaxY(r) - vertOffset);
175 #else
176         location = NSMakePoint(NSMinX(r) + popOverHorizontalAdjust, NSMaxY(r) - vertOffset);
177 #endif
178     } else {
179 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
180         if (textDirection == TextDirection::LTR)
181             location = NSMakePoint(NSMinX(r) + popUnderHorizontalAdjust, NSMaxY(r) + popUnderVerticalAdjust);
182         else
183             location = NSMakePoint(NSMaxX(r) - popUnderHorizontalAdjust, NSMaxY(r) + popUnderVerticalAdjust);
184 #else
185         location = NSMakePoint(NSMinX(r) + popUnderHorizontalAdjust, NSMaxY(r) + popUnderVerticalAdjust);
186 #endif
187     }
188     // Save the current event that triggered the popup, so we can clean up our event
189     // state after the NSMenu goes away.
190     Ref<Frame> frame(v->frame());
191     RetainPtr<NSEvent> event = frame->eventHandler().currentNSEvent();
192     
193     Ref<PopupMenuMac> protector(*this);
194
195     RetainPtr<NSView> dummyView = adoptNS([[NSView alloc] initWithFrame:r]);
196     [dummyView.get() setUserInterfaceLayoutDirection:textDirection == TextDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
197     [view addSubview:dummyView.get()];
198     location = [dummyView convertPoint:location fromView:view];
199     
200     if (Page* page = frame->page()) {
201         WebView* webView = kit(page);
202         BEGIN_BLOCK_OBJC_EXCEPTIONS;
203         CallUIDelegate(webView, @selector(webView:willPopupMenu:), menu);
204         END_BLOCK_OBJC_EXCEPTIONS;
205     }
206
207     NSControlSize controlSize;
208     switch (m_client->menuStyle().menuSize()) {
209     case PopupMenuStyle::PopupMenuSizeNormal:
210         controlSize = NSControlSizeRegular;
211         break;
212     case PopupMenuStyle::PopupMenuSizeSmall:
213         controlSize = NSControlSizeSmall;
214         break;
215     case PopupMenuStyle::PopupMenuSizeMini:
216         controlSize = NSControlSizeMini;
217         break;
218     }
219
220     PAL::popUpMenu(menu, location, roundf(NSWidth(r)), dummyView.get(), index, toNSFont(font), controlSize, !m_client->menuStyle().hasDefaultAppearance());
221
222     [m_popup dismissPopUp];
223     [dummyView removeFromSuperview];
224
225     if (!m_client)
226         return;
227
228     int newIndex = [m_popup indexOfSelectedItem];
229     m_client->popupDidHide();
230
231     // Adjust newIndex for hidden first item.
232     if (!m_client->shouldPopOver())
233         newIndex--;
234
235     if (index != newIndex && newIndex >= 0)
236         m_client->valueChanged(newIndex);
237
238     // Give the frame a chance to fix up its event state, since the popup eats all the
239     // events during tracking.
240     frame->eventHandler().sendFakeEventsAfterWidgetTracking(event.get());
241 }
242
243 void PopupMenuMac::hide()
244 {
245     [m_popup dismissPopUp];
246 }
247     
248 void PopupMenuMac::updateFromElement()
249 {
250 }
251
252 void PopupMenuMac::disconnectClient()
253 {
254     m_client = 0;
255 }