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