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