Expand font-weight and font-stretch to take any number
[WebKit.git] / Source / WebKit / mac / WebCoreSupport / PopupMenuMac.mm
1 /*
2  * Copyright (C) 2006, 2008, 2010, 2011 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 <WebKitSystemInterface.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 == 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 == LTR ? NSTextAlignmentLeft : NSTextAlignmentRight];
94         NSWritingDirection writingDirection = style.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 overriden 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 == LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
150
151     NSMenu *menu = [m_popup menu];
152 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100
153     [menu setUserInterfaceLayoutDirection:textDirection == LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft];
154 #endif
155
156     NSPoint location;
157     CTFontRef font = m_client->menuStyle().font().primaryFont().getCTFont();
158
159     // These values were borrowed from AppKit to match their placement of the menu.
160     const int popOverHorizontalAdjust = -13;
161     const int popUnderHorizontalAdjust = 6;
162     const int popUnderVerticalAdjust = 6;
163     if (m_client->shouldPopOver()) {
164         NSRect titleFrame = [m_popup titleRectForBounds:r];
165         if (titleFrame.size.width <= 0 || titleFrame.size.height <= 0)
166             titleFrame = r;
167         float vertOffset = roundf((NSMaxY(r) - NSMaxY(titleFrame)) + NSHeight(titleFrame));
168         // Adjust for fonts other than the system font.
169         auto defaultFont = adoptCF(CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, CTFontGetSize(font), nil));
170         vertOffset += CTFontGetDescent(font) - CTFontGetDescent(defaultFont.get());
171         vertOffset = fminf(NSHeight(r), vertOffset);
172 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
173         if (textDirection == LTR)
174             location = NSMakePoint(NSMinX(r) + popOverHorizontalAdjust, NSMaxY(r) - vertOffset);
175         else
176             location = NSMakePoint(NSMinX(r) - popOverHorizontalAdjust, NSMaxY(r) - vertOffset);
177 #else
178         location = NSMakePoint(NSMinX(r) + popOverHorizontalAdjust, NSMaxY(r) - vertOffset);
179 #endif
180     } else
181         location = NSMakePoint(NSMinX(r) + popUnderHorizontalAdjust, NSMaxY(r) + popUnderVerticalAdjust);    
182
183     // Save the current event that triggered the popup, so we can clean up our event
184     // state after the NSMenu goes away.
185     Ref<Frame> frame(v->frame());
186     RetainPtr<NSEvent> event = frame->eventHandler().currentNSEvent();
187     
188     Ref<PopupMenuMac> protector(*this);
189
190     RetainPtr<NSView> dummyView = adoptNS([[NSView alloc] initWithFrame:r]);
191     [view addSubview:dummyView.get()];
192     location = [dummyView convertPoint:location fromView:view];
193     
194     if (Page* page = frame->page()) {
195         WebView* webView = kit(page);
196         BEGIN_BLOCK_OBJC_EXCEPTIONS;
197         CallUIDelegate(webView, @selector(webView:willPopupMenu:), menu);
198         END_BLOCK_OBJC_EXCEPTIONS;
199     }
200
201     NSControlSize controlSize;
202     switch (m_client->menuStyle().menuSize()) {
203     case PopupMenuStyle::PopupMenuSizeNormal:
204         controlSize = NSControlSizeRegular;
205         break;
206     case PopupMenuStyle::PopupMenuSizeSmall:
207         controlSize = NSControlSizeSmall;
208         break;
209     case PopupMenuStyle::PopupMenuSizeMini:
210         controlSize = NSControlSizeMini;
211         break;
212     }
213
214     WKPopupMenu(menu, location, roundf(NSWidth(r)), dummyView.get(), index, toNSFont(font), controlSize, !m_client->menuStyle().hasDefaultAppearance());
215
216     [m_popup dismissPopUp];
217     [dummyView removeFromSuperview];
218
219     if (!m_client)
220         return;
221
222     int newIndex = [m_popup indexOfSelectedItem];
223     m_client->popupDidHide();
224
225     // Adjust newIndex for hidden first item.
226     if (!m_client->shouldPopOver())
227         newIndex--;
228
229     if (index != newIndex && newIndex >= 0)
230         m_client->valueChanged(newIndex);
231
232     // Give the frame a chance to fix up its event state, since the popup eats all the
233     // events during tracking.
234     frame->eventHandler().sendFakeEventsAfterWidgetTracking(event.get());
235 }
236
237 void PopupMenuMac::hide()
238 {
239     [m_popup dismissPopUp];
240 }
241     
242 void PopupMenuMac::updateFromElement()
243 {
244 }
245
246 void PopupMenuMac::disconnectClient()
247 {
248     m_client = 0;
249 }