Source/WebCore/rendering/RenderThemeMac.mm:2181:118: error: null passed to a callee...
[WebKit-https.git] / Source / WebCore / rendering / RenderThemeMac.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public License
15  * along with this library; see the file COPYING.LIB.  If not, write to
16  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19 #if !PLATFORM(IOS)
20
21 #import "config.h"
22 #import "RenderThemeMac.h"
23
24 #import "BitmapImage.h"
25 #import "CSSValueKeywords.h"
26 #import "CSSValueList.h"
27 #import "ColorMac.h"
28 #import "CoreGraphicsSPI.h"
29 #import "Document.h"
30 #import "Element.h"
31 #import "ExceptionCodePlaceholder.h"
32 #import "FileList.h"
33 #import "FloatRoundedRect.h"
34 #import "FocusController.h"
35 #import "Frame.h"
36 #import "FrameSelection.h"
37 #import "FrameView.h"
38 #import "GraphicsContextCG.h"
39 #import "HTMLAttachmentElement.h"
40 #import "HTMLAudioElement.h"
41 #import "HTMLInputElement.h"
42 #import "HTMLMediaElement.h"
43 #import "HTMLNames.h"
44 #import "HTMLPlugInImageElement.h"
45 #import "Icon.h"
46 #import "Image.h"
47 #import "ImageBuffer.h"
48 #import "LocalCurrentGraphicsContext.h"
49 #import "LocalizedStrings.h"
50 #import "MediaControlElements.h"
51 #import "NSSharingServicePickerSPI.h"
52 #import "Page.h"
53 #import "PaintInfo.h"
54 #import "RenderAttachment.h"
55 #import "RenderLayer.h"
56 #import "RenderMedia.h"
57 #import "RenderMediaControlElements.h"
58 #import "RenderMediaControls.h"
59 #import "RenderProgress.h"
60 #import "RenderSlider.h"
61 #import "RenderSnapshottedPlugIn.h"
62 #import "RenderView.h"
63 #import "SharedBuffer.h"
64 #import "StringTruncator.h"
65 #import "StyleResolver.h"
66 #import "ThemeMac.h"
67 #import "TimeRanges.h"
68 #import "UserAgentScripts.h"
69 #import "UserAgentStyleSheets.h"
70 #import "WebCoreSystemInterface.h"
71 #import <wtf/RetainPtr.h>
72 #import <wtf/RetainPtr.h>
73 #import <wtf/StdLibExtras.h>
74 #import <wtf/text/StringBuilder.h>
75 #import <Carbon/Carbon.h>
76 #import <Cocoa/Cocoa.h>
77 #import <math.h>
78
79 #if ENABLE(METER_ELEMENT)
80 #import "RenderMeter.h"
81 #import "HTMLMeterElement.h"
82 #endif
83
84 #if defined(__LP64__) && __LP64__
85 #define HAVE_APPKIT_SERVICE_CONTROLS_SUPPORT 1
86 #else
87 #define HAVE_APPKIT_SERVICE_CONTROLS_SUPPORT 0
88 #endif
89
90 #if ENABLE(SERVICE_CONTROLS) && HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
91
92 #if __has_include(<AppKit/AppKitDefines_Private.h>)
93 #import <AppKit/AppKitDefines_Private.h>
94 #else
95 #define APPKIT_PRIVATE_CLASS
96 #endif
97
98 #if __has_include(<AppKit/NSServicesRolloverButtonCell.h>)
99 #import <AppKit/NSServicesRolloverButtonCell.h>
100 #else
101 @interface NSServicesRolloverButtonCell : NSButtonCell
102 @end
103 #endif
104
105 @interface NSServicesRolloverButtonCell (Details)
106 + (NSServicesRolloverButtonCell *)serviceRolloverButtonCellForStyle:(NSSharingServicePickerStyle)style;
107 - (NSRect)rectForBounds:(NSRect)bounds preferredEdge:(NSRectEdge)preferredEdge;
108 @end
109
110 #endif // ENABLE(SERVICE_CONTROLS)
111
112 // The methods in this file are specific to the Mac OS X platform.
113
114 // FIXME: The platform-independent code in this class should be factored out and merged with RenderThemeSafari.
115
116 // We estimate the animation rate of a Mac OS X progress bar is 33 fps.
117 // Hard code the value here because we haven't found API for it.
118 const double progressAnimationFrameRate = 0.033;
119
120 // Mac OS X progress bar animation seems to have 256 frames.
121 const double progressAnimationNumFrames = 256;
122
123 @interface WebCoreRenderThemeNotificationObserver : NSObject
124 {
125     WebCore::RenderTheme *_theme;
126 }
127
128 - (id)initWithTheme:(WebCore::RenderTheme *)theme;
129 - (void)systemColorsDidChange:(NSNotification *)notification;
130
131 @end
132
133 @implementation WebCoreRenderThemeNotificationObserver
134
135 - (id)initWithTheme:(WebCore::RenderTheme *)theme
136 {
137     if (!(self = [super init]))
138         return nil;
139
140     _theme = theme;
141     return self;
142 }
143
144 - (void)systemColorsDidChange:(NSNotification *)unusedNotification
145 {
146     ASSERT_UNUSED(unusedNotification, [[unusedNotification name] isEqualToString:NSSystemColorsDidChangeNotification]);
147     _theme->platformColorsDidChange();
148 }
149
150 @end
151
152 @interface NSTextFieldCell (WKDetails)
153 - (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame inView:(NSView *)controlView includeFocus:(BOOL)includeFocus;
154 @end
155
156
157 @interface WebCoreTextFieldCell : NSTextFieldCell
158 - (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame inView:(NSView *)controlView includeFocus:(BOOL)includeFocus;
159 @end
160
161 @implementation WebCoreTextFieldCell
162 - (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame inView:(NSView *)controlView includeFocus:(BOOL)includeFocus
163 {
164     // FIXME: This is a post-Lion-only workaround for <rdar://problem/11385461>. When that bug is resolved, we should remove this code.
165     CFMutableDictionaryRef coreUIDrawOptions = CFDictionaryCreateMutableCopy(NULL, 0, [super _coreUIDrawOptionsWithFrame:cellFrame inView:controlView includeFocus:includeFocus]);
166     CFDictionarySetValue(coreUIDrawOptions, @"borders only", kCFBooleanTrue);
167     return (CFDictionaryRef)[NSMakeCollectable(coreUIDrawOptions) autorelease];
168 }
169 @end
170
171 @interface WebCoreRenderThemeBundle : NSObject
172 @end
173
174 @implementation WebCoreRenderThemeBundle
175 @end
176
177 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
178 @interface NSSearchFieldCell(Details)
179 @property (getter=isCenteredLook) BOOL centeredLook;
180 @end
181 #endif
182
183 namespace WebCore {
184
185 using namespace HTMLNames;
186
187 enum {
188     topMargin,
189     rightMargin,
190     bottomMargin,
191     leftMargin
192 };
193
194 enum {
195     topPadding,
196     rightPadding,
197     bottomPadding,
198     leftPadding
199 };
200
201 PassRefPtr<RenderTheme> RenderTheme::themeForPage(Page*)
202 {
203     static RenderTheme* rt = RenderThemeMac::create().leakRef();
204     return rt;
205 }
206
207 PassRefPtr<RenderTheme> RenderThemeMac::create()
208 {
209     return adoptRef(new RenderThemeMac);
210 }
211
212 RenderThemeMac::RenderThemeMac()
213     : m_isSliderThumbHorizontalPressed(false)
214     , m_isSliderThumbVerticalPressed(false)
215     , m_notificationObserver(adoptNS([[WebCoreRenderThemeNotificationObserver alloc] initWithTheme:this]))
216 {
217     [[NSNotificationCenter defaultCenter] addObserver:m_notificationObserver.get()
218                                                         selector:@selector(systemColorsDidChange:)
219                                                             name:NSSystemColorsDidChangeNotification
220                                                           object:nil];
221 }
222
223 RenderThemeMac::~RenderThemeMac()
224 {
225     [[NSNotificationCenter defaultCenter] removeObserver:m_notificationObserver.get()];
226 }
227
228 NSView* RenderThemeMac::documentViewFor(const RenderObject& o) const
229 {
230     ControlStates states(extractControlStatesForRenderer(o));
231     return ThemeMac::ensuredView(&o.view().frameView(), &states);
232 }
233
234 #if ENABLE(VIDEO)
235 String RenderThemeMac::mediaControlsStyleSheet()
236 {
237 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
238     if (m_mediaControlsStyleSheet.isEmpty())
239         m_mediaControlsStyleSheet = [NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsApple" ofType:@"css"] encoding:NSUTF8StringEncoding error:nil];
240     return m_mediaControlsStyleSheet;
241 #else
242     return emptyString();
243 #endif
244 }
245
246 String RenderThemeMac::mediaControlsScript()
247 {
248 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
249     if (m_mediaControlsScript.isEmpty()) {
250         StringBuilder scriptBuilder;
251         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsLocalizedStrings" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
252         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsApple" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
253         m_mediaControlsScript = scriptBuilder.toString();
254     }
255     return m_mediaControlsScript;
256 #else
257     return emptyString();
258 #endif
259 }
260
261 #endif // ENABLE(VIDEO)
262
263
264 #if ENABLE(SERVICE_CONTROLS)
265 String RenderThemeMac::imageControlsStyleSheet() const
266 {
267     return String(imageControlsMacUserAgentStyleSheet, sizeof(imageControlsMacUserAgentStyleSheet));
268 }
269 #endif
270
271 Color RenderThemeMac::platformActiveSelectionBackgroundColor() const
272 {
273     NSColor* color = [[NSColor selectedTextBackgroundColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
274     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
275 }
276
277 Color RenderThemeMac::platformInactiveSelectionBackgroundColor() const
278 {
279     NSColor* color = [[NSColor secondarySelectedControlColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
280     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
281 }
282
283 Color RenderThemeMac::platformActiveListBoxSelectionBackgroundColor() const
284 {
285     NSColor* color = [[NSColor alternateSelectedControlColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
286     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
287 }
288
289 Color RenderThemeMac::platformActiveListBoxSelectionForegroundColor() const
290 {
291     return Color::white;
292 }
293
294 Color RenderThemeMac::platformInactiveListBoxSelectionForegroundColor() const
295 {
296     return Color::black;
297 }
298
299 Color RenderThemeMac::platformFocusRingColor() const
300 {
301     if (usesTestModeFocusRingColor())
302         return oldAquaFocusRingColor();
303
304     return systemColor(CSSValueWebkitFocusRingColor);
305 }
306
307 int RenderThemeMac::platformFocusRingMaxWidth() const
308 {
309     // FIXME: Shouldn't this function be named platformFocusRingMinWidth? But also, I'm not sure if this function is needed - looks like
310     // all platforms just used 0 for this before <http://trac.webkit.org/changeset/168397>.
311     return 0;
312 }
313
314 Color RenderThemeMac::platformInactiveListBoxSelectionBackgroundColor() const
315 {
316     return platformInactiveSelectionBackgroundColor();
317 }
318
319 static FontWeight toFontWeight(NSInteger appKitFontWeight)
320 {
321     ASSERT(appKitFontWeight > 0 && appKitFontWeight < 15);
322     if (appKitFontWeight > 14)
323         appKitFontWeight = 14;
324     else if (appKitFontWeight < 1)
325         appKitFontWeight = 1;
326
327     static FontWeight fontWeights[] = {
328         FontWeight100,
329         FontWeight100,
330         FontWeight200,
331         FontWeight300,
332         FontWeight400,
333         FontWeight500,
334         FontWeight600,
335         FontWeight600,
336         FontWeight700,
337         FontWeight800,
338         FontWeight800,
339         FontWeight900,
340         FontWeight900,
341         FontWeight900
342     };
343     return fontWeights[appKitFontWeight - 1];
344 }
345
346 void RenderThemeMac::updateCachedSystemFontDescription(CSSValueID cssValueId, FontDescription& fontDescription) const
347 {
348     NSFont* font;
349     switch (cssValueId) {
350         case CSSValueSmallCaption:
351             font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
352             break;
353         case CSSValueMenu:
354             font = [NSFont menuFontOfSize:[NSFont systemFontSize]];
355             break;
356         case CSSValueStatusBar:
357             font = [NSFont labelFontOfSize:[NSFont labelFontSize]];
358             break;
359         case CSSValueWebkitMiniControl:
360             font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSMiniControlSize]];
361             break;
362         case CSSValueWebkitSmallControl:
363             font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
364             break;
365         case CSSValueWebkitControl:
366             font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSRegularControlSize]];
367             break;
368         default:
369             font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
370     }
371
372     if (!font)
373         return;
374
375     NSFontManager *fontManager = [NSFontManager sharedFontManager];
376     fontDescription.setIsAbsoluteSize(true);
377     fontDescription.setOneFamily([font webCoreFamilyName]);
378     fontDescription.setSpecifiedSize([font pointSize]);
379     fontDescription.setWeight(toFontWeight([fontManager weightOfFont:font]));
380     fontDescription.setIsItalic([fontManager traitsOfFont:font] & NSItalicFontMask);
381 }
382
383 static RGBA32 convertNSColorToColor(NSColor *color)
384 {
385     NSColor *colorInColorSpace = [color colorUsingColorSpaceName:NSDeviceRGBColorSpace];
386     if (colorInColorSpace) {
387         static const double scaleFactor = nextafter(256.0, 0.0);
388         return makeRGB(static_cast<int>(scaleFactor * [colorInColorSpace redComponent]),
389             static_cast<int>(scaleFactor * [colorInColorSpace greenComponent]),
390             static_cast<int>(scaleFactor * [colorInColorSpace blueComponent]));
391     }
392
393     // This conversion above can fail if the NSColor in question is an NSPatternColor
394     // (as many system colors are). These colors are actually a repeating pattern
395     // not just a solid color. To work around this we simply draw a 1x1 image of
396     // the color and use that pixel's color. It might be better to use an average of
397     // the colors in the pattern instead.
398     NSBitmapImageRep *offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
399                                                                              pixelsWide:1
400                                                                              pixelsHigh:1
401                                                                           bitsPerSample:8
402                                                                         samplesPerPixel:4
403                                                                                hasAlpha:YES
404                                                                                isPlanar:NO
405                                                                          colorSpaceName:NSDeviceRGBColorSpace
406                                                                             bytesPerRow:4
407                                                                            bitsPerPixel:32];
408
409     [NSGraphicsContext saveGraphicsState];
410     [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]];
411     NSEraseRect(NSMakeRect(0, 0, 1, 1));
412     [color drawSwatchInRect:NSMakeRect(0, 0, 1, 1)];
413     [NSGraphicsContext restoreGraphicsState];
414
415     NSUInteger pixel[4];
416     [offscreenRep getPixel:pixel atX:0 y:0];
417
418     [offscreenRep release];
419
420     return makeRGB(pixel[0], pixel[1], pixel[2]);
421 }
422
423 static RGBA32 menuBackgroundColor()
424 {
425     NSBitmapImageRep *offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
426                                                                              pixelsWide:1
427                                                                              pixelsHigh:1
428                                                                           bitsPerSample:8
429                                                                         samplesPerPixel:4
430                                                                                hasAlpha:YES
431                                                                                isPlanar:NO
432                                                                          colorSpaceName:NSDeviceRGBColorSpace
433                                                                             bytesPerRow:4
434                                                                            bitsPerPixel:32];
435
436     CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep] graphicsPort]);
437     CGRect rect = CGRectMake(0, 0, 1, 1);
438     HIThemeMenuDrawInfo drawInfo;
439     drawInfo.version =  0;
440     drawInfo.menuType = kThemeMenuTypePopUp;
441     HIThemeDrawMenuBackground(&rect, &drawInfo, context, kHIThemeOrientationInverted);
442
443     NSUInteger pixel[4];
444     [offscreenRep getPixel:pixel atX:0 y:0];
445
446     [offscreenRep release];
447
448     return makeRGB(pixel[0], pixel[1], pixel[2]);
449 }
450
451 void RenderThemeMac::platformColorsDidChange()
452 {
453     m_systemColorCache.clear();
454     RenderTheme::platformColorsDidChange();
455 }
456
457 Color RenderThemeMac::systemColor(CSSValueID cssValueId) const
458 {
459     {
460         HashMap<int, RGBA32>::iterator it = m_systemColorCache.find(cssValueId);
461         if (it != m_systemColorCache.end())
462             return it->value;
463     }
464
465     Color color;
466     switch (cssValueId) {
467     case CSSValueActiveborder:
468         color = convertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
469         break;
470     case CSSValueActivecaption:
471         color = convertNSColorToColor([NSColor windowFrameTextColor]);
472         break;
473     case CSSValueAppworkspace:
474         color = convertNSColorToColor([NSColor headerColor]);
475         break;
476     case CSSValueBackground:
477         // Use theme independent default
478         break;
479     case CSSValueButtonface:
480         // We use this value instead of NSColor's controlColor to avoid website incompatibilities.
481         // We may want to change this to use the NSColor in future.
482         color = 0xFFC0C0C0;
483         break;
484     case CSSValueButtonhighlight:
485         color = convertNSColorToColor([NSColor controlHighlightColor]);
486         break;
487     case CSSValueButtonshadow:
488         color = convertNSColorToColor([NSColor controlShadowColor]);
489         break;
490     case CSSValueButtontext:
491         color = convertNSColorToColor([NSColor controlTextColor]);
492         break;
493     case CSSValueActivebuttontext:
494 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
495         color = 0xC0FFFFFF;
496 #endif
497         break;
498     case CSSValueCaptiontext:
499         color = convertNSColorToColor([NSColor textColor]);
500         break;
501     case CSSValueGraytext:
502         color = convertNSColorToColor([NSColor disabledControlTextColor]);
503         break;
504     case CSSValueHighlight:
505         color = convertNSColorToColor([NSColor selectedTextBackgroundColor]);
506         break;
507     case CSSValueHighlighttext:
508         color = convertNSColorToColor([NSColor selectedTextColor]);
509         break;
510     case CSSValueInactiveborder:
511         color = convertNSColorToColor([NSColor controlBackgroundColor]);
512         break;
513     case CSSValueInactivecaption:
514         color = convertNSColorToColor([NSColor controlBackgroundColor]);
515         break;
516     case CSSValueInactivecaptiontext:
517         color = convertNSColorToColor([NSColor textColor]);
518         break;
519     case CSSValueInfobackground:
520         // There is no corresponding NSColor for this so we use a hard coded value.
521         color = 0xFFFBFCC5;
522         break;
523     case CSSValueInfotext:
524         color = convertNSColorToColor([NSColor textColor]);
525         break;
526     case CSSValueMenu:
527         color = menuBackgroundColor();
528         break;
529     case CSSValueMenutext:
530         color = convertNSColorToColor([NSColor selectedMenuItemTextColor]);
531         break;
532     case CSSValueScrollbar:
533         color = convertNSColorToColor([NSColor scrollBarColor]);
534         break;
535     case CSSValueText:
536         color = convertNSColorToColor([NSColor textColor]);
537         break;
538     case CSSValueThreeddarkshadow:
539         color = convertNSColorToColor([NSColor controlDarkShadowColor]);
540         break;
541     case CSSValueThreedshadow:
542         color = convertNSColorToColor([NSColor shadowColor]);
543         break;
544     case CSSValueThreedface:
545         // We use this value instead of NSColor's controlColor to avoid website incompatibilities.
546         // We may want to change this to use the NSColor in future.
547         color = 0xFFC0C0C0;
548         break;
549     case CSSValueThreedhighlight:
550         color = convertNSColorToColor([NSColor highlightColor]);
551         break;
552     case CSSValueThreedlightshadow:
553         color = convertNSColorToColor([NSColor controlLightHighlightColor]);
554         break;
555     case CSSValueWebkitFocusRingColor:
556         color = convertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
557         break;
558     case CSSValueWindow:
559         color = convertNSColorToColor([NSColor windowBackgroundColor]);
560         break;
561     case CSSValueWindowframe:
562         color = convertNSColorToColor([NSColor windowFrameColor]);
563         break;
564     case CSSValueWindowtext:
565         color = convertNSColorToColor([NSColor windowFrameTextColor]);
566         break;
567     default:
568         break;
569     }
570
571     if (!color.isValid())
572         color = RenderTheme::systemColor(cssValueId);
573
574     if (color.isValid())
575         m_systemColorCache.set(cssValueId, color.rgb());
576
577     return color;
578 }
579
580 bool RenderThemeMac::usesTestModeFocusRingColor() const
581 {
582     return WebCore::usesTestModeFocusRingColor();
583 }
584
585 bool RenderThemeMac::isControlStyled(const RenderStyle& style, const BorderData& border,
586                                      const FillLayer& background, const Color& backgroundColor) const
587 {
588     if (style.appearance() == TextFieldPart || style.appearance() == TextAreaPart || style.appearance() == ListboxPart)
589         return style.border() != border;
590
591     // FIXME: This is horrible, but there is not much else that can be done.  Menu lists cannot draw properly when
592     // scaled.  They can't really draw properly when transformed either.  We can't detect the transform case at style
593     // adjustment time so that will just have to stay broken.  We can however detect that we're zooming.  If zooming
594     // is in effect we treat it like the control is styled.
595     if (style.appearance() == MenulistPart && style.effectiveZoom() != 1.0f)
596         return true;
597
598     return RenderTheme::isControlStyled(style, border, background, backgroundColor);
599 }
600
601 static FloatRect inflateRect(const FloatRect& rect, const IntSize& size, const int* margins, float zoomLevel)
602 {
603     // Only do the inflation if the available width/height are too small. Otherwise try to
604     // fit the glow/check space into the available box's width/height.
605     int widthDelta = rect.width() - (size.width() + margins[leftMargin] * zoomLevel + margins[rightMargin] * zoomLevel);
606     int heightDelta = rect.height() - (size.height() + margins[topMargin] * zoomLevel + margins[bottomMargin] * zoomLevel);
607     FloatRect result(rect);
608     if (widthDelta < 0) {
609         result.setX(result.x() - margins[leftMargin] * zoomLevel);
610         result.setWidth(result.width() - widthDelta);
611     }
612     if (heightDelta < 0) {
613         result.setY(result.y() - margins[topMargin] * zoomLevel);
614         result.setHeight(result.height() - heightDelta);
615     }
616     return result;
617 }
618
619 void RenderThemeMac::adjustRepaintRect(const RenderObject& renderer, FloatRect& rect)
620 {
621     ControlPart part = renderer.style().appearance();
622
623 #if USE(NEW_THEME)
624     switch (part) {
625         case CheckboxPart:
626         case RadioPart:
627         case PushButtonPart:
628         case SquareButtonPart:
629         case DefaultButtonPart:
630         case ButtonPart:
631         case InnerSpinButtonPart:
632             return RenderTheme::adjustRepaintRect(renderer, rect);
633         default:
634             break;
635     }
636 #endif
637
638     float zoomLevel = renderer.style().effectiveZoom();
639
640     if (part == MenulistPart) {
641         setPopupButtonCellState(renderer, IntSize(rect.size()));
642         IntSize size = popupButtonSizes()[[popupButton() controlSize]];
643         size.setHeight(size.height() * zoomLevel);
644         size.setWidth(rect.width());
645         rect = inflateRect(rect, size, popupButtonMargins(), zoomLevel);
646     }
647 }
648
649 FloatRect RenderThemeMac::convertToPaintingRect(const RenderObject& inputRenderer, const RenderObject& partRenderer, const FloatRect& inputRect, const IntRect& r) const
650 {
651     FloatRect partRect(inputRect);
652
653     // Compute an offset between the part renderer and the input renderer
654     FloatSize offsetFromInputRenderer;
655     const RenderObject* renderer = &partRenderer;
656     while (renderer && renderer != &inputRenderer) {
657         RenderElement* containingRenderer = renderer->container();
658         ASSERT(containingRenderer);
659         offsetFromInputRenderer -= roundedIntSize(renderer->offsetFromContainer(*containingRenderer, LayoutPoint()));
660         renderer = containingRenderer;
661     }
662     // If the input renderer was not a container, something went wrong
663     ASSERT(renderer == &inputRenderer);
664     // Move the rect into partRenderer's coords
665     partRect.move(offsetFromInputRenderer);
666     // Account for the local drawing offset (tx, ty)
667     partRect.move(r.x(), r.y());
668
669     return partRect;
670 }
671
672 void RenderThemeMac::updateCheckedState(NSCell* cell, const RenderObject& o)
673 {
674     bool oldIndeterminate = [cell state] == NSMixedState;
675     bool indeterminate = isIndeterminate(o);
676     bool checked = isChecked(o);
677
678     if (oldIndeterminate != indeterminate) {
679         [cell setState:indeterminate ? NSMixedState : (checked ? NSOnState : NSOffState)];
680         return;
681     }
682
683     bool oldChecked = [cell state] == NSOnState;
684     if (checked != oldChecked)
685         [cell setState:checked ? NSOnState : NSOffState];
686 }
687
688 void RenderThemeMac::updateEnabledState(NSCell* cell, const RenderObject& o)
689 {
690     bool oldEnabled = [cell isEnabled];
691     bool enabled = isEnabled(o);
692     if (enabled != oldEnabled)
693         [cell setEnabled:enabled];
694 }
695
696 void RenderThemeMac::updateFocusedState(NSCell* cell, const RenderObject& o)
697 {
698     bool oldFocused = [cell showsFirstResponder];
699     bool focused = isFocused(o) && o.style().outlineStyleIsAuto();
700     if (focused != oldFocused)
701         [cell setShowsFirstResponder:focused];
702 }
703
704 void RenderThemeMac::updatePressedState(NSCell* cell, const RenderObject& o)
705 {
706     bool oldPressed = [cell isHighlighted];
707     bool pressed = is<Element>(o.node()) && downcast<Element>(*o.node()).active();
708     if (pressed != oldPressed)
709         [cell setHighlighted:pressed];
710 }
711
712 bool RenderThemeMac::controlSupportsTints(const RenderObject& o) const
713 {
714     // An alternate way to implement this would be to get the appropriate cell object
715     // and call the private _needRedrawOnWindowChangedKeyState method. An advantage of
716     // that would be that we would match AppKit behavior more closely, but a disadvantage
717     // would be that we would rely on an AppKit SPI method.
718
719     if (!isEnabled(o))
720         return false;
721
722     // Checkboxes only have tint when checked.
723     if (o.style().appearance() == CheckboxPart)
724         return isChecked(o);
725
726     // For now assume other controls have tint if enabled.
727     return true;
728 }
729
730 NSControlSize RenderThemeMac::controlSizeForFont(RenderStyle& style) const
731 {
732     int fontSize = style.fontSize();
733     if (fontSize >= 16)
734         return NSRegularControlSize;
735     if (fontSize >= 11)
736         return NSSmallControlSize;
737     return NSMiniControlSize;
738 }
739
740 NSControlSize RenderThemeMac::controlSizeForCell(NSCell*, const IntSize* sizes, const IntSize& minSize, float zoomLevel) const
741 {
742     if (minSize.width() >= static_cast<int>(sizes[NSRegularControlSize].width() * zoomLevel)
743         && minSize.height() >= static_cast<int>(sizes[NSRegularControlSize].height() * zoomLevel))
744         return NSRegularControlSize;
745
746     if (minSize.width() >= static_cast<int>(sizes[NSSmallControlSize].width() * zoomLevel)
747         && minSize.height() >= static_cast<int>(sizes[NSSmallControlSize].height() * zoomLevel))
748         return NSSmallControlSize;
749
750     return NSMiniControlSize;
751 }
752
753 void RenderThemeMac::setControlSize(NSCell* cell, const IntSize* sizes, const IntSize& minSize, float zoomLevel)
754 {
755     NSControlSize size = controlSizeForCell(cell, sizes, minSize, zoomLevel);
756     if (size != [cell controlSize]) // Only update if we have to, since AppKit does work even if the size is the same.
757         [cell setControlSize:size];
758 }
759
760 IntSize RenderThemeMac::sizeForFont(RenderStyle& style, const IntSize* sizes) const
761 {
762     if (style.effectiveZoom() != 1.0f) {
763         IntSize result = sizes[controlSizeForFont(style)];
764         return IntSize(result.width() * style.effectiveZoom(), result.height() * style.effectiveZoom());
765     }
766     return sizes[controlSizeForFont(style)];
767 }
768
769 IntSize RenderThemeMac::sizeForSystemFont(RenderStyle& style, const IntSize* sizes) const
770 {
771     if (style.effectiveZoom() != 1.0f) {
772         IntSize result = sizes[controlSizeForSystemFont(style)];
773         return IntSize(result.width() * style.effectiveZoom(), result.height() * style.effectiveZoom());
774     }
775     return sizes[controlSizeForSystemFont(style)];
776 }
777
778 void RenderThemeMac::setSizeFromFont(RenderStyle& style, const IntSize* sizes) const
779 {
780     // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
781     IntSize size = sizeForFont(style, sizes);
782     if (style.width().isIntrinsicOrAuto() && size.width() > 0)
783         style.setWidth(Length(size.width(), Fixed));
784     if (style.height().isAuto() && size.height() > 0)
785         style.setHeight(Length(size.height(), Fixed));
786 }
787
788 void RenderThemeMac::setFontFromControlSize(StyleResolver&, RenderStyle& style, NSControlSize controlSize) const
789 {
790     FontDescription fontDescription;
791     fontDescription.setIsAbsoluteSize(true);
792
793     NSFont* font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:controlSize]];
794     fontDescription.setOneFamily([font webCoreFamilyName]);
795     fontDescription.setComputedSize([font pointSize] * style.effectiveZoom());
796     fontDescription.setSpecifiedSize([font pointSize] * style.effectiveZoom());
797
798     // Reset line height
799     style.setLineHeight(RenderStyle::initialLineHeight());
800
801     if (style.setFontDescription(fontDescription))
802         style.fontCascade().update(0);
803 }
804
805 NSControlSize RenderThemeMac::controlSizeForSystemFont(RenderStyle& style) const
806 {
807     int fontSize = style.fontSize();
808     if (fontSize >= [NSFont systemFontSizeForControlSize:NSRegularControlSize])
809         return NSRegularControlSize;
810     if (fontSize >= [NSFont systemFontSizeForControlSize:NSSmallControlSize])
811         return NSSmallControlSize;
812     return NSMiniControlSize;
813 }
814
815 bool RenderThemeMac::paintTextField(const RenderObject& o, const PaintInfo& paintInfo, const FloatRect& r)
816 {
817     LocalCurrentGraphicsContext localContext(paintInfo.context);
818
819     NSTextFieldCell *textField = this->textField();
820
821     GraphicsContextStateSaver stateSaver(*paintInfo.context);
822
823     [textField setEnabled:(isEnabled(o) && !isReadOnlyControl(o))];
824     [textField drawWithFrame:NSRect(r) inView:documentViewFor(o)];
825
826     [textField setControlView:nil];
827
828     return false;
829 }
830
831 void RenderThemeMac::adjustTextFieldStyle(StyleResolver&, RenderStyle&, Element*) const
832 {
833 }
834
835 bool RenderThemeMac::paintTextArea(const RenderObject& o, const PaintInfo& paintInfo, const FloatRect& r)
836 {
837     LocalCurrentGraphicsContext localContext(paintInfo.context);
838     wkDrawBezeledTextArea(r, isEnabled(o) && !isReadOnlyControl(o));
839     return false;
840 }
841
842 void RenderThemeMac::adjustTextAreaStyle(StyleResolver&, RenderStyle&, Element*) const
843 {
844 }
845
846 const int* RenderThemeMac::popupButtonMargins() const
847 {
848     static const int margins[3][4] =
849     {
850         { 0, 3, 1, 3 },
851         { 0, 3, 2, 3 },
852         { 0, 1, 0, 1 }
853     };
854     return margins[[popupButton() controlSize]];
855 }
856
857 const IntSize* RenderThemeMac::popupButtonSizes() const
858 {
859     static const IntSize sizes[3] = { IntSize(0, 21), IntSize(0, 18), IntSize(0, 15) };
860     return sizes;
861 }
862
863 const int* RenderThemeMac::popupButtonPadding(NSControlSize size) const
864 {
865     static const int padding[3][4] =
866     {
867         { 2, 26, 3, 8 },
868         { 2, 23, 3, 8 },
869         { 2, 22, 3, 10 }
870     };
871     return padding[size];
872 }
873
874 bool RenderThemeMac::paintMenuList(const RenderObject& renderer, const PaintInfo& paintInfo, const FloatRect& rect)
875 {
876     LocalCurrentGraphicsContext localContext(paintInfo.context);
877     setPopupButtonCellState(renderer, IntSize(rect.size()));
878
879     NSPopUpButtonCell* popupButton = this->popupButton();
880
881     float zoomLevel = renderer.style().effectiveZoom();
882     IntSize size = popupButtonSizes()[[popupButton controlSize]];
883     size.setHeight(size.height() * zoomLevel);
884     size.setWidth(rect.width());
885
886     // Now inflate it to account for the shadow.
887     FloatRect inflatedRect = rect;
888     if (rect.width() >= minimumMenuListSize(renderer.style()))
889         inflatedRect = inflateRect(rect, size, popupButtonMargins(), zoomLevel);
890
891     GraphicsContextStateSaver stateSaver(*paintInfo.context);
892
893     // On Leopard, the cell will draw outside of the given rect, so we have to clip to the rect
894     paintInfo.context->clip(inflatedRect);
895
896     if (zoomLevel != 1.0f) {
897         inflatedRect.setWidth(inflatedRect.width() / zoomLevel);
898         inflatedRect.setHeight(inflatedRect.height() / zoomLevel);
899         paintInfo.context->translate(inflatedRect.x(), inflatedRect.y());
900         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
901         paintInfo.context->translate(-inflatedRect.x(), -inflatedRect.y());
902     }
903
904     NSView *view = documentViewFor(renderer);
905     [popupButton drawWithFrame:inflatedRect inView:view];
906     if (isFocused(renderer) && renderer.style().outlineStyleIsAuto()) {
907         if (wkDrawCellFocusRingWithFrameAtTime(popupButton, inflatedRect, view, std::numeric_limits<double>::max()))
908             renderer.document().page()->focusController().setFocusedElementNeedsRepaint();
909     }
910
911     [popupButton setControlView:nil];
912
913     return false;
914 }
915
916 #if ENABLE(METER_ELEMENT)
917
918 IntSize RenderThemeMac::meterSizeForBounds(const RenderMeter& renderMeter, const IntRect& bounds) const
919 {
920     if (NoControlPart == renderMeter.style().appearance())
921         return bounds.size();
922
923     NSLevelIndicatorCell* cell = levelIndicatorFor(renderMeter);
924     // Makes enough room for cell's intrinsic size.
925     NSSize cellSize = [cell cellSizeForBounds:IntRect(IntPoint(), bounds.size())];
926     return IntSize(bounds.width() < cellSize.width ? cellSize.width : bounds.width(),
927                    bounds.height() < cellSize.height ? cellSize.height : bounds.height());
928 }
929
930 bool RenderThemeMac::paintMeter(const RenderObject& renderObject, const PaintInfo& paintInfo, const IntRect& rect)
931 {
932     if (!is<RenderMeter>(renderObject))
933         return true;
934
935     LocalCurrentGraphicsContext localContext(paintInfo.context);
936
937     NSLevelIndicatorCell* cell = levelIndicatorFor(downcast<RenderMeter>(renderObject));
938     GraphicsContextStateSaver stateSaver(*paintInfo.context);
939
940     [cell drawWithFrame:rect inView:documentViewFor(renderObject)];
941     [cell setControlView:nil];
942     return false;
943 }
944
945 bool RenderThemeMac::supportsMeter(ControlPart part) const
946 {
947     switch (part) {
948     case RelevancyLevelIndicatorPart:
949     case DiscreteCapacityLevelIndicatorPart:
950     case RatingLevelIndicatorPart:
951     case MeterPart:
952     case ContinuousCapacityLevelIndicatorPart:
953         return true;
954     default:
955         return false;
956     }
957 }
958
959 NSLevelIndicatorStyle RenderThemeMac::levelIndicatorStyleFor(ControlPart part) const
960 {
961     switch (part) {
962     case RelevancyLevelIndicatorPart:
963         return NSRelevancyLevelIndicatorStyle;
964     case DiscreteCapacityLevelIndicatorPart:
965         return NSDiscreteCapacityLevelIndicatorStyle;
966     case RatingLevelIndicatorPart:
967         return NSRatingLevelIndicatorStyle;
968     case MeterPart:
969     case ContinuousCapacityLevelIndicatorPart:
970     default:
971         return NSContinuousCapacityLevelIndicatorStyle;
972     }
973
974 }
975
976 NSLevelIndicatorCell* RenderThemeMac::levelIndicatorFor(const RenderMeter& renderMeter) const
977 {
978     const RenderStyle& style = renderMeter.style();
979     ASSERT(style.appearance() != NoControlPart);
980
981     if (!m_levelIndicator)
982         m_levelIndicator = adoptNS([[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle]);
983     NSLevelIndicatorCell* cell = m_levelIndicator.get();
984
985     HTMLMeterElement* element = renderMeter.meterElement();
986     double value = element->value();
987
988     // Because NSLevelIndicatorCell does not support optimum-in-the-middle type coloring,
989     // we explicitly control the color instead giving low and high value to NSLevelIndicatorCell as is.
990     switch (element->gaugeRegion()) {
991     case HTMLMeterElement::GaugeRegionOptimum:
992         // Make meter the green
993         [cell setWarningValue:value + 1];
994         [cell setCriticalValue:value + 2];
995         break;
996     case HTMLMeterElement::GaugeRegionSuboptimal:
997         // Make the meter yellow
998         [cell setWarningValue:value - 1];
999         [cell setCriticalValue:value + 1];
1000         break;
1001     case HTMLMeterElement::GaugeRegionEvenLessGood:
1002         // Make the meter red
1003         [cell setWarningValue:value - 2];
1004         [cell setCriticalValue:value - 1];
1005         break;
1006     }
1007
1008     [cell setLevelIndicatorStyle:levelIndicatorStyleFor(style.appearance())];
1009     [cell setBaseWritingDirection:style.isLeftToRightDirection() ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft];
1010     [cell setMinValue:element->min()];
1011     [cell setMaxValue:element->max()];
1012     RetainPtr<NSNumber> valueObject = [NSNumber numberWithDouble:value];
1013     [cell setObjectValue:valueObject.get()];
1014
1015     return cell;
1016 }
1017
1018 #endif
1019
1020 const IntSize* RenderThemeMac::progressBarSizes() const
1021 {
1022     static const IntSize sizes[3] = { IntSize(0, 20), IntSize(0, 12), IntSize(0, 12) };
1023     return sizes;
1024 }
1025
1026 const int* RenderThemeMac::progressBarMargins(NSControlSize controlSize) const
1027 {
1028     static const int margins[3][4] =
1029     {
1030         { 0, 0, 1, 0 },
1031         { 0, 0, 1, 0 },
1032         { 0, 0, 1, 0 },
1033     };
1034     return margins[controlSize];
1035 }
1036
1037 IntRect RenderThemeMac::progressBarRectForBounds(const RenderObject& renderObject, const IntRect& bounds) const
1038 {
1039     // Workaround until <rdar://problem/15855086> is fixed.
1040     int maxDimension = static_cast<int>(std::numeric_limits<ushort>::max());
1041     IntRect progressBarBounds(bounds.x(), bounds.y(), std::min(bounds.width(), maxDimension), std::min(bounds.height(), maxDimension));
1042     if (NoControlPart == renderObject.style().appearance())
1043         return progressBarBounds;
1044
1045     float zoomLevel = renderObject.style().effectiveZoom();
1046     NSControlSize controlSize = controlSizeForFont(renderObject.style());
1047     IntSize size = progressBarSizes()[controlSize];
1048     size.setHeight(size.height() * zoomLevel);
1049     size.setWidth(progressBarBounds.width());
1050
1051     // Now inflate it to account for the shadow.
1052     IntRect inflatedRect = progressBarBounds;
1053     if (progressBarBounds.height() <= minimumProgressBarHeight(renderObject.style()))
1054         inflatedRect = IntRect(inflateRect(inflatedRect, size, progressBarMargins(controlSize), zoomLevel));
1055
1056     return inflatedRect;
1057 }
1058
1059 int RenderThemeMac::minimumProgressBarHeight(RenderStyle& style) const
1060 {
1061     return sizeForSystemFont(style, progressBarSizes()).height();
1062 }
1063
1064 double RenderThemeMac::animationRepeatIntervalForProgressBar(RenderProgress&) const
1065 {
1066     return progressAnimationFrameRate;
1067 }
1068
1069 double RenderThemeMac::animationDurationForProgressBar(RenderProgress&) const
1070 {
1071     return progressAnimationNumFrames * progressAnimationFrameRate;
1072 }
1073
1074 void RenderThemeMac::adjustProgressBarStyle(StyleResolver&, RenderStyle&, Element*) const
1075 {
1076 }
1077
1078 bool RenderThemeMac::paintProgressBar(const RenderObject& renderObject, const PaintInfo& paintInfo, const IntRect& rect)
1079 {
1080     if (!is<RenderProgress>(renderObject))
1081         return true;
1082
1083     IntRect inflatedRect = progressBarRectForBounds(renderObject, rect);
1084     NSControlSize controlSize = controlSizeForFont(renderObject.style());
1085
1086     const auto& renderProgress = downcast<RenderProgress>(renderObject);
1087     HIThemeTrackDrawInfo trackInfo;
1088     trackInfo.version = 0;
1089     if (controlSize == NSRegularControlSize)
1090         trackInfo.kind = renderProgress.position() < 0 ? kThemeLargeIndeterminateBar : kThemeLargeProgressBar;
1091     else
1092         trackInfo.kind = renderProgress.position() < 0 ? kThemeMediumIndeterminateBar : kThemeMediumProgressBar;
1093
1094     float deviceScaleFactor = renderObject.document().deviceScaleFactor();
1095     trackInfo.bounds = IntRect(IntPoint(), inflatedRect.size());
1096     trackInfo.min = 0;
1097     trackInfo.max = std::numeric_limits<SInt32>::max();
1098     trackInfo.value = lround(renderProgress.position() * nextafter(trackInfo.max, 0));
1099     trackInfo.trackInfo.progress.phase = lround(renderProgress.animationProgress() * nextafter(progressAnimationNumFrames, 0) * deviceScaleFactor);
1100     trackInfo.attributes = kThemeTrackHorizontal;
1101     trackInfo.enableState = isActive(renderObject) ? kThemeTrackActive : kThemeTrackInactive;
1102     trackInfo.reserved = 0;
1103     trackInfo.filler1 = 0;
1104
1105     std::unique_ptr<ImageBuffer> imageBuffer = ImageBuffer::createCompatibleBuffer(inflatedRect.size(), deviceScaleFactor, ColorSpaceDeviceRGB, paintInfo.context, true);
1106     if (!imageBuffer)
1107         return true;
1108
1109     ContextContainer cgContextContainer(imageBuffer->context());
1110     CGContextRef cgContext = cgContextContainer.context();
1111     HIThemeDrawTrack(&trackInfo, 0, cgContext, kHIThemeOrientationNormal);
1112
1113     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1114
1115     if (!renderProgress.style().isLeftToRightDirection()) {
1116         paintInfo.context->translate(2 * inflatedRect.x() + inflatedRect.width(), 0);
1117         paintInfo.context->scale(FloatSize(-1, 1));
1118     }
1119
1120     paintInfo.context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, inflatedRect.location());
1121     return false;
1122 }
1123
1124 const float baseFontSize = 11.0f;
1125 const float baseArrowHeight = 4.0f;
1126 const float baseArrowWidth = 5.0f;
1127 const float baseSpaceBetweenArrows = 2.0f;
1128 const int arrowPaddingLeft = 6;
1129 const int arrowPaddingRight = 6;
1130 const int paddingBeforeSeparator = 4;
1131 const int baseBorderRadius = 5;
1132 const int styledPopupPaddingLeft = 8;
1133 const int styledPopupPaddingTop = 1;
1134 const int styledPopupPaddingBottom = 2;
1135
1136 static void TopGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1137 {
1138     static float dark[4] = { 1.0f, 1.0f, 1.0f, 0.4f };
1139     static float light[4] = { 1.0f, 1.0f, 1.0f, 0.15f };
1140     float a = inData[0];
1141     int i = 0;
1142     for (i = 0; i < 4; i++)
1143         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1144 }
1145
1146 static void BottomGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1147 {
1148     static float dark[4] = { 1.0f, 1.0f, 1.0f, 0.0f };
1149     static float light[4] = { 1.0f, 1.0f, 1.0f, 0.3f };
1150     float a = inData[0];
1151     int i = 0;
1152     for (i = 0; i < 4; i++)
1153         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1154 }
1155
1156 static void MainGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1157 {
1158     static float dark[4] = { 0.0f, 0.0f, 0.0f, 0.15f };
1159     static float light[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
1160     float a = inData[0];
1161     int i = 0;
1162     for (i = 0; i < 4; i++)
1163         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1164 }
1165
1166 static void TrackGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1167 {
1168     static float dark[4] = { 0.0f, 0.0f, 0.0f, 0.678f };
1169     static float light[4] = { 0.0f, 0.0f, 0.0f, 0.13f };
1170     float a = inData[0];
1171     int i = 0;
1172     for (i = 0; i < 4; i++)
1173         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1174 }
1175
1176 void RenderThemeMac::paintMenuListButtonGradients(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1177 {
1178     if (r.isEmpty())
1179         return;
1180
1181     ContextContainer cgContextContainer(paintInfo.context);
1182     CGContextRef context = cgContextContainer.context();
1183
1184     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1185
1186     FloatRoundedRect border = FloatRoundedRect(o.style().getRoundedBorderFor(r));
1187     int radius = border.radii().topLeft().width();
1188
1189     CGColorSpaceRef cspace = deviceRGBColorSpaceRef();
1190
1191     FloatRect topGradient(r.x(), r.y(), r.width(), r.height() / 2.0f);
1192     struct CGFunctionCallbacks topCallbacks = { 0, TopGradientInterpolate, NULL };
1193     RetainPtr<CGFunctionRef> topFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &topCallbacks));
1194     RetainPtr<CGShadingRef> topShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(topGradient.x(), topGradient.y()), CGPointMake(topGradient.x(), topGradient.maxY()), topFunction.get(), false, false));
1195
1196     FloatRect bottomGradient(r.x() + radius, r.y() + r.height() / 2.0f, r.width() - 2.0f * radius, r.height() / 2.0f);
1197     struct CGFunctionCallbacks bottomCallbacks = { 0, BottomGradientInterpolate, NULL };
1198     RetainPtr<CGFunctionRef> bottomFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &bottomCallbacks));
1199     RetainPtr<CGShadingRef> bottomShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bottomGradient.x(),  bottomGradient.y()), CGPointMake(bottomGradient.x(), bottomGradient.maxY()), bottomFunction.get(), false, false));
1200
1201     struct CGFunctionCallbacks mainCallbacks = { 0, MainGradientInterpolate, NULL };
1202     RetainPtr<CGFunctionRef> mainFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &mainCallbacks));
1203     RetainPtr<CGShadingRef> mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(r.x(),  r.y()), CGPointMake(r.x(), r.maxY()), mainFunction.get(), false, false));
1204
1205     RetainPtr<CGShadingRef> leftShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(r.x(),  r.y()), CGPointMake(r.x() + radius, r.y()), mainFunction.get(), false, false));
1206
1207     RetainPtr<CGShadingRef> rightShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(r.maxX(),  r.y()), CGPointMake(r.maxX() - radius, r.y()), mainFunction.get(), false, false));
1208
1209     {
1210         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1211         CGContextClipToRect(context, r);
1212         paintInfo.context->clipRoundedRect(border);
1213         context = cgContextContainer.context();
1214         CGContextDrawShading(context, mainShading.get());
1215     }
1216
1217     {
1218         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1219         CGContextClipToRect(context, topGradient);
1220         paintInfo.context->clipRoundedRect(FloatRoundedRect(enclosingIntRect(topGradient), border.radii().topLeft(), border.radii().topRight(), IntSize(), IntSize()));
1221         context = cgContextContainer.context();
1222         CGContextDrawShading(context, topShading.get());
1223     }
1224
1225     if (!bottomGradient.isEmpty()) {
1226         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1227         CGContextClipToRect(context, bottomGradient);
1228         paintInfo.context->clipRoundedRect(FloatRoundedRect(enclosingIntRect(bottomGradient), IntSize(), IntSize(), border.radii().bottomLeft(), border.radii().bottomRight()));
1229         context = cgContextContainer.context();
1230         CGContextDrawShading(context, bottomShading.get());
1231     }
1232
1233     {
1234         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1235         CGContextClipToRect(context, r);
1236         paintInfo.context->clipRoundedRect(border);
1237         context = cgContextContainer.context();
1238         CGContextDrawShading(context, leftShading.get());
1239         CGContextDrawShading(context, rightShading.get());
1240     }
1241 }
1242
1243 bool RenderThemeMac::paintMenuListButtonDecorations(const RenderObject& renderer, const PaintInfo& paintInfo, const FloatRect& rect)
1244 {
1245     IntRect bounds = IntRect(rect.x() + renderer.style().borderLeftWidth(),
1246         rect.y() + renderer.style().borderTopWidth(),
1247         rect.width() - renderer.style().borderLeftWidth() - renderer.style().borderRightWidth(),
1248         rect.height() - renderer.style().borderTopWidth() - renderer.style().borderBottomWidth());
1249     // Draw the gradients to give the styled popup menu a button appearance
1250     paintMenuListButtonGradients(renderer, paintInfo, bounds);
1251
1252     // Since we actually know the size of the control here, we restrict the font scale to make sure the arrows will fit vertically in the bounds
1253     float fontScale = std::min(renderer.style().fontSize() / baseFontSize, bounds.height() / (baseArrowHeight * 2 + baseSpaceBetweenArrows));
1254     float centerY = bounds.y() + bounds.height() / 2.0f;
1255     float arrowHeight = baseArrowHeight * fontScale;
1256     float arrowWidth = baseArrowWidth * fontScale;
1257     float leftEdge = bounds.maxX() - arrowPaddingRight * renderer.style().effectiveZoom() - arrowWidth;
1258     float spaceBetweenArrows = baseSpaceBetweenArrows * fontScale;
1259
1260     if (bounds.width() < arrowWidth + arrowPaddingLeft * renderer.style().effectiveZoom())
1261         return false;
1262
1263     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1264
1265     paintInfo.context->setFillColor(renderer.style().visitedDependentColor(CSSPropertyColor), renderer.style().colorSpace());
1266     paintInfo.context->setStrokeStyle(NoStroke);
1267
1268     FloatPoint arrow1[3];
1269     arrow1[0] = FloatPoint(leftEdge, centerY - spaceBetweenArrows / 2.0f);
1270     arrow1[1] = FloatPoint(leftEdge + arrowWidth, centerY - spaceBetweenArrows / 2.0f);
1271     arrow1[2] = FloatPoint(leftEdge + arrowWidth / 2.0f, centerY - spaceBetweenArrows / 2.0f - arrowHeight);
1272
1273     // Draw the top arrow
1274     paintInfo.context->drawConvexPolygon(3, arrow1, true);
1275
1276     FloatPoint arrow2[3];
1277     arrow2[0] = FloatPoint(leftEdge, centerY + spaceBetweenArrows / 2.0f);
1278     arrow2[1] = FloatPoint(leftEdge + arrowWidth, centerY + spaceBetweenArrows / 2.0f);
1279     arrow2[2] = FloatPoint(leftEdge + arrowWidth / 2.0f, centerY + spaceBetweenArrows / 2.0f + arrowHeight);
1280
1281     // Draw the bottom arrow
1282     paintInfo.context->drawConvexPolygon(3, arrow2, true);
1283
1284     Color leftSeparatorColor(0, 0, 0, 40);
1285     Color rightSeparatorColor(255, 255, 255, 40);
1286
1287     // FIXME: Should the separator thickness and space be scaled up by fontScale?
1288     int separatorSpace = 2; // Deliberately ignores zoom since it looks nicer if it stays thin.
1289     int leftEdgeOfSeparator = static_cast<int>(leftEdge - arrowPaddingLeft * renderer.style().effectiveZoom()); // FIXME: Round?
1290
1291     // Draw the separator to the left of the arrows
1292     paintInfo.context->setStrokeThickness(1); // Deliberately ignores zoom since it looks nicer if it stays thin.
1293     paintInfo.context->setStrokeStyle(SolidStroke);
1294     paintInfo.context->setStrokeColor(leftSeparatorColor, ColorSpaceDeviceRGB);
1295     paintInfo.context->drawLine(IntPoint(leftEdgeOfSeparator, bounds.y()),
1296                                 IntPoint(leftEdgeOfSeparator, bounds.maxY()));
1297
1298     paintInfo.context->setStrokeColor(rightSeparatorColor, ColorSpaceDeviceRGB);
1299     paintInfo.context->drawLine(IntPoint(leftEdgeOfSeparator + separatorSpace, bounds.y()),
1300                                 IntPoint(leftEdgeOfSeparator + separatorSpace, bounds.maxY()));
1301     return false;
1302 }
1303
1304 static const IntSize* menuListButtonSizes()
1305 {
1306     static const IntSize sizes[3] = { IntSize(0, 21), IntSize(0, 18), IntSize(0, 15) };
1307     return sizes;
1308 }
1309
1310 void RenderThemeMac::adjustMenuListStyle(StyleResolver& styleResolver, RenderStyle& style, Element* e) const
1311 {
1312     NSControlSize controlSize = controlSizeForFont(style);
1313
1314     style.resetBorder();
1315     style.resetPadding();
1316
1317     // Height is locked to auto.
1318     style.setHeight(Length(Auto));
1319
1320     // White-space is locked to pre
1321     style.setWhiteSpace(PRE);
1322
1323     // Set the foreground color to black or gray when we have the aqua look.
1324     // Cast to RGB32 is to work around a compiler bug.
1325     style.setColor(e && !e->isDisabledFormControl() ? static_cast<RGBA32>(Color::black) : Color::darkGray);
1326
1327     // Set the button's vertical size.
1328     setSizeFromFont(style, menuListButtonSizes());
1329
1330     // Our font is locked to the appropriate system font size for the control.  To clarify, we first use the CSS-specified font to figure out
1331     // a reasonable control size, but once that control size is determined, we throw that font away and use the appropriate
1332     // system font for the control size instead.
1333     setFontFromControlSize(styleResolver, style, controlSize);
1334
1335     style.setBoxShadow(nullptr);
1336 }
1337
1338 int RenderThemeMac::popupInternalPaddingLeft(RenderStyle& style) const
1339 {
1340     if (style.appearance() == MenulistPart)
1341         return popupButtonPadding(controlSizeForFont(style))[leftPadding] * style.effectiveZoom();
1342     if (style.appearance() == MenulistButtonPart)
1343         return styledPopupPaddingLeft * style.effectiveZoom();
1344     return 0;
1345 }
1346
1347 int RenderThemeMac::popupInternalPaddingRight(RenderStyle& style) const
1348 {
1349     if (style.appearance() == MenulistPart)
1350         return popupButtonPadding(controlSizeForFont(style))[rightPadding] * style.effectiveZoom();
1351     if (style.appearance() == MenulistButtonPart) {
1352         float fontScale = style.fontSize() / baseFontSize;
1353         float arrowWidth = baseArrowWidth * fontScale;
1354         return static_cast<int>(ceilf(arrowWidth + (arrowPaddingLeft + arrowPaddingRight + paddingBeforeSeparator) * style.effectiveZoom()));
1355     }
1356     return 0;
1357 }
1358
1359 int RenderThemeMac::popupInternalPaddingTop(RenderStyle& style) const
1360 {
1361     if (style.appearance() == MenulistPart)
1362         return popupButtonPadding(controlSizeForFont(style))[topPadding] * style.effectiveZoom();
1363     if (style.appearance() == MenulistButtonPart)
1364         return styledPopupPaddingTop * style.effectiveZoom();
1365     return 0;
1366 }
1367
1368 int RenderThemeMac::popupInternalPaddingBottom(RenderStyle& style) const
1369 {
1370     if (style.appearance() == MenulistPart)
1371         return popupButtonPadding(controlSizeForFont(style))[bottomPadding] * style.effectiveZoom();
1372     if (style.appearance() == MenulistButtonPart)
1373         return styledPopupPaddingBottom * style.effectiveZoom();
1374     return 0;
1375 }
1376
1377 PopupMenuStyle::PopupMenuSize RenderThemeMac::popupMenuSize(const RenderStyle& style, IntRect& rect) const
1378 {
1379     NSPopUpButtonCell* popupButton = this->popupButton();
1380     NSControlSize size = controlSizeForCell(popupButton, popupButtonSizes(), rect.size(), style.effectiveZoom());
1381     switch (size) {
1382     case NSRegularControlSize:
1383         return PopupMenuStyle::PopupMenuSizeNormal;
1384     case NSSmallControlSize:
1385         return PopupMenuStyle::PopupMenuSizeSmall;
1386     case NSMiniControlSize:
1387         return PopupMenuStyle::PopupMenuSizeMini;
1388     default:
1389         return PopupMenuStyle::PopupMenuSizeNormal;
1390     }
1391 }
1392
1393 void RenderThemeMac::adjustMenuListButtonStyle(StyleResolver&, RenderStyle& style, Element*) const
1394 {
1395     float fontScale = style.fontSize() / baseFontSize;
1396
1397     style.resetPadding();
1398     style.setBorderRadius(IntSize(int(baseBorderRadius + fontScale - 1), int(baseBorderRadius + fontScale - 1))); // FIXME: Round up?
1399
1400     const int minHeight = 15;
1401     style.setMinHeight(Length(minHeight, Fixed));
1402
1403     style.setLineHeight(RenderStyle::initialLineHeight());
1404 }
1405
1406 void RenderThemeMac::setPopupButtonCellState(const RenderObject& o, const IntSize& buttonSize)
1407 {
1408     NSPopUpButtonCell* popupButton = this->popupButton();
1409
1410     // Set the control size based off the rectangle we're painting into.
1411     setControlSize(popupButton, popupButtonSizes(), buttonSize, o.style().effectiveZoom());
1412
1413     // Update the various states we respond to.
1414     updateCheckedState(popupButton, o);
1415     updateEnabledState(popupButton, o);
1416     updatePressedState(popupButton, o);
1417 }
1418
1419 const IntSize* RenderThemeMac::menuListSizes() const
1420 {
1421     static const IntSize sizes[3] = { IntSize(9, 0), IntSize(5, 0), IntSize(0, 0) };
1422     return sizes;
1423 }
1424
1425 int RenderThemeMac::minimumMenuListSize(RenderStyle& style) const
1426 {
1427     return sizeForSystemFont(style, menuListSizes()).width();
1428 }
1429
1430 const int trackWidth = 5;
1431 const int trackRadius = 2;
1432
1433 void RenderThemeMac::adjustSliderTrackStyle(StyleResolver&, RenderStyle& style, Element*) const
1434 {
1435     style.setBoxShadow(nullptr);
1436 }
1437
1438 bool RenderThemeMac::paintSliderTrack(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1439 {
1440     IntRect bounds = r;
1441     float zoomLevel = o.style().effectiveZoom();
1442     float zoomedTrackWidth = trackWidth * zoomLevel;
1443
1444     if (o.style().appearance() ==  SliderHorizontalPart || o.style().appearance() ==  MediaSliderPart) {
1445         bounds.setHeight(zoomedTrackWidth);
1446         bounds.setY(r.y() + r.height() / 2 - zoomedTrackWidth / 2);
1447     } else if (o.style().appearance() == SliderVerticalPart) {
1448         bounds.setWidth(zoomedTrackWidth);
1449         bounds.setX(r.x() + r.width() / 2 - zoomedTrackWidth / 2);
1450     }
1451
1452     LocalCurrentGraphicsContext localContext(paintInfo.context);
1453     CGContextRef context = localContext.cgContext();
1454     CGColorSpaceRef cspace = deviceRGBColorSpaceRef();
1455
1456 #if ENABLE(DATALIST_ELEMENT)
1457     paintSliderTicks(o, paintInfo, r);
1458 #endif
1459
1460     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1461     CGContextClipToRect(context, bounds);
1462
1463     struct CGFunctionCallbacks mainCallbacks = { 0, TrackGradientInterpolate, NULL };
1464     RetainPtr<CGFunctionRef> mainFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &mainCallbacks));
1465     RetainPtr<CGShadingRef> mainShading;
1466     if (o.style().appearance() == SliderVerticalPart)
1467         mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.maxY()), CGPointMake(bounds.maxX(), bounds.maxY()), mainFunction.get(), false, false));
1468     else
1469         mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.y()), CGPointMake(bounds.x(), bounds.maxY()), mainFunction.get(), false, false));
1470
1471     IntSize radius(trackRadius, trackRadius);
1472     paintInfo.context->clipRoundedRect(FloatRoundedRect(bounds, radius, radius, radius, radius));
1473     context = localContext.cgContext();
1474     CGContextDrawShading(context, mainShading.get());
1475
1476     return false;
1477 }
1478
1479 void RenderThemeMac::adjustSliderThumbStyle(StyleResolver& styleResolver, RenderStyle& style, Element* element) const
1480 {
1481     RenderTheme::adjustSliderThumbStyle(styleResolver, style, element);
1482     style.setBoxShadow(nullptr);
1483 }
1484
1485 const float verticalSliderHeightPadding = 0.1f;
1486
1487 bool RenderThemeMac::paintSliderThumb(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1488 {
1489     NSSliderCell* sliderThumbCell = o.style().appearance() == SliderThumbVerticalPart
1490         ? sliderThumbVertical()
1491         : sliderThumbHorizontal();
1492
1493     LocalCurrentGraphicsContext localContext(paintInfo.context);
1494
1495     // Update the various states we respond to.
1496     updateEnabledState(sliderThumbCell, o);
1497         Element* focusDelegate = is<Element>(o.node()) ? downcast<Element>(*o.node()).focusDelegate() : nullptr;
1498     if (focusDelegate)
1499         updateFocusedState(sliderThumbCell, *focusDelegate->renderer());
1500
1501     // Update the pressed state using the NSCell tracking methods, since that's how NSSliderCell keeps track of it.
1502     bool oldPressed;
1503     if (o.style().appearance() == SliderThumbVerticalPart)
1504         oldPressed = m_isSliderThumbVerticalPressed;
1505     else
1506         oldPressed = m_isSliderThumbHorizontalPressed;
1507
1508     bool pressed = isPressed(o);
1509
1510     if (o.style().appearance() == SliderThumbVerticalPart)
1511         m_isSliderThumbVerticalPressed = pressed;
1512     else
1513         m_isSliderThumbHorizontalPressed = pressed;
1514
1515     if (pressed != oldPressed) {
1516         if (pressed)
1517             [sliderThumbCell startTrackingAt:NSPoint() inView:nil];
1518         else
1519             [sliderThumbCell stopTracking:NSPoint() at:NSPoint() inView:nil mouseIsUp:YES];
1520     }
1521
1522     FloatRect bounds = r;
1523     // Make the height of the vertical slider slightly larger so NSSliderCell will draw a vertical slider.
1524     if (o.style().appearance() == SliderThumbVerticalPart)
1525         bounds.setHeight(bounds.height() + verticalSliderHeightPadding * o.style().effectiveZoom());
1526
1527     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1528     float zoomLevel = o.style().effectiveZoom();
1529
1530     FloatRect unzoomedRect = bounds;
1531     if (zoomLevel != 1.0f) {
1532         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1533         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1534         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
1535         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
1536         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
1537     }
1538
1539     [sliderThumbCell drawInteriorWithFrame:unzoomedRect inView:documentViewFor(o)];
1540     [sliderThumbCell setControlView:nil];
1541
1542     return false;
1543 }
1544
1545 bool RenderThemeMac::paintSearchField(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1546 {
1547     LocalCurrentGraphicsContext localContext(paintInfo.context);
1548     NSSearchFieldCell* search = this->search();
1549
1550     setSearchCellState(o, r);
1551
1552     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1553
1554     float zoomLevel = o.style().effectiveZoom();
1555
1556     IntRect unzoomedRect = r;
1557
1558     if (zoomLevel != 1.0f) {
1559         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1560         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1561         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
1562         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
1563         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
1564     }
1565
1566     // Set the search button to nil before drawing.  Then reset it so we can draw it later.
1567     [search setSearchButtonCell:nil];
1568
1569     NSView *documentView = documentViewFor(o);
1570     [search drawWithFrame:NSRect(unzoomedRect) inView:documentView];
1571
1572     [search setControlView:nil];
1573     [search resetSearchButtonCell];
1574
1575     if (isFocused(o) && o.style().outlineStyleIsAuto()) {
1576         if (wkDrawCellFocusRingWithFrameAtTime(search, NSRect(unzoomedRect), documentView, std::numeric_limits<double>::max()))
1577             o.document().page()->focusController().setFocusedElementNeedsRepaint();
1578     }
1579     
1580     return false;
1581 }
1582
1583 void RenderThemeMac::setSearchCellState(const RenderObject& o, const IntRect&)
1584 {
1585     NSSearchFieldCell* search = this->search();
1586
1587     [search setControlSize:controlSizeForFont(o.style())];
1588
1589     // Update the various states we respond to.
1590     updateEnabledState(search, o);
1591     updateFocusedState(search, o);
1592 }
1593
1594 const IntSize* RenderThemeMac::searchFieldSizes() const
1595 {
1596     static const IntSize sizes[3] = { IntSize(0, 22), IntSize(0, 19), IntSize(0, 17) };
1597     return sizes;
1598 }
1599
1600 void RenderThemeMac::setSearchFieldSize(RenderStyle& style) const
1601 {
1602     // If the width and height are both specified, then we have nothing to do.
1603     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
1604         return;
1605
1606     // Use the font size to determine the intrinsic width of the control.
1607     setSizeFromFont(style, searchFieldSizes());
1608 }
1609
1610 void RenderThemeMac::adjustSearchFieldStyle(StyleResolver& styleResolver, RenderStyle& style, Element*) const
1611 {
1612     // Override border.
1613     style.resetBorder();
1614     const short borderWidth = 2 * style.effectiveZoom();
1615     style.setBorderLeftWidth(borderWidth);
1616     style.setBorderLeftStyle(INSET);
1617     style.setBorderRightWidth(borderWidth);
1618     style.setBorderRightStyle(INSET);
1619     style.setBorderBottomWidth(borderWidth);
1620     style.setBorderBottomStyle(INSET);
1621     style.setBorderTopWidth(borderWidth);
1622     style.setBorderTopStyle(INSET);
1623
1624     // Override height.
1625     style.setHeight(Length(Auto));
1626     setSearchFieldSize(style);
1627
1628     // Override padding size to match AppKit text positioning.
1629     const int padding = 1 * style.effectiveZoom();
1630     style.setPaddingLeft(Length(padding, Fixed));
1631     style.setPaddingRight(Length(padding, Fixed));
1632     style.setPaddingTop(Length(padding, Fixed));
1633     style.setPaddingBottom(Length(padding, Fixed));
1634
1635     NSControlSize controlSize = controlSizeForFont(style);
1636     setFontFromControlSize(styleResolver, style, controlSize);
1637
1638     style.setBoxShadow(nullptr);
1639 }
1640
1641 bool RenderThemeMac::paintSearchFieldCancelButton(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1642 {
1643     Element* input = o.node()->shadowHost();
1644     if (!input)
1645         input = downcast<Element>(o.node());
1646
1647     if (!input->renderer()->isBox())
1648         return false;
1649
1650     LocalCurrentGraphicsContext localContext(paintInfo.context);
1651     setSearchCellState(*input->renderer(), r);
1652
1653     NSSearchFieldCell* search = this->search();
1654
1655     if (!input->isDisabledFormControl() && (is<HTMLTextFormControlElement>(*input) && !downcast<HTMLTextFormControlElement>(*input).isReadOnly()))
1656         updatePressedState([search cancelButtonCell], o);
1657     else if ([[search cancelButtonCell] isHighlighted])
1658         [[search cancelButtonCell] setHighlighted:NO];
1659
1660     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1661
1662     float zoomLevel = o.style().effectiveZoom();
1663
1664     FloatRect localBounds = [search cancelButtonRectForBounds:NSRect(input->renderBox()->pixelSnappedBorderBoxRect())];
1665     localBounds = convertToPaintingRect(*input->renderer(), o, localBounds, r);
1666
1667     FloatRect unzoomedRect(localBounds);
1668     if (zoomLevel != 1.0f) {
1669         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1670         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1671         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
1672         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
1673         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
1674     }
1675
1676     [[search cancelButtonCell] drawWithFrame:unzoomedRect inView:documentViewFor(o)];
1677     [[search cancelButtonCell] setControlView:nil];
1678     return false;
1679 }
1680
1681 const IntSize* RenderThemeMac::cancelButtonSizes() const
1682 {
1683     static const IntSize sizes[3] = { IntSize(16, 13), IntSize(13, 11), IntSize(13, 9) };
1684     return sizes;
1685 }
1686
1687 void RenderThemeMac::adjustSearchFieldCancelButtonStyle(StyleResolver&, RenderStyle& style, Element*) const
1688 {
1689     IntSize size = sizeForSystemFont(style, cancelButtonSizes());
1690     style.setWidth(Length(size.width(), Fixed));
1691     style.setHeight(Length(size.height(), Fixed));
1692     style.setBoxShadow(nullptr);
1693 }
1694
1695 const IntSize* RenderThemeMac::resultsButtonSizes() const
1696 {
1697     static const IntSize sizes[3] = { IntSize(19, 13), IntSize(17, 11), IntSize(17, 9) };
1698     return sizes;
1699 }
1700
1701 const int emptyResultsOffset = 9;
1702 void RenderThemeMac::adjustSearchFieldDecorationPartStyle(StyleResolver&, RenderStyle& style, Element*) const
1703 {
1704     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
1705     style.setWidth(Length(size.width() - emptyResultsOffset, Fixed));
1706     style.setHeight(Length(size.height(), Fixed));
1707     style.setBoxShadow(nullptr);
1708 }
1709
1710 bool RenderThemeMac::paintSearchFieldDecorationPart(const RenderObject&, const PaintInfo&, const IntRect&)
1711 {
1712     return false;
1713 }
1714
1715 void RenderThemeMac::adjustSearchFieldResultsDecorationPartStyle(StyleResolver&, RenderStyle& style, Element*) const
1716 {
1717     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
1718     style.setWidth(Length(size.width(), Fixed));
1719     style.setHeight(Length(size.height(), Fixed));
1720     style.setBoxShadow(nullptr);
1721 }
1722
1723 bool RenderThemeMac::paintSearchFieldResultsDecorationPart(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1724 {
1725     Node* input = o.node()->shadowHost();
1726     if (!input)
1727         input = o.node();
1728     if (!input->renderer()->isBox())
1729         return false;
1730
1731     LocalCurrentGraphicsContext localContext(paintInfo.context);
1732     setSearchCellState(*input->renderer(), r);
1733
1734     NSSearchFieldCell* search = this->search();
1735
1736     if ([search searchMenuTemplate] != nil)
1737         [search setSearchMenuTemplate:nil];
1738
1739     FloatRect localBounds = [search searchButtonRectForBounds:NSRect(input->renderBox()->pixelSnappedBorderBoxRect())];
1740     localBounds = convertToPaintingRect(*input->renderer(), o, localBounds, r);
1741
1742     [[search searchButtonCell] drawWithFrame:localBounds inView:documentViewFor(o)];
1743     [[search searchButtonCell] setControlView:nil];
1744     return false;
1745 }
1746
1747 const int resultsArrowWidth = 5;
1748 void RenderThemeMac::adjustSearchFieldResultsButtonStyle(StyleResolver&, RenderStyle& style, Element*) const
1749 {
1750     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
1751     style.setWidth(Length(size.width() + resultsArrowWidth, Fixed));
1752     style.setHeight(Length(size.height(), Fixed));
1753     style.setBoxShadow(nullptr);
1754 }
1755
1756 bool RenderThemeMac::paintSearchFieldResultsButton(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1757 {
1758     Node* input = o.node()->shadowHost();
1759     if (!input)
1760         input = o.node();
1761     if (!input->renderer()->isBox())
1762         return false;
1763
1764     LocalCurrentGraphicsContext localContext(paintInfo.context);
1765     setSearchCellState(*input->renderer(), r);
1766
1767     NSSearchFieldCell* search = this->search();
1768
1769     if (![search searchMenuTemplate])
1770         [search setSearchMenuTemplate:searchMenuTemplate()];
1771
1772     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1773     float zoomLevel = o.style().effectiveZoom();
1774
1775     FloatRect localBounds = [search searchButtonRectForBounds:NSRect(input->renderBox()->pixelSnappedBorderBoxRect())];
1776     localBounds = convertToPaintingRect(*input->renderer(), o, localBounds, r);
1777
1778     IntRect unzoomedRect(localBounds);
1779     if (zoomLevel != 1.0f) {
1780         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1781         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1782         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
1783         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
1784         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
1785     }
1786
1787     [[search searchButtonCell] drawWithFrame:unzoomedRect inView:documentViewFor(o)];
1788     [[search searchButtonCell] setControlView:nil];
1789
1790     return false;
1791 }
1792
1793 bool RenderThemeMac::paintSnapshottedPluginOverlay(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect&)
1794 {
1795     if (paintInfo.phase != PaintPhaseBlockBackground)
1796         return true;
1797
1798     if (!is<RenderBlock>(renderer))
1799         return true;
1800
1801     const RenderBlock& renderBlock = downcast<RenderBlock>(renderer);
1802
1803     LayoutUnit contentWidth = renderBlock.contentWidth();
1804     LayoutUnit contentHeight = renderBlock.contentHeight();
1805     if (!contentWidth || !contentHeight)
1806         return true;
1807
1808     GraphicsContext* context = paintInfo.context;
1809
1810     LayoutSize contentSize(contentWidth, contentHeight);
1811     LayoutPoint contentLocation = renderBlock.location();
1812     contentLocation.move(renderBlock.borderLeft() + renderBlock.paddingLeft(), renderBlock.borderTop() + renderBlock.paddingTop());
1813
1814     LayoutRect rect(contentLocation, contentSize);
1815     IntRect alignedRect = snappedIntRect(rect);
1816     if (alignedRect.width() <= 0 || alignedRect.height() <= 0)
1817         return true;
1818
1819     // We need to get the snapshot image from the plugin element, which should be available
1820     // from our node. Assuming this node is the plugin overlay element, we should get to the
1821     // plugin itself by asking for the shadow root parent, and then its parent.
1822
1823     if (!is<HTMLElement>(*renderBlock.element()))
1824         return true;
1825
1826     HTMLElement& plugInOverlay = downcast<HTMLElement>(*renderBlock.element());
1827     Element* parent = plugInOverlay.parentOrShadowHostElement();
1828     while (parent && !is<HTMLPlugInElement>(*parent))
1829         parent = parent->parentOrShadowHostElement();
1830
1831     if (!parent)
1832         return true;
1833
1834     HTMLPlugInElement& plugInElement = downcast<HTMLPlugInElement>(*parent);
1835     if (!is<HTMLPlugInImageElement>(plugInElement))
1836         return true;
1837
1838     HTMLPlugInImageElement& plugInImageElement = downcast<HTMLPlugInImageElement>(plugInElement);
1839
1840     Image* snapshot = plugInImageElement.snapshotImage();
1841     if (!snapshot)
1842         return true;
1843
1844     RenderSnapshottedPlugIn& plugInRenderer = downcast<RenderSnapshottedPlugIn>(*plugInImageElement.renderer());
1845     FloatPoint snapshotAbsPos = plugInRenderer.localToAbsolute();
1846     snapshotAbsPos.move(plugInRenderer.borderLeft() + plugInRenderer.paddingLeft(), plugInRenderer.borderTop() + plugInRenderer.paddingTop());
1847
1848     // We could draw the snapshot with that coordinates, but we need to make sure there
1849     // isn't a composited layer between us and the plugInRenderer.
1850     for (auto* renderBox = &downcast<RenderBox>(renderer); renderBox != &plugInRenderer; renderBox = renderBox->parentBox()) {
1851         if (renderBox->hasLayer() && renderBox->layer() && renderBox->layer()->isComposited()) {
1852             snapshotAbsPos = -renderBox->location();
1853             break;
1854         }
1855     }
1856
1857     LayoutSize pluginSize(plugInRenderer.contentWidth(), plugInRenderer.contentHeight());
1858     LayoutRect pluginRect(snapshotAbsPos, pluginSize);
1859     IntRect alignedPluginRect = snappedIntRect(pluginRect);
1860
1861     if (alignedPluginRect.width() <= 0 || alignedPluginRect.height() <= 0)
1862         return true;
1863
1864     context->drawImage(snapshot, plugInRenderer.style().colorSpace(), alignedPluginRect, CompositeSourceOver);
1865     return false;
1866 }
1867
1868 #if ENABLE(DATALIST_ELEMENT)
1869 IntSize RenderThemeMac::sliderTickSize() const
1870 {
1871     return IntSize(1, 3);
1872 }
1873
1874 int RenderThemeMac::sliderTickOffsetFromTrackCenter() const
1875 {
1876     return -9;
1877 }
1878 #endif
1879
1880 const int sliderThumbWidth = 15;
1881 const int sliderThumbHeight = 15;
1882
1883 void RenderThemeMac::adjustSliderThumbSize(RenderStyle& style, Element*) const
1884 {
1885     float zoomLevel = style.effectiveZoom();
1886     if (style.appearance() == SliderThumbHorizontalPart || style.appearance() == SliderThumbVerticalPart) {
1887         style.setWidth(Length(static_cast<int>(sliderThumbWidth * zoomLevel), Fixed));
1888         style.setHeight(Length(static_cast<int>(sliderThumbHeight * zoomLevel), Fixed));
1889     }
1890 }
1891
1892 bool RenderThemeMac::shouldShowPlaceholderWhenFocused() const
1893 {
1894     return true;
1895 }
1896
1897 bool RenderThemeMac::shouldHaveCapsLockIndicator(HTMLInputElement& element) const
1898 {
1899     return element.isPasswordField();
1900 }
1901
1902 NSPopUpButtonCell* RenderThemeMac::popupButton() const
1903 {
1904     if (!m_popupButton) {
1905         m_popupButton = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]);
1906         [m_popupButton.get() setUsesItemFromMenu:NO];
1907         [m_popupButton.get() setFocusRingType:NSFocusRingTypeExterior];
1908         // We don't want the app's UI layout direction to affect the appearance of popup buttons in
1909         // web content, which has its own layout direction.
1910         // FIXME: Make this depend on the directionality of the select element, once the rest of the
1911         // rendering code can account for the popup arrows appearing on the other side.
1912         [m_popupButton setUserInterfaceLayoutDirection:NSUserInterfaceLayoutDirectionLeftToRight];
1913     }
1914
1915     return m_popupButton.get();
1916 }
1917
1918 NSSearchFieldCell* RenderThemeMac::search() const
1919 {
1920     if (!m_search) {
1921         m_search = adoptNS([[NSSearchFieldCell alloc] initTextCell:@""]);
1922         [m_search.get() setBezelStyle:NSTextFieldRoundedBezel];
1923         [m_search.get() setBezeled:YES];
1924         [m_search.get() setEditable:YES];
1925         [m_search.get() setFocusRingType:NSFocusRingTypeExterior];
1926 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
1927         [m_search.get() setCenteredLook:NO];
1928 #endif
1929     }
1930
1931     return m_search.get();
1932 }
1933
1934 NSMenu* RenderThemeMac::searchMenuTemplate() const
1935 {
1936     if (!m_searchMenuTemplate)
1937         m_searchMenuTemplate = adoptNS([[NSMenu alloc] initWithTitle:@""]);
1938
1939     return m_searchMenuTemplate.get();
1940 }
1941
1942 NSSliderCell* RenderThemeMac::sliderThumbHorizontal() const
1943 {
1944     if (!m_sliderThumbHorizontal) {
1945         m_sliderThumbHorizontal = adoptNS([[NSSliderCell alloc] init]);
1946         [m_sliderThumbHorizontal.get() setSliderType:NSLinearSlider];
1947         [m_sliderThumbHorizontal.get() setControlSize:NSSmallControlSize];
1948         [m_sliderThumbHorizontal.get() setFocusRingType:NSFocusRingTypeExterior];
1949     }
1950
1951     return m_sliderThumbHorizontal.get();
1952 }
1953
1954 NSSliderCell* RenderThemeMac::sliderThumbVertical() const
1955 {
1956     if (!m_sliderThumbVertical) {
1957         m_sliderThumbVertical = adoptNS([[NSSliderCell alloc] init]);
1958         [m_sliderThumbVertical.get() setSliderType:NSLinearSlider];
1959         [m_sliderThumbVertical.get() setControlSize:NSSmallControlSize];
1960         [m_sliderThumbVertical.get() setFocusRingType:NSFocusRingTypeExterior];
1961     }
1962
1963     return m_sliderThumbVertical.get();
1964 }
1965
1966 NSTextFieldCell* RenderThemeMac::textField() const
1967 {
1968     if (!m_textField) {
1969         m_textField = adoptNS([[WebCoreTextFieldCell alloc] initTextCell:@""]);
1970         [m_textField.get() setBezeled:YES];
1971         [m_textField.get() setEditable:YES];
1972         [m_textField.get() setFocusRingType:NSFocusRingTypeExterior];
1973         // Post-Lion, WebCore can be in charge of paintinng the background thanks to
1974         // the workaround in place for <rdar://problem/11385461>, which is implemented
1975         // above as _coreUIDrawOptionsWithFrame.
1976         [m_textField.get() setDrawsBackground:NO];
1977     }
1978
1979     return m_textField.get();
1980 }
1981
1982 String RenderThemeMac::fileListNameForWidth(const FileList* fileList, const FontCascade& font, int width, bool multipleFilesAllowed) const
1983 {
1984     if (width <= 0)
1985         return String();
1986
1987     String strToTruncate;
1988     if (fileList->isEmpty())
1989         strToTruncate = fileListDefaultLabel(multipleFilesAllowed);
1990     else if (fileList->length() == 1)
1991         strToTruncate = [[NSFileManager defaultManager] displayNameAtPath:(fileList->item(0)->path())];
1992     else
1993         return StringTruncator::rightTruncate(multipleFileUploadText(fileList->length()), width, font, StringTruncator::EnableRoundingHacks);
1994
1995     return StringTruncator::centerTruncate(strToTruncate, width, font, StringTruncator::EnableRoundingHacks);
1996 }
1997
1998 bool RenderThemeMac::defaultButtonHasAnimation() const
1999 {
2000 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2001     return false;
2002 #else
2003     return true;
2004 #endif
2005 }
2006
2007 #if ENABLE(SERVICE_CONTROLS)
2008 NSServicesRolloverButtonCell* RenderThemeMac::servicesRolloverButtonCell() const
2009 {
2010 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2011     if (!m_servicesRolloverButton) {
2012         m_servicesRolloverButton = [NSServicesRolloverButtonCell serviceRolloverButtonCellForStyle:NSSharingServicePickerStyleRollover];
2013         [m_servicesRolloverButton setBezelStyle:NSRoundedDisclosureBezelStyle];
2014         [m_servicesRolloverButton setButtonType:NSPushOnPushOffButton];
2015         [m_servicesRolloverButton setImagePosition:NSImageOnly];
2016         [m_servicesRolloverButton setState:NO];
2017     }
2018
2019     return m_servicesRolloverButton.get();
2020 #else
2021     return nil;
2022 #endif
2023 }
2024
2025 bool RenderThemeMac::paintImageControlsButton(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& rect)
2026 {
2027     if (paintInfo.phase != PaintPhaseBlockBackground)
2028         return true;
2029
2030 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2031     NSServicesRolloverButtonCell *cell = servicesRolloverButtonCell();
2032
2033     LocalCurrentGraphicsContext localContext(paintInfo.context);
2034     GraphicsContextStateSaver stateSaver(*paintInfo.context);
2035
2036     paintInfo.context->translate(rect.x(), rect.y());
2037
2038     IntRect innerFrame(IntPoint(), rect.size());
2039     [cell drawWithFrame:innerFrame inView:documentViewFor(renderer)];
2040     [cell setControlView:nil];
2041 #else
2042     UNUSED_PARAM(renderer);
2043     UNUSED_PARAM(rect);
2044 #endif
2045
2046     return true;
2047 }
2048
2049 IntSize RenderThemeMac::imageControlsButtonSize(const RenderObject&) const
2050 {
2051 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2052     return IntSize(servicesRolloverButtonCell().cellSize);
2053 #else
2054     return IntSize();
2055 #endif
2056 }
2057
2058 IntSize RenderThemeMac::imageControlsButtonPositionOffset() const
2059 {
2060 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2061     // FIXME: Currently the offsets will always be the same no matter what image rect you try with.
2062     // This may not always be true in the future.
2063     static const int dummyDimension = 100;
2064     IntRect dummyImageRect(0, 0, dummyDimension, dummyDimension);
2065     NSRect bounds = [servicesRolloverButtonCell() rectForBounds:dummyImageRect preferredEdge:NSMinYEdge];
2066
2067     return IntSize(dummyDimension - bounds.origin.x, bounds.origin.y);
2068 #else
2069     return IntSize();
2070 #endif
2071 }
2072 #endif
2073
2074 #if ENABLE(ATTACHMENT_ELEMENT)
2075 const CGFloat attachmentIconSize = 48;
2076 const CGFloat attachmentIconBackgroundPadding = 6;
2077 const CGFloat attachmentIconBackgroundSize = attachmentIconSize + attachmentIconBackgroundPadding;
2078 const CGFloat attachmentIconSelectionBorderThickness = 1;
2079 const CGFloat attachmentIconBackgroundRadius = 3;
2080 const CGFloat attachmentIconToTitleMargin = 2;
2081
2082 static Color attachmentIconBackgroundColor() { return Color(0, 0, 0, 30); }
2083 static Color attachmentIconBorderColor() { return Color(255, 255, 255, 125); }
2084
2085 const CGFloat attachmentTitleFontSize = 12;
2086 const CGFloat attachmentTitleBackgroundRadius = 3;
2087 const CGFloat attachmentTitleBackgroundPadding = 3;
2088 const CGFloat attachmentTitleMaximumWidth = 100 - (attachmentTitleBackgroundPadding * 2);
2089 const CFIndex attachmentTitleMaximumLineCount = 2;
2090
2091 static Color attachmentTitleInactiveBackgroundColor() { return Color(204, 204, 204, 255); }
2092 static Color attachmentTitleInactiveTextColor() { return Color(100, 100, 100, 255); }
2093
2094 const CGFloat attachmentSubtitleFontSize = 10;
2095 static Color attachmentSubtitleTextColor() { return Color(82, 145, 214, 255); }
2096
2097 const CGFloat attachmentProgressBarWidth = 30;
2098 const CGFloat attachmentProgressBarHeight = 5;
2099 const CGFloat attachmentProgressBarOffset = -9;
2100 const CGFloat attachmentProgressBarBorderWidth = 1;
2101 static Color attachmentProgressBarBackgroundColor() { return Color(0, 0, 0, 89); }
2102 static Color attachmentProgressBarFillColor() { return Color(Color::white); }
2103 static Color attachmentProgressBarBorderColor() { return Color(0, 0, 0, 128); }
2104
2105 const CGFloat attachmentMargin = 3;
2106
2107 struct AttachmentLayout {
2108     explicit AttachmentLayout(const RenderAttachment&);
2109
2110     struct LabelLine {
2111         FloatRect backgroundRect;
2112         FloatPoint origin;
2113         RetainPtr<CTLineRef> line;
2114     };
2115
2116     Vector<LabelLine> lines;
2117
2118     FloatRect iconRect;
2119     FloatRect iconBackgroundRect;
2120     FloatRect attachmentRect;
2121
2122     int baseline;
2123
2124     RetainPtr<CTLineRef> subtitleLine;
2125     FloatRect subtitleTextRect;
2126
2127 private:
2128     void layOutTitle(const RenderAttachment&);
2129     void layOutSubtitle(const RenderAttachment&);
2130
2131     void addTitleLine(CTLineRef, CGFloat& yOffset, Vector<CGPoint> origins, CFIndex lineIndex, const RenderAttachment&);
2132 };
2133
2134 static NSColor *titleTextColorForAttachment(const RenderAttachment& attachment)
2135 {
2136     if (attachment.selectionState() != RenderObject::SelectionNone) {
2137         if (attachment.frame().selection().isFocusedAndActive())
2138             return [NSColor alternateSelectedControlTextColor];    
2139         return (NSColor *)cachedCGColor(attachmentTitleInactiveTextColor(), ColorSpaceDeviceRGB);
2140     }
2141
2142     return [NSColor blackColor];
2143 }
2144
2145 void AttachmentLayout::addTitleLine(CTLineRef line, CGFloat& yOffset, Vector<CGPoint> origins, CFIndex lineIndex, const RenderAttachment& attachment)
2146 {
2147     CGRect lineBounds = CTLineGetBoundsWithOptions(line, 0);
2148     CGFloat trailingWhitespaceWidth = CTLineGetTrailingWhitespaceWidth(line);
2149     CGFloat lineWidthIgnoringTrailingWhitespace = lineBounds.size.width - trailingWhitespaceWidth;
2150     CGFloat lineHeight = CGCeiling(lineBounds.size.height);
2151
2152     // Center the line relative to the icon.
2153     CGFloat xOffset = (attachmentIconBackgroundSize / 2) - (lineWidthIgnoringTrailingWhitespace / 2);
2154
2155     if (lineIndex)
2156         yOffset += origins[lineIndex - 1].y - origins[lineIndex].y;
2157
2158     LabelLine labelLine;
2159     labelLine.origin = FloatPoint(xOffset, yOffset + lineHeight - origins.last().y);
2160     labelLine.line = line;
2161     labelLine.backgroundRect = FloatRect(xOffset, yOffset, lineWidthIgnoringTrailingWhitespace, lineHeight);
2162     labelLine.backgroundRect.inflateX(attachmentTitleBackgroundPadding);
2163     labelLine.backgroundRect = encloseRectToDevicePixels(labelLine.backgroundRect, attachment.document().deviceScaleFactor());
2164
2165     // If the text rects are close in size, the curved enclosing background won't
2166     // look right, so make them the same exact size.
2167     if (!lines.isEmpty()) {
2168         float previousBackgroundRectWidth = lines.last().backgroundRect.width();
2169         if (fabs(labelLine.backgroundRect.width() - previousBackgroundRectWidth) < attachmentTitleBackgroundRadius * 4) {
2170             float newBackgroundRectWidth = std::max(previousBackgroundRectWidth, labelLine.backgroundRect.width());
2171             labelLine.backgroundRect.inflateX((newBackgroundRectWidth - labelLine.backgroundRect.width()) / 2);
2172             lines.last().backgroundRect.inflateX((newBackgroundRectWidth - previousBackgroundRectWidth) / 2);
2173         }
2174     }
2175
2176     lines.append(labelLine);
2177 }
2178
2179 void AttachmentLayout::layOutTitle(const RenderAttachment& attachment)
2180 {
2181     CFStringRef language = 0; // By not specifying a language we use the system language.
2182     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, attachmentTitleFontSize, language));
2183     baseline = CGRound(attachmentIconBackgroundSize + attachmentIconToTitleMargin + CTFontGetAscent(font.get()));
2184
2185     String title = attachment.attachmentElement().attachmentTitle();
2186     if (title.isEmpty())
2187         return;
2188
2189     NSDictionary *textAttributes = @{
2190         (id)kCTFontAttributeName: (id)font.get(),
2191         (id)kCTForegroundColorAttributeName: titleTextColorForAttachment(attachment)
2192     };
2193     RetainPtr<NSAttributedString> attributedTitle = adoptNS([[NSAttributedString alloc] initWithString:title attributes:textAttributes]);
2194     RetainPtr<CTFramesetterRef> titleFramesetter = adoptCF(CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedTitle.get()));
2195
2196     CFRange fitRange;
2197     CGSize titleTextSize = CTFramesetterSuggestFrameSizeWithConstraints(titleFramesetter.get(), CFRangeMake(0, 0), nullptr, CGSizeMake(attachmentTitleMaximumWidth, CGFLOAT_MAX), &fitRange);
2198
2199     RetainPtr<CGPathRef> titlePath = adoptCF(CGPathCreateWithRect(CGRectMake(0, 0, titleTextSize.width, titleTextSize.height), nullptr));
2200     RetainPtr<CTFrameRef> titleFrame = adoptCF(CTFramesetterCreateFrame(titleFramesetter.get(), fitRange, titlePath.get(), nullptr));
2201
2202     CFArrayRef ctLines = CTFrameGetLines(titleFrame.get());
2203     CFIndex lineCount = CFArrayGetCount(ctLines);
2204     if (!lineCount)
2205         return;
2206
2207     Vector<CGPoint> origins(lineCount);
2208     CTFrameGetLineOrigins(titleFrame.get(), CFRangeMake(0, 0), origins.data());
2209
2210     // Lay out and record the first (attachmentTitleMaximumLineCount - 1) lines.
2211     CFIndex lineIndex = 0;
2212     CGFloat yOffset = attachmentIconBackgroundSize + attachmentIconToTitleMargin;
2213     for (; lineIndex < std::min(attachmentTitleMaximumLineCount - 1, lineCount); ++lineIndex) {
2214         CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
2215         addTitleLine(line, yOffset, origins, lineIndex, attachment);
2216     }
2217
2218     if (lineIndex == lineCount)
2219         return;
2220
2221     // We had text that didn't fit in the first (attachmentTitleMaximumLineCount - 1) lines.
2222     // Combine it into one last line, and center-truncate it.
2223     CTLineRef firstRemainingLine = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
2224     CFIndex remainingRangeStart = CTLineGetStringRange(firstRemainingLine).location;
2225     NSRange remainingRange = NSMakeRange(remainingRangeStart, [attributedTitle length] - remainingRangeStart);
2226     NSAttributedString *remainingString = [attributedTitle attributedSubstringFromRange:remainingRange];
2227     RetainPtr<CTLineRef> remainingLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)remainingString));
2228     RetainPtr<NSAttributedString> ellipsisString = adoptNS([[NSAttributedString alloc] initWithString:@"\u2026" attributes:textAttributes]);
2229     RetainPtr<CTLineRef> ellipsisLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)ellipsisString.get()));
2230     RetainPtr<CTLineRef> truncatedLine = adoptCF(CTLineCreateTruncatedLine(remainingLine.get(), attachmentTitleMaximumWidth, kCTLineTruncationMiddle, ellipsisLine.get()));
2231
2232     if (!truncatedLine)
2233         truncatedLine = remainingLine;
2234
2235     addTitleLine(truncatedLine.get(), yOffset, origins, lineIndex, attachment);
2236 }
2237
2238 void AttachmentLayout::layOutSubtitle(const RenderAttachment& attachment)
2239 {
2240     String subtitleText = attachment.attachmentElement().fastGetAttribute(subtitleAttr);
2241
2242     if (subtitleText.isEmpty())
2243         return;
2244
2245     CFStringRef language = 0; // By not specifying a language we use the system language.
2246     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, attachmentSubtitleFontSize, language));
2247     NSDictionary *textAttributes = @{
2248         (id)kCTFontAttributeName: (id)font.get(),
2249         (id)kCTForegroundColorAttributeName: (NSColor *)cachedCGColor(attachmentSubtitleTextColor(), ColorSpaceDeviceRGB)
2250     };
2251     RetainPtr<NSAttributedString> attributedSubtitleText = adoptNS([[NSAttributedString alloc] initWithString:subtitleText attributes:textAttributes]);
2252     subtitleLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)attributedSubtitleText.get()));
2253
2254     CGRect lineBounds = CTLineGetBoundsWithOptions(subtitleLine.get(), 0);
2255
2256     // Center the line relative to the icon.
2257     CGFloat xOffset = (attachmentIconBackgroundSize / 2) - (lineBounds.size.width / 2);
2258     CGFloat yOffset = 0;
2259
2260     if (!lines.isEmpty())
2261         yOffset = lines.last().backgroundRect.maxY();
2262     else
2263         yOffset = attachmentIconBackgroundSize + attachmentIconToTitleMargin;
2264
2265     LabelLine labelLine;
2266     subtitleTextRect = FloatRect(xOffset, yOffset, lineBounds.size.width, lineBounds.size.height);
2267 }
2268
2269 AttachmentLayout::AttachmentLayout(const RenderAttachment& attachment)
2270 {
2271     layOutTitle(attachment);
2272     layOutSubtitle(attachment);
2273
2274     iconBackgroundRect = FloatRect(0, 0, attachmentIconBackgroundSize, attachmentIconBackgroundSize);
2275
2276     iconRect = iconBackgroundRect;
2277     iconRect.setSize(FloatSize(attachmentIconSize, attachmentIconSize));
2278     iconRect.move(attachmentIconBackgroundPadding / 2, attachmentIconBackgroundPadding / 2);
2279
2280     attachmentRect = iconBackgroundRect;
2281     for (const auto& line : lines)
2282         attachmentRect.unite(line.backgroundRect);
2283     attachmentRect.unite(subtitleTextRect);
2284     attachmentRect.inflate(attachmentMargin);
2285     attachmentRect = encloseRectToDevicePixels(attachmentRect, attachment.document().deviceScaleFactor());
2286 }
2287
2288 LayoutSize RenderThemeMac::attachmentIntrinsicSize(const RenderAttachment& attachment) const
2289 {
2290     AttachmentLayout layout(attachment);
2291     return LayoutSize(layout.attachmentRect.size());
2292 }
2293
2294 int RenderThemeMac::attachmentBaseline(const RenderAttachment& attachment) const
2295 {
2296     AttachmentLayout layout(attachment);
2297     return layout.baseline;
2298 }
2299
2300 static void paintAttachmentIconBackground(const RenderAttachment&, GraphicsContext& context, AttachmentLayout& layout)
2301 {
2302     // FIXME: Finder has a discontinuous behavior here when you have a background color other than white,
2303     // where it switches into 'bordered mode' and the border pops in on top of the background.
2304     bool paintBorder = true;
2305
2306     FloatRect backgroundRect = layout.iconBackgroundRect;
2307     if (paintBorder)
2308         backgroundRect.inflate(-attachmentIconSelectionBorderThickness);
2309
2310     context.fillRoundedRect(FloatRoundedRect(backgroundRect, FloatRoundedRect::Radii(attachmentIconBackgroundRadius)), attachmentIconBackgroundColor(), ColorSpaceDeviceRGB);
2311
2312     if (paintBorder) {
2313         FloatRect borderRect = layout.iconBackgroundRect;
2314         borderRect.inflate(-attachmentIconSelectionBorderThickness / 2);
2315
2316         FloatSize iconBackgroundRadiusSize(attachmentIconBackgroundRadius, attachmentIconBackgroundRadius);
2317         Path borderPath;
2318         borderPath.addRoundedRect(borderRect, iconBackgroundRadiusSize);
2319         context.setStrokeColor(attachmentIconBorderColor(), ColorSpaceDeviceRGB);
2320         context.setStrokeThickness(attachmentIconSelectionBorderThickness);
2321         context.strokePath(borderPath);
2322     }
2323 }
2324
2325 static void paintAttachmentIcon(const RenderAttachment& attachment, GraphicsContext& context, AttachmentLayout& layout)
2326 {
2327     Vector<String> filenames;
2328     if (File* file = attachment.attachmentElement().file())
2329         filenames.append(file->path());
2330     RefPtr<Icon> icon = Icon::createIconForFiles(filenames);
2331     if (!icon)
2332         return;
2333     icon->paint(context, layout.iconRect);
2334 }
2335
2336 static void addAttachmentTitleBackgroundRightCorner(Path& path, const FloatRect* fromRect, const FloatRect* toRect)
2337 {
2338     FloatSize horizontalRadius(attachmentTitleBackgroundRadius, 0);
2339     FloatSize verticalRadius(0, attachmentTitleBackgroundRadius);
2340
2341     if (!fromRect) {
2342         // For the first (top) rect:
2343
2344         path.moveTo(toRect->minXMinYCorner() + horizontalRadius);
2345
2346         // Across the top, towards the right.
2347         path.addLineTo(toRect->maxXMinYCorner() - horizontalRadius);
2348
2349         // Arc the top corner.
2350         path.addArcTo(toRect->maxXMinYCorner(), toRect->maxXMinYCorner() + verticalRadius, attachmentTitleBackgroundRadius);
2351
2352         // Down the right.
2353         path.addLineTo(toRect->maxXMaxYCorner() - verticalRadius);
2354     } else if (!toRect) {
2355         // For the last rect:
2356
2357         // Arc the bottom corner.
2358         path.addArcTo(fromRect->maxXMaxYCorner(), fromRect->maxXMaxYCorner() - horizontalRadius, attachmentTitleBackgroundRadius);
2359     } else {
2360         // For middle rects:
2361
2362         float widthDifference = toRect->width() - fromRect->width();
2363
2364         // Skip over very similar-width rects, because we can't make
2365         // sensible curves between them.
2366         if (fabs(widthDifference) < std::numeric_limits<float>::epsilon())
2367             return;
2368
2369         if (widthDifference < 0) {
2370             // Arc the outer corner.
2371             path.addArcTo(FloatPoint(fromRect->maxX(), toRect->y()), FloatPoint(fromRect->maxX(), toRect->y()) - horizontalRadius, attachmentTitleBackgroundRadius);
2372
2373             // Across the bottom, towards the left.
2374             path.addLineTo(toRect->maxXMinYCorner() + horizontalRadius);
2375
2376             // Arc the inner corner.
2377             path.addArcTo(toRect->maxXMinYCorner(), toRect->maxXMinYCorner() + verticalRadius, attachmentTitleBackgroundRadius);
2378         } else {
2379             // Arc the inner corner.
2380             path.addArcTo(FloatPoint(fromRect->maxX(), toRect->y()), FloatPoint(fromRect->maxX(), toRect->y()) + horizontalRadius, attachmentTitleBackgroundRadius);
2381
2382             // Across the bottom, towards the right.
2383             path.addLineTo(toRect->maxXMinYCorner() - horizontalRadius);
2384
2385             // Arc the outer corner.
2386             path.addArcTo(toRect->maxXMinYCorner(), toRect->maxXMinYCorner() + verticalRadius, attachmentTitleBackgroundRadius);
2387         }
2388
2389         // Down the right.
2390         path.addLineTo(toRect->maxXMaxYCorner() - verticalRadius);
2391     }
2392 }
2393
2394 static void addAttachmentTitleBackgroundLeftCorner(Path& path, const FloatRect* fromRect, const FloatRect* toRect)
2395 {
2396     FloatSize horizontalRadius(attachmentTitleBackgroundRadius, 0);
2397     FloatSize verticalRadius(0, attachmentTitleBackgroundRadius);
2398
2399     if (!fromRect) {
2400         // For the first (bottom) rect:
2401
2402         // Across the bottom, towards the left.
2403         path.addLineTo(toRect->minXMaxYCorner() + horizontalRadius);
2404
2405         // Arc the bottom corner.
2406         path.addArcTo(toRect->minXMaxYCorner(), toRect->minXMaxYCorner() - verticalRadius, attachmentTitleBackgroundRadius);
2407
2408         // Up the left.
2409         path.addLineTo(toRect->minXMinYCorner() + verticalRadius);
2410     } else if (!toRect) {
2411         // For the last (top) rect:
2412
2413         // Arc the top corner.
2414         path.addArcTo(fromRect->minXMinYCorner(), fromRect->minXMinYCorner() + horizontalRadius, attachmentTitleBackgroundRadius);
2415     } else {
2416         // For middle rects:
2417         float widthDifference = toRect->width() - fromRect->width();
2418
2419         // Skip over very similar-width rects, because we can't make
2420         // sensible curves between them.
2421         if (fabs(widthDifference) < std::numeric_limits<float>::epsilon())
2422             return;
2423
2424         if (widthDifference < 0) {
2425             // Arc the inner corner.
2426             path.addArcTo(FloatPoint(fromRect->x(), toRect->maxY()), FloatPoint(fromRect->x(), toRect->maxY()) + horizontalRadius, attachmentTitleBackgroundRadius);
2427
2428             // Across the bottom, towards the right.
2429             path.addLineTo(toRect->minXMaxYCorner() - horizontalRadius);
2430
2431             // Arc the outer corner.
2432             path.addArcTo(toRect->minXMaxYCorner(), toRect->minXMaxYCorner() - verticalRadius, attachmentTitleBackgroundRadius);
2433         } else {
2434             // Arc the outer corner.
2435             path.addArcTo(FloatPoint(fromRect->x(), toRect->maxY()), FloatPoint(fromRect->x(), toRect->maxY()) - horizontalRadius, attachmentTitleBackgroundRadius);
2436
2437             // Across the bottom, towards the left.
2438             path.addLineTo(toRect->minXMaxYCorner() + horizontalRadius);
2439
2440             // Arc the inner corner.
2441             path.addArcTo(toRect->minXMaxYCorner(), toRect->minXMaxYCorner() - verticalRadius, attachmentTitleBackgroundRadius);
2442         }
2443         
2444         // Up the right.
2445         path.addLineTo(toRect->minXMinYCorner() + verticalRadius);
2446     }
2447 }
2448
2449 static void paintAttachmentTitleBackground(const RenderAttachment& attachment, GraphicsContext& context, AttachmentLayout& layout)
2450 {
2451     if (layout.lines.isEmpty())
2452         return;
2453
2454     Path backgroundPath;
2455
2456     for (size_t i = 0; i <= layout.lines.size(); ++i)
2457         addAttachmentTitleBackgroundRightCorner(backgroundPath, i ? &layout.lines[i - 1].backgroundRect : nullptr, i < layout.lines.size() ? &layout.lines[i].backgroundRect : nullptr);
2458
2459     for (size_t i = 0; i <= layout.lines.size(); ++i) {
2460         size_t reverseIndex = layout.lines.size() - i;
2461         addAttachmentTitleBackgroundLeftCorner(backgroundPath, reverseIndex < layout.lines.size() ? &layout.lines[reverseIndex].backgroundRect : nullptr, reverseIndex ? &layout.lines[reverseIndex - 1].backgroundRect : nullptr);
2462     }
2463
2464     backgroundPath.closeSubpath();
2465
2466     Color backgroundColor;
2467     if (attachment.frame().selection().isFocusedAndActive())
2468         backgroundColor = convertNSColorToColor([NSColor alternateSelectedControlColor]);
2469     else
2470         backgroundColor = attachmentTitleInactiveBackgroundColor();
2471
2472     context.setFillColor(backgroundColor, ColorSpaceDeviceRGB);
2473     context.fillPath(backgroundPath);
2474 }
2475
2476 static void paintAttachmentTitle(const RenderAttachment&, GraphicsContext& context, AttachmentLayout& layout)
2477 {
2478     for (const auto& line : layout.lines) {
2479         GraphicsContextStateSaver saver(context);
2480
2481         context.translate(toFloatSize(line.origin));
2482         context.scale(FloatSize(1, -1));
2483
2484         CGContextSetTextMatrix(context.platformContext(), CGAffineTransformIdentity);
2485         CTLineDraw(line.line.get(), context.platformContext());
2486     }
2487 }
2488
2489 static void paintAttachmentSubtitle(const RenderAttachment&, GraphicsContext& context, AttachmentLayout& layout)
2490 {
2491     GraphicsContextStateSaver saver(context);
2492
2493     context.translate(toFloatSize(layout.subtitleTextRect.minXMaxYCorner()));
2494     context.scale(FloatSize(1, -1));
2495
2496     CGContextSetTextMatrix(context.platformContext(), CGAffineTransformIdentity);
2497     CTLineDraw(layout.subtitleLine.get(), context.platformContext());
2498 }
2499
2500 static void paintAttachmentProgress(const RenderAttachment& attachment, GraphicsContext& context, AttachmentLayout& layout)
2501 {
2502     String progressString = attachment.attachmentElement().fastGetAttribute(progressAttr);
2503     if (progressString.isEmpty())
2504         return;
2505     bool validProgress;
2506     float progress = progressString.toFloat(&validProgress);
2507     if (!validProgress)
2508         return;
2509
2510     GraphicsContextStateSaver saver(context);
2511
2512     FloatRect progressBounds((attachmentIconBackgroundSize - attachmentProgressBarWidth) / 2, layout.iconBackgroundRect.maxY() + attachmentProgressBarOffset - attachmentProgressBarHeight, attachmentProgressBarWidth, attachmentProgressBarHeight);
2513
2514     FloatRect borderRect = progressBounds;
2515     borderRect.inflate(-0.5);
2516     FloatRect backgroundRect = borderRect;
2517     backgroundRect.inflate(-attachmentProgressBarBorderWidth / 2);
2518
2519     FloatRoundedRect backgroundRoundedRect(backgroundRect, FloatRoundedRect::Radii(backgroundRect.height() / 2));
2520     context.fillRoundedRect(backgroundRoundedRect, attachmentProgressBarBackgroundColor(), ColorSpaceDeviceRGB);
2521
2522     {
2523         GraphicsContextStateSaver clipSaver(context);
2524         context.clipRoundedRect(backgroundRoundedRect);
2525
2526         FloatRect progressRect = progressBounds;
2527         progressRect.setWidth(progressRect.width() * progress);
2528         progressRect = encloseRectToDevicePixels(progressRect, attachment.document().deviceScaleFactor());
2529
2530         context.fillRect(progressRect, attachmentProgressBarFillColor(), ColorSpaceDeviceRGB);
2531     }
2532
2533     Path borderPath;
2534     float borderRadius = borderRect.height() / 2;
2535     borderPath.addRoundedRect(borderRect, FloatSize(borderRadius, borderRadius));
2536     context.setStrokeColor(attachmentProgressBarBorderColor(), ColorSpaceDeviceRGB);
2537     context.setStrokeThickness(attachmentProgressBarBorderWidth);
2538     context.strokePath(borderPath);
2539 }
2540
2541 bool RenderThemeMac::paintAttachment(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& paintRect)
2542 {
2543     if (!is<RenderAttachment>(renderer))
2544         return false;
2545
2546     const RenderAttachment& attachment = downcast<RenderAttachment>(renderer);
2547
2548     AttachmentLayout layout(attachment);
2549
2550     GraphicsContext& context = *paintInfo.context;
2551     LocalCurrentGraphicsContext localContext(&context);
2552     GraphicsContextStateSaver saver(context);
2553
2554     context.translate(toFloatSize(paintRect.location()));
2555     context.translate(FloatSize((layout.attachmentRect.width() - attachmentIconBackgroundSize) / 2, 0));
2556
2557     bool useSelectedStyle = attachment.selectionState() != RenderObject::SelectionNone;
2558
2559     if (useSelectedStyle)
2560         paintAttachmentIconBackground(attachment, context, layout);
2561     paintAttachmentIcon(attachment, context, layout);
2562     if (useSelectedStyle)
2563         paintAttachmentTitleBackground(attachment, context, layout);
2564     paintAttachmentTitle(attachment, context, layout);
2565     paintAttachmentSubtitle(attachment, context, layout);
2566     paintAttachmentProgress(attachment, context, layout);
2567
2568     return true;
2569 }
2570
2571 #endif // ENABLE(ATTACHMENT_ELEMENT)
2572
2573 } // namespace WebCore
2574
2575 #endif // !PLATFORM(IOS)