[GTK] Menu list button doesn't use the text color from the theme
[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&, const 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&, const 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&, const 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, const 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 LengthBox RenderThemeMac::popupInternalPaddingBox(const RenderStyle& style) const
1369 {
1370     if (style.appearance() == MenulistPart) {
1371         return { static_cast<int>(popupButtonPadding(controlSizeForFont(style))[topPadding] * style.effectiveZoom()),
1372             static_cast<int>(popupButtonPadding(controlSizeForFont(style))[rightPadding] * style.effectiveZoom()),
1373             static_cast<int>(popupButtonPadding(controlSizeForFont(style))[bottomPadding] * style.effectiveZoom()),
1374             static_cast<int>(popupButtonPadding(controlSizeForFont(style))[leftPadding] * style.effectiveZoom()) };
1375     }
1376
1377     if (style.appearance() == MenulistButtonPart) {
1378         float arrowWidth = baseArrowWidth * (style.fontSize() / baseFontSize);
1379         return { static_cast<int>(styledPopupPaddingTop * style.effectiveZoom()),
1380             static_cast<int>(ceilf(arrowWidth + (arrowPaddingLeft + arrowPaddingRight + paddingBeforeSeparator) * style.effectiveZoom())),
1381             static_cast<int>(styledPopupPaddingBottom * style.effectiveZoom()), static_cast<int>(styledPopupPaddingLeft * style.effectiveZoom()) };
1382     }
1383
1384     return { 0, 0, 0, 0 };
1385 }
1386
1387 PopupMenuStyle::PopupMenuSize RenderThemeMac::popupMenuSize(const RenderStyle& style, IntRect& rect) const
1388 {
1389     NSPopUpButtonCell* popupButton = this->popupButton();
1390     NSControlSize size = controlSizeForCell(popupButton, popupButtonSizes(), rect.size(), style.effectiveZoom());
1391     switch (size) {
1392 #pragma clang diagnostic push
1393 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1394     case NSRegularControlSize:
1395         return PopupMenuStyle::PopupMenuSizeNormal;
1396     case NSSmallControlSize:
1397         return PopupMenuStyle::PopupMenuSizeSmall;
1398     case NSMiniControlSize:
1399         return PopupMenuStyle::PopupMenuSizeMini;
1400 #pragma clang diagnostic pop
1401     default:
1402         return PopupMenuStyle::PopupMenuSizeNormal;
1403     }
1404 }
1405
1406 void RenderThemeMac::adjustMenuListButtonStyle(StyleResolver&, RenderStyle& style, const Element*) const
1407 {
1408     float fontScale = style.fontSize() / baseFontSize;
1409
1410     style.resetPadding();
1411     style.setBorderRadius(IntSize(int(baseBorderRadius + fontScale - 1), int(baseBorderRadius + fontScale - 1))); // FIXME: Round up?
1412
1413     const int minHeight = 15;
1414     style.setMinHeight(Length(minHeight, Fixed));
1415
1416     style.setLineHeight(RenderStyle::initialLineHeight());
1417 }
1418
1419 void RenderThemeMac::setPopupButtonCellState(const RenderObject& o, const IntSize& buttonSize)
1420 {
1421     NSPopUpButtonCell* popupButton = this->popupButton();
1422
1423     // Set the control size based off the rectangle we're painting into.
1424     setControlSize(popupButton, popupButtonSizes(), buttonSize, o.style().effectiveZoom());
1425
1426     // Update the various states we respond to.
1427     updateCheckedState(popupButton, o);
1428     updateEnabledState(popupButton, o);
1429     updatePressedState(popupButton, o);
1430 }
1431
1432 void RenderThemeMac::paintCellAndSetFocusedElementNeedsRepaintIfNecessary(NSCell* cell, const RenderObject& renderer, const PaintInfo& paintInfo, const FloatRect& rect)
1433 {
1434     Page* page = renderer.document().page();
1435     bool shouldDrawFocusRing = isFocused(renderer) && renderer.style().outlineStyleIsAuto();
1436     bool shouldUseImageBuffer = renderer.style().effectiveZoom() != 1 || page->pageScaleFactor() != 1;
1437     bool shouldDrawCell = true;
1438     if (ThemeMac::drawCellOrFocusRingWithViewIntoContext(cell, paintInfo.context(), rect, documentViewFor(renderer), shouldDrawCell, shouldDrawFocusRing, shouldUseImageBuffer, page->deviceScaleFactor()))
1439         page->focusController().setFocusedElementNeedsRepaint();
1440 }
1441
1442 const IntSize* RenderThemeMac::menuListSizes() const
1443 {
1444     static const IntSize sizes[3] = { IntSize(9, 0), IntSize(5, 0), IntSize(0, 0) };
1445     return sizes;
1446 }
1447
1448 int RenderThemeMac::minimumMenuListSize(const RenderStyle& style) const
1449 {
1450     return sizeForSystemFont(style, menuListSizes()).width();
1451 }
1452
1453 const int trackWidth = 5;
1454 const int trackRadius = 2;
1455
1456 void RenderThemeMac::adjustSliderTrackStyle(StyleResolver&, RenderStyle& style, const Element*) const
1457 {
1458     style.setBoxShadow(nullptr);
1459 }
1460
1461 bool RenderThemeMac::paintSliderTrack(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1462 {
1463     IntRect bounds = r;
1464     float zoomLevel = o.style().effectiveZoom();
1465     float zoomedTrackWidth = trackWidth * zoomLevel;
1466
1467     if (o.style().appearance() ==  SliderHorizontalPart || o.style().appearance() ==  MediaSliderPart) {
1468         bounds.setHeight(zoomedTrackWidth);
1469         bounds.setY(r.y() + r.height() / 2 - zoomedTrackWidth / 2);
1470     } else if (o.style().appearance() == SliderVerticalPart) {
1471         bounds.setWidth(zoomedTrackWidth);
1472         bounds.setX(r.x() + r.width() / 2 - zoomedTrackWidth / 2);
1473     }
1474
1475     LocalCurrentGraphicsContext localContext(paintInfo.context());
1476     CGContextRef context = localContext.cgContext();
1477     CGColorSpaceRef cspace = sRGBColorSpaceRef();
1478
1479 #if ENABLE(DATALIST_ELEMENT)
1480     paintSliderTicks(o, paintInfo, r);
1481 #endif
1482
1483     GraphicsContextStateSaver stateSaver(paintInfo.context());
1484     CGContextClipToRect(context, bounds);
1485
1486     struct CGFunctionCallbacks mainCallbacks = { 0, TrackGradientInterpolate, NULL };
1487     RetainPtr<CGFunctionRef> mainFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &mainCallbacks));
1488     RetainPtr<CGShadingRef> mainShading;
1489     if (o.style().appearance() == SliderVerticalPart)
1490         mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.maxY()), CGPointMake(bounds.maxX(), bounds.maxY()), mainFunction.get(), false, false));
1491     else
1492         mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.y()), CGPointMake(bounds.x(), bounds.maxY()), mainFunction.get(), false, false));
1493
1494     IntSize radius(trackRadius, trackRadius);
1495     paintInfo.context().clipRoundedRect(FloatRoundedRect(bounds, radius, radius, radius, radius));
1496     context = localContext.cgContext();
1497     CGContextDrawShading(context, mainShading.get());
1498
1499     return false;
1500 }
1501
1502 void RenderThemeMac::adjustSliderThumbStyle(StyleResolver& styleResolver, RenderStyle& style, const Element* element) const
1503 {
1504     RenderTheme::adjustSliderThumbStyle(styleResolver, style, element);
1505     style.setBoxShadow(nullptr);
1506 }
1507
1508 const float verticalSliderHeightPadding = 0.1f;
1509
1510 bool RenderThemeMac::paintSliderThumb(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1511 {
1512     NSSliderCell* sliderThumbCell = o.style().appearance() == SliderThumbVerticalPart
1513         ? sliderThumbVertical()
1514         : sliderThumbHorizontal();
1515
1516     LocalCurrentGraphicsContext localContext(paintInfo.context());
1517
1518     // Update the various states we respond to.
1519     updateEnabledState(sliderThumbCell, o);
1520         Element* focusDelegate = is<Element>(o.node()) ? downcast<Element>(*o.node()).focusDelegate() : nullptr;
1521     if (focusDelegate)
1522         updateFocusedState(sliderThumbCell, *focusDelegate->renderer());
1523
1524     // Update the pressed state using the NSCell tracking methods, since that's how NSSliderCell keeps track of it.
1525     bool oldPressed;
1526     if (o.style().appearance() == SliderThumbVerticalPart)
1527         oldPressed = m_isSliderThumbVerticalPressed;
1528     else
1529         oldPressed = m_isSliderThumbHorizontalPressed;
1530
1531     bool pressed = isPressed(o);
1532
1533     if (o.style().appearance() == SliderThumbVerticalPart)
1534         m_isSliderThumbVerticalPressed = pressed;
1535     else
1536         m_isSliderThumbHorizontalPressed = pressed;
1537
1538     NSView *view = documentViewFor(o);
1539
1540     if (pressed != oldPressed) {
1541         if (pressed)
1542             [sliderThumbCell startTrackingAt:NSPoint() inView:view];
1543         else
1544             [sliderThumbCell stopTracking:NSPoint() at:NSPoint() inView:view mouseIsUp:YES];
1545     }
1546
1547     FloatRect bounds = r;
1548     // Make the height of the vertical slider slightly larger so NSSliderCell will draw a vertical slider.
1549     if (o.style().appearance() == SliderThumbVerticalPart)
1550         bounds.setHeight(bounds.height() + verticalSliderHeightPadding * o.style().effectiveZoom());
1551
1552     GraphicsContextStateSaver stateSaver(paintInfo.context());
1553     float zoomLevel = o.style().effectiveZoom();
1554
1555     FloatRect unzoomedRect = bounds;
1556     if (zoomLevel != 1.0f) {
1557         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1558         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1559         paintInfo.context().translate(unzoomedRect.x(), unzoomedRect.y());
1560         paintInfo.context().scale(FloatSize(zoomLevel, zoomLevel));
1561         paintInfo.context().translate(-unzoomedRect.x(), -unzoomedRect.y());
1562     }
1563
1564     bool shouldDrawCell = true;
1565     bool shouldDrawFocusRing = false;
1566     float deviceScaleFactor = o.document().page()->deviceScaleFactor();
1567     bool shouldUseImageBuffer = deviceScaleFactor != 1 || zoomLevel != 1;
1568     ThemeMac::drawCellOrFocusRingWithViewIntoContext(sliderThumbCell, paintInfo.context(), unzoomedRect, view, shouldDrawCell, shouldDrawFocusRing, shouldUseImageBuffer, deviceScaleFactor);
1569     [sliderThumbCell setControlView:nil];
1570
1571     return false;
1572 }
1573
1574 bool RenderThemeMac::paintSearchField(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1575 {
1576     LocalCurrentGraphicsContext localContext(paintInfo.context());
1577     NSSearchFieldCell* search = this->search();
1578
1579     setSearchCellState(o, r);
1580
1581     GraphicsContextStateSaver stateSaver(paintInfo.context());
1582
1583     float zoomLevel = o.style().effectiveZoom();
1584
1585     IntRect unzoomedRect = r;
1586
1587     if (zoomLevel != 1.0f) {
1588         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1589         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1590         paintInfo.context().translate(unzoomedRect.x(), unzoomedRect.y());
1591         paintInfo.context().scale(FloatSize(zoomLevel, zoomLevel));
1592         paintInfo.context().translate(-unzoomedRect.x(), -unzoomedRect.y());
1593     }
1594
1595     // Set the search button to nil before drawing.  Then reset it so we can draw it later.
1596     [search setSearchButtonCell:nil];
1597
1598     paintCellAndSetFocusedElementNeedsRepaintIfNecessary(search, o, paintInfo, unzoomedRect);
1599     [search setControlView:nil];
1600     [search resetSearchButtonCell];
1601
1602     return false;
1603 }
1604
1605 void RenderThemeMac::setSearchCellState(const RenderObject& o, const IntRect&)
1606 {
1607     NSSearchFieldCell* search = this->search();
1608
1609     [search setPlaceholderString:@""];
1610     [search setControlSize:controlSizeForFont(o.style())];
1611
1612     // Update the various states we respond to.
1613     updateEnabledState(search, o);
1614     updateFocusedState(search, o);
1615 }
1616
1617 const IntSize* RenderThemeMac::searchFieldSizes() const
1618 {
1619     static const IntSize sizes[3] = { IntSize(0, 22), IntSize(0, 19), IntSize(0, 17) };
1620     return sizes;
1621 }
1622
1623 void RenderThemeMac::setSearchFieldSize(RenderStyle& style) const
1624 {
1625     // If the width and height are both specified, then we have nothing to do.
1626     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
1627         return;
1628
1629     // Use the font size to determine the intrinsic width of the control.
1630     setSizeFromFont(style, searchFieldSizes());
1631 }
1632
1633 void RenderThemeMac::adjustSearchFieldStyle(StyleResolver& styleResolver, RenderStyle& style, const Element*) const
1634 {
1635     // Override border.
1636     style.resetBorder();
1637     const short borderWidth = 2 * style.effectiveZoom();
1638     style.setBorderLeftWidth(borderWidth);
1639     style.setBorderLeftStyle(INSET);
1640     style.setBorderRightWidth(borderWidth);
1641     style.setBorderRightStyle(INSET);
1642     style.setBorderBottomWidth(borderWidth);
1643     style.setBorderBottomStyle(INSET);
1644     style.setBorderTopWidth(borderWidth);
1645     style.setBorderTopStyle(INSET);
1646
1647     // Override height.
1648     style.setHeight(Length(Auto));
1649     setSearchFieldSize(style);
1650
1651     // Override padding size to match AppKit text positioning.
1652     const int padding = 1 * style.effectiveZoom();
1653     style.setPaddingLeft(Length(padding, Fixed));
1654     style.setPaddingRight(Length(padding, Fixed));
1655     style.setPaddingTop(Length(padding, Fixed));
1656     style.setPaddingBottom(Length(padding, Fixed));
1657
1658     NSControlSize controlSize = controlSizeForFont(style);
1659     setFontFromControlSize(styleResolver, style, controlSize);
1660
1661     style.setBoxShadow(nullptr);
1662 }
1663
1664 bool RenderThemeMac::paintSearchFieldCancelButton(const RenderBox& box, const PaintInfo& paintInfo, const IntRect& r)
1665 {
1666     auto adjustedCancelButtonRect = [this, &box] (const FloatRect& localBoundsForCancelButton) -> FloatRect
1667     {
1668         IntSize cancelButtonSizeBasedOnFontSize = sizeForSystemFont(box.style(), cancelButtonSizes());
1669         FloatSize diff = localBoundsForCancelButton.size() - FloatSize(cancelButtonSizeBasedOnFontSize);
1670         if (!diff.width() && !diff.height())
1671             return localBoundsForCancelButton;
1672         // Vertically centered and right aligned.
1673         FloatRect adjustedLocalBoundsForCancelButton = localBoundsForCancelButton;
1674         adjustedLocalBoundsForCancelButton.move(diff.width(), floorToDevicePixel(diff.height() / 2, box.document().deviceScaleFactor()));
1675         adjustedLocalBoundsForCancelButton.setSize(cancelButtonSizeBasedOnFontSize);
1676         return adjustedLocalBoundsForCancelButton;
1677     };
1678
1679     if (!box.element())
1680         return false;
1681     Element* input = box.element()->shadowHost();
1682     if (!input)
1683         input = box.element();
1684
1685     if (!is<RenderBox>(input->renderer()))
1686         return false;
1687
1688     const RenderBox& inputBox = downcast<RenderBox>(*input->renderer());
1689     LocalCurrentGraphicsContext localContext(paintInfo.context());
1690     setSearchCellState(inputBox, r);
1691
1692     NSSearchFieldCell* search = this->search();
1693
1694     if (!input->isDisabledFormControl() && (is<HTMLTextFormControlElement>(*input) && !downcast<HTMLTextFormControlElement>(*input).isReadOnly()))
1695         updatePressedState([search cancelButtonCell], box);
1696     else if ([[search cancelButtonCell] isHighlighted])
1697         [[search cancelButtonCell] setHighlighted:NO];
1698
1699     GraphicsContextStateSaver stateSaver(paintInfo.context());
1700
1701     float zoomLevel = box.style().effectiveZoom();
1702
1703     FloatRect localBounds = adjustedCancelButtonRect([search cancelButtonRectForBounds:NSRect(snappedIntRect(inputBox.contentBoxRect()))]);
1704     FloatPoint paintingPos = convertToPaintingPosition(inputBox, box, localBounds.location(), r.location());
1705
1706     FloatRect unzoomedRect(paintingPos, localBounds.size());
1707     if (zoomLevel != 1.0f) {
1708         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1709         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1710         paintInfo.context().translate(unzoomedRect.x(), unzoomedRect.y());
1711         paintInfo.context().scale(FloatSize(zoomLevel, zoomLevel));
1712         paintInfo.context().translate(-unzoomedRect.x(), -unzoomedRect.y());
1713     }
1714     [[search cancelButtonCell] drawWithFrame:unzoomedRect inView:documentViewFor(box)];
1715     [[search cancelButtonCell] setControlView:nil];
1716     return false;
1717 }
1718
1719 const IntSize* RenderThemeMac::cancelButtonSizes() const
1720 {
1721     static const IntSize sizes[3] = { IntSize(22, 22), IntSize(19, 19), IntSize(15, 15) };
1722     return sizes;
1723 }
1724
1725 void RenderThemeMac::adjustSearchFieldCancelButtonStyle(StyleResolver&, RenderStyle& style, const Element*) const
1726 {
1727     IntSize size = sizeForSystemFont(style, cancelButtonSizes());
1728     style.setWidth(Length(size.width(), Fixed));
1729     style.setHeight(Length(size.height(), Fixed));
1730     style.setBoxShadow(nullptr);
1731 }
1732
1733 const int resultsArrowWidth = 5;
1734 const IntSize* RenderThemeMac::resultsButtonSizes() const
1735 {
1736     static const IntSize sizes[3] = { IntSize(19, 22), IntSize(17, 19), IntSize(17, 15) };
1737     return sizes;
1738 }
1739
1740 const int emptyResultsOffset = 9;
1741 void RenderThemeMac::adjustSearchFieldDecorationPartStyle(StyleResolver&, RenderStyle& style, const Element*) const
1742 {
1743     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
1744     style.setWidth(Length(size.width() - emptyResultsOffset, Fixed));
1745     style.setHeight(Length(size.height(), Fixed));
1746     style.setBoxShadow(nullptr);
1747 }
1748
1749 bool RenderThemeMac::paintSearchFieldDecorationPart(const RenderObject&, const PaintInfo&, const IntRect&)
1750 {
1751     return false;
1752 }
1753
1754 void RenderThemeMac::adjustSearchFieldResultsDecorationPartStyle(StyleResolver&, RenderStyle& style, const Element*) const
1755 {
1756     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
1757     style.setWidth(Length(size.width(), Fixed));
1758     style.setHeight(Length(size.height(), Fixed));
1759     style.setBoxShadow(nullptr);
1760 }
1761
1762 bool RenderThemeMac::paintSearchFieldResultsDecorationPart(const RenderBox& box, const PaintInfo& paintInfo, const IntRect& r)
1763 {
1764     if (!box.element())
1765         return false;
1766     Element* input = box.element()->shadowHost();
1767     if (!input)
1768         input = box.element();
1769     if (!is<RenderBox>(input->renderer()))
1770         return false;
1771     
1772     const RenderBox& inputBox = downcast<RenderBox>(*input->renderer());
1773     LocalCurrentGraphicsContext localContext(paintInfo.context());
1774     setSearchCellState(inputBox, r);
1775
1776     NSSearchFieldCell* search = this->search();
1777
1778     if ([search searchMenuTemplate] != nil)
1779         [search setSearchMenuTemplate:nil];
1780
1781     FloatRect localBounds = [search searchButtonRectForBounds:NSRect(snappedIntRect(inputBox.borderBoxRect()))];
1782     FloatPoint paintingPos = convertToPaintingPosition(inputBox, box, localBounds.location(), r.location());
1783     localBounds.setLocation(paintingPos);
1784
1785     [[search searchButtonCell] drawWithFrame:localBounds inView:documentViewFor(box)];
1786     [[search searchButtonCell] setControlView:nil];
1787     return false;
1788 }
1789
1790 void RenderThemeMac::adjustSearchFieldResultsButtonStyle(StyleResolver&, RenderStyle& style, const Element*) const
1791 {
1792     IntSize size = sizeForSystemFont(style, resultsButtonSizes());
1793     style.setWidth(Length(size.width() + resultsArrowWidth, Fixed));
1794     style.setHeight(Length(size.height(), Fixed));
1795     style.setBoxShadow(nullptr);
1796 }
1797
1798 bool RenderThemeMac::paintSearchFieldResultsButton(const RenderBox& box, const PaintInfo& paintInfo, const IntRect& r)
1799 {
1800     auto adjustedResultButtonRect = [this, &box] (const FloatRect& localBounds) -> FloatRect
1801     {
1802         IntSize buttonSize = sizeForSystemFont(box.style(), resultsButtonSizes());
1803         buttonSize.expand(resultsArrowWidth, 0);
1804         FloatSize diff = localBounds.size() - FloatSize(buttonSize);
1805         if (!diff.isZero())
1806             return localBounds;
1807         // Vertically centered and left aligned.
1808         FloatRect adjustedLocalBounds = localBounds;
1809         adjustedLocalBounds.move(0, floorToDevicePixel(diff.height() / 2, box.document().deviceScaleFactor()));
1810         adjustedLocalBounds.setSize(buttonSize);
1811         return adjustedLocalBounds;
1812     };
1813
1814     Element* input = box.element()->shadowHost();
1815     if (!input)
1816         input = box.element();
1817     if (!is<RenderBox>(input->renderer()))
1818         return false;
1819     
1820     const RenderBox& inputBox = downcast<RenderBox>(*input->renderer());
1821     LocalCurrentGraphicsContext localContext(paintInfo.context());
1822     setSearchCellState(inputBox, r);
1823
1824     NSSearchFieldCell* search = this->search();
1825
1826     if (![search searchMenuTemplate])
1827         [search setSearchMenuTemplate:searchMenuTemplate()];
1828
1829     GraphicsContextStateSaver stateSaver(paintInfo.context());
1830     float zoomLevel = box.style().effectiveZoom();
1831
1832     FloatRect localBounds = adjustedResultButtonRect([search searchButtonRectForBounds:NSRect(snappedIntRect(inputBox.contentBoxRect()))]);
1833     FloatPoint paintingPos = convertToPaintingPosition(inputBox, box, localBounds.location(), r.location());
1834     
1835     FloatRect unzoomedRect(paintingPos, localBounds.size());
1836     if (zoomLevel != 1.0f) {
1837         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1838         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1839         paintInfo.context().translate(unzoomedRect.x(), unzoomedRect.y());
1840         paintInfo.context().scale(FloatSize(zoomLevel, zoomLevel));
1841         paintInfo.context().translate(-unzoomedRect.x(), -unzoomedRect.y());
1842     }
1843
1844     [[search searchButtonCell] drawWithFrame:unzoomedRect inView:documentViewFor(box)];
1845     [[search searchButtonCell] setControlView:nil];
1846
1847     return false;
1848 }
1849
1850 bool RenderThemeMac::paintSnapshottedPluginOverlay(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect&)
1851 {
1852     if (paintInfo.phase != PaintPhaseBlockBackground)
1853         return true;
1854
1855     if (!is<RenderBlock>(renderer))
1856         return true;
1857
1858     const RenderBlock& renderBlock = downcast<RenderBlock>(renderer);
1859
1860     LayoutUnit contentWidth = renderBlock.contentWidth();
1861     LayoutUnit contentHeight = renderBlock.contentHeight();
1862     if (!contentWidth || !contentHeight)
1863         return true;
1864
1865     GraphicsContext& context = paintInfo.context();
1866
1867     LayoutSize contentSize(contentWidth, contentHeight);
1868     LayoutPoint contentLocation = renderBlock.location();
1869     contentLocation.move(renderBlock.borderLeft() + renderBlock.paddingLeft(), renderBlock.borderTop() + renderBlock.paddingTop());
1870
1871     LayoutRect rect(contentLocation, contentSize);
1872     IntRect alignedRect = snappedIntRect(rect);
1873     if (alignedRect.width() <= 0 || alignedRect.height() <= 0)
1874         return true;
1875
1876     // We need to get the snapshot image from the plugin element, which should be available
1877     // from our node. Assuming this node is the plugin overlay element, we should get to the
1878     // plugin itself by asking for the shadow root parent, and then its parent.
1879
1880     if (!is<HTMLElement>(*renderBlock.element()))
1881         return true;
1882
1883     HTMLElement& plugInOverlay = downcast<HTMLElement>(*renderBlock.element());
1884     Element* parent = plugInOverlay.parentOrShadowHostElement();
1885     while (parent && !is<HTMLPlugInElement>(*parent))
1886         parent = parent->parentOrShadowHostElement();
1887
1888     if (!parent)
1889         return true;
1890
1891     HTMLPlugInElement& plugInElement = downcast<HTMLPlugInElement>(*parent);
1892     if (!is<HTMLPlugInImageElement>(plugInElement))
1893         return true;
1894
1895     HTMLPlugInImageElement& plugInImageElement = downcast<HTMLPlugInImageElement>(plugInElement);
1896
1897     Image* snapshot = plugInImageElement.snapshotImage();
1898     if (!snapshot)
1899         return true;
1900
1901     RenderSnapshottedPlugIn& plugInRenderer = downcast<RenderSnapshottedPlugIn>(*plugInImageElement.renderer());
1902     FloatPoint snapshotAbsPos = plugInRenderer.localToAbsolute();
1903     snapshotAbsPos.move(plugInRenderer.borderLeft() + plugInRenderer.paddingLeft(), plugInRenderer.borderTop() + plugInRenderer.paddingTop());
1904
1905     // We could draw the snapshot with that coordinates, but we need to make sure there
1906     // isn't a composited layer between us and the plugInRenderer.
1907     for (auto* renderBox = &downcast<RenderBox>(renderer); renderBox != &plugInRenderer; renderBox = renderBox->parentBox()) {
1908         if (renderBox->isComposited()) {
1909             snapshotAbsPos = -renderBox->location();
1910             break;
1911         }
1912     }
1913
1914     LayoutSize pluginSize(plugInRenderer.contentWidth(), plugInRenderer.contentHeight());
1915     LayoutRect pluginRect(snapshotAbsPos, pluginSize);
1916     IntRect alignedPluginRect = snappedIntRect(pluginRect);
1917
1918     if (alignedPluginRect.width() <= 0 || alignedPluginRect.height() <= 0)
1919         return true;
1920
1921     context.drawImage(*snapshot, alignedPluginRect, CompositeSourceOver);
1922     return false;
1923 }
1924
1925 #if ENABLE(DATALIST_ELEMENT)
1926 IntSize RenderThemeMac::sliderTickSize() const
1927 {
1928     return IntSize(1, 3);
1929 }
1930
1931 int RenderThemeMac::sliderTickOffsetFromTrackCenter() const
1932 {
1933     return -9;
1934 }
1935 #endif
1936
1937 const int sliderThumbWidth = 15;
1938 const int sliderThumbHeight = 15;
1939
1940 void RenderThemeMac::adjustSliderThumbSize(RenderStyle& style, const Element*) const
1941 {
1942     float zoomLevel = style.effectiveZoom();
1943     if (style.appearance() == SliderThumbHorizontalPart || style.appearance() == SliderThumbVerticalPart) {
1944         style.setWidth(Length(static_cast<int>(sliderThumbWidth * zoomLevel), Fixed));
1945         style.setHeight(Length(static_cast<int>(sliderThumbHeight * zoomLevel), Fixed));
1946     }
1947 }
1948
1949 bool RenderThemeMac::shouldHaveCapsLockIndicator(const HTMLInputElement& element) const
1950 {
1951     return element.isPasswordField();
1952 }
1953
1954 NSPopUpButtonCell* RenderThemeMac::popupButton() const
1955 {
1956     if (!m_popupButton) {
1957         m_popupButton = adoptNS([[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO]);
1958         [m_popupButton.get() setUsesItemFromMenu:NO];
1959         [m_popupButton.get() setFocusRingType:NSFocusRingTypeExterior];
1960         // We don't want the app's UI layout direction to affect the appearance of popup buttons in
1961         // web content, which has its own layout direction.
1962         // FIXME: Make this depend on the directionality of the select element, once the rest of the
1963         // rendering code can account for the popup arrows appearing on the other side.
1964         [m_popupButton setUserInterfaceLayoutDirection:NSUserInterfaceLayoutDirectionLeftToRight];
1965     }
1966
1967     return m_popupButton.get();
1968 }
1969
1970 NSSearchFieldCell* RenderThemeMac::search() const
1971 {
1972     if (!m_search) {
1973         m_search = adoptNS([[NSSearchFieldCell alloc] initTextCell:@""]);
1974         [m_search.get() setBezelStyle:NSTextFieldRoundedBezel];
1975         [m_search.get() setBezeled:YES];
1976         [m_search.get() setEditable:YES];
1977         [m_search.get() setFocusRingType:NSFocusRingTypeExterior];
1978         [m_search.get() setCenteredLook:NO];
1979     }
1980
1981     return m_search.get();
1982 }
1983
1984 NSMenu* RenderThemeMac::searchMenuTemplate() const
1985 {
1986     if (!m_searchMenuTemplate)
1987         m_searchMenuTemplate = adoptNS([[NSMenu alloc] initWithTitle:@""]);
1988
1989     return m_searchMenuTemplate.get();
1990 }
1991
1992 NSSliderCell* RenderThemeMac::sliderThumbHorizontal() const
1993 {
1994     if (!m_sliderThumbHorizontal) {
1995         m_sliderThumbHorizontal = adoptNS([[NSSliderCell alloc] init]);
1996 #pragma clang diagnostic push
1997 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1998         [m_sliderThumbHorizontal.get() setSliderType:NSLinearSlider];
1999         [m_sliderThumbHorizontal.get() setControlSize:NSSmallControlSize];
2000         [m_sliderThumbHorizontal.get() setFocusRingType:NSFocusRingTypeExterior];
2001 #pragma clang diagnostic pop
2002     }
2003
2004     return m_sliderThumbHorizontal.get();
2005 }
2006
2007 NSSliderCell* RenderThemeMac::sliderThumbVertical() const
2008 {
2009     if (!m_sliderThumbVertical) {
2010         m_sliderThumbVertical = adoptNS([[NSSliderCell alloc] init]);
2011 #pragma clang diagnostic push
2012 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
2013         [m_sliderThumbVertical.get() setSliderType:NSLinearSlider];
2014         [m_sliderThumbVertical.get() setControlSize:NSSmallControlSize];
2015 #pragma clang diagnostic pop
2016         [m_sliderThumbVertical.get() setFocusRingType:NSFocusRingTypeExterior];
2017     }
2018
2019     return m_sliderThumbVertical.get();
2020 }
2021
2022 NSTextFieldCell* RenderThemeMac::textField() const
2023 {
2024     if (!m_textField) {
2025         m_textField = adoptNS([[WebCoreTextFieldCell alloc] initTextCell:@""]);
2026         [m_textField.get() setBezeled:YES];
2027         [m_textField.get() setEditable:YES];
2028         [m_textField.get() setFocusRingType:NSFocusRingTypeExterior];
2029         // Post-Lion, WebCore can be in charge of paintinng the background thanks to
2030         // the workaround in place for <rdar://problem/11385461>, which is implemented
2031         // above as _coreUIDrawOptionsWithFrame.
2032         [m_textField.get() setDrawsBackground:NO];
2033     }
2034
2035     return m_textField.get();
2036 }
2037
2038 String RenderThemeMac::fileListNameForWidth(const FileList* fileList, const FontCascade& font, int width, bool multipleFilesAllowed) const
2039 {
2040     if (width <= 0)
2041         return String();
2042
2043     String strToTruncate;
2044     if (fileList->isEmpty())
2045         strToTruncate = fileListDefaultLabel(multipleFilesAllowed);
2046     else if (fileList->length() == 1)
2047         strToTruncate = [[NSFileManager defaultManager] displayNameAtPath:(fileList->item(0)->path())];
2048     else
2049         return StringTruncator::rightTruncate(multipleFileUploadText(fileList->length()), width, font);
2050
2051     return StringTruncator::centerTruncate(strToTruncate, width, font);
2052 }
2053
2054 #if ENABLE(SERVICE_CONTROLS)
2055 NSServicesRolloverButtonCell* RenderThemeMac::servicesRolloverButtonCell() const
2056 {
2057 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2058     if (!m_servicesRolloverButton) {
2059         m_servicesRolloverButton = [NSServicesRolloverButtonCell serviceRolloverButtonCellForStyle:NSSharingServicePickerStyleRollover];
2060         [m_servicesRolloverButton setBezelStyle:NSRoundedDisclosureBezelStyle];
2061         [m_servicesRolloverButton setButtonType:NSPushOnPushOffButton];
2062         [m_servicesRolloverButton setImagePosition:NSImageOnly];
2063         [m_servicesRolloverButton setState:NO];
2064     }
2065
2066     return m_servicesRolloverButton.get();
2067 #else
2068     return nil;
2069 #endif
2070 }
2071
2072 bool RenderThemeMac::paintImageControlsButton(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& rect)
2073 {
2074     if (paintInfo.phase != PaintPhaseBlockBackground)
2075         return true;
2076
2077 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2078     NSServicesRolloverButtonCell *cell = servicesRolloverButtonCell();
2079
2080     LocalCurrentGraphicsContext localContext(paintInfo.context());
2081     GraphicsContextStateSaver stateSaver(paintInfo.context());
2082
2083     paintInfo.context().translate(rect.x(), rect.y());
2084
2085     IntRect innerFrame(IntPoint(), rect.size());
2086     [cell drawWithFrame:innerFrame inView:documentViewFor(renderer)];
2087     [cell setControlView:nil];
2088 #else
2089     UNUSED_PARAM(renderer);
2090     UNUSED_PARAM(rect);
2091 #endif
2092
2093     return true;
2094 }
2095
2096 IntSize RenderThemeMac::imageControlsButtonSize(const RenderObject&) const
2097 {
2098 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2099     return IntSize(servicesRolloverButtonCell().cellSize);
2100 #else
2101     return IntSize();
2102 #endif
2103 }
2104
2105 IntSize RenderThemeMac::imageControlsButtonPositionOffset() const
2106 {
2107 #if HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
2108     // FIXME: Currently the offsets will always be the same no matter what image rect you try with.
2109     // This may not always be true in the future.
2110     static const int dummyDimension = 100;
2111     IntRect dummyImageRect(0, 0, dummyDimension, dummyDimension);
2112     NSRect bounds = [servicesRolloverButtonCell() rectForBounds:dummyImageRect preferredEdge:NSMinYEdge];
2113
2114     return IntSize(dummyDimension - bounds.origin.x, bounds.origin.y);
2115 #else
2116     return IntSize();
2117 #endif
2118 }
2119 #endif
2120
2121 #if ENABLE(ATTACHMENT_ELEMENT)
2122 const CGFloat attachmentIconSize = 48;
2123 const CGFloat attachmentIconBackgroundPadding = 6;
2124 const CGFloat attachmentIconBackgroundSize = attachmentIconSize + attachmentIconBackgroundPadding;
2125 const CGFloat attachmentIconSelectionBorderThickness = 1;
2126 const CGFloat attachmentIconBackgroundRadius = 3;
2127 const CGFloat attachmentIconToTitleMargin = 2;
2128
2129 static Color attachmentIconBackgroundColor() { return Color(0, 0, 0, 30); }
2130 static Color attachmentIconBorderColor() { return Color(255, 255, 255, 125); }
2131
2132 const CGFloat attachmentTitleFontSize = 12;
2133 const CGFloat attachmentTitleBackgroundRadius = 3;
2134 const CGFloat attachmentTitleBackgroundPadding = 3;
2135 const CGFloat attachmentTitleMaximumWidth = 100 - (attachmentTitleBackgroundPadding * 2);
2136 const CFIndex attachmentTitleMaximumLineCount = 2;
2137
2138 static Color attachmentTitleInactiveBackgroundColor() { return Color(204, 204, 204, 255); }
2139 static Color attachmentTitleInactiveTextColor() { return Color(100, 100, 100, 255); }
2140
2141 const CGFloat attachmentSubtitleFontSize = 10;
2142 static Color attachmentSubtitleTextColor() { return Color(82, 145, 214, 255); }
2143
2144 const CGFloat attachmentProgressBarWidth = 30;
2145 const CGFloat attachmentProgressBarHeight = 5;
2146 const CGFloat attachmentProgressBarOffset = -9;
2147 const CGFloat attachmentProgressBarBorderWidth = 1;
2148 static Color attachmentProgressBarBackgroundColor() { return Color(0, 0, 0, 89); }
2149 static Color attachmentProgressBarFillColor() { return Color(Color::white); }
2150 static Color attachmentProgressBarBorderColor() { return Color(0, 0, 0, 128); }
2151
2152 const CGFloat attachmentMargin = 3;
2153
2154 struct AttachmentLayout {
2155     explicit AttachmentLayout(const RenderAttachment&);
2156
2157     struct LabelLine {
2158         FloatRect backgroundRect;
2159         FloatPoint origin;
2160         RetainPtr<CTLineRef> line;
2161     };
2162
2163     Vector<LabelLine> lines;
2164
2165     FloatRect iconRect;
2166     FloatRect iconBackgroundRect;
2167     FloatRect attachmentRect;
2168
2169     int baseline;
2170
2171     RetainPtr<CTLineRef> subtitleLine;
2172     FloatRect subtitleTextRect;
2173
2174 private:
2175     void layOutTitle(const RenderAttachment&);
2176     void layOutSubtitle(const RenderAttachment&);
2177
2178     void addTitleLine(CTLineRef, CGFloat& yOffset, Vector<CGPoint> origins, CFIndex lineIndex, const RenderAttachment&);
2179 };
2180
2181 static NSColor *titleTextColorForAttachment(const RenderAttachment& attachment)
2182 {
2183     if (attachment.selectionState() != RenderObject::SelectionNone) {
2184         if (attachment.frame().selection().isFocusedAndActive())
2185             return [NSColor alternateSelectedControlTextColor];    
2186         return (NSColor *)cachedCGColor(attachmentTitleInactiveTextColor());
2187     }
2188
2189     return [NSColor blackColor];
2190 }
2191
2192 void AttachmentLayout::addTitleLine(CTLineRef line, CGFloat& yOffset, Vector<CGPoint> origins, CFIndex lineIndex, const RenderAttachment& attachment)
2193 {
2194     CGRect lineBounds = CTLineGetBoundsWithOptions(line, 0);
2195     CGFloat trailingWhitespaceWidth = CTLineGetTrailingWhitespaceWidth(line);
2196     CGFloat lineWidthIgnoringTrailingWhitespace = lineBounds.size.width - trailingWhitespaceWidth;
2197     CGFloat lineHeight = CGCeiling(lineBounds.size.height);
2198
2199     // Center the line relative to the icon.
2200     CGFloat xOffset = (attachmentIconBackgroundSize / 2) - (lineWidthIgnoringTrailingWhitespace / 2);
2201
2202     if (lineIndex)
2203         yOffset += origins[lineIndex - 1].y - origins[lineIndex].y;
2204
2205     LabelLine labelLine;
2206     labelLine.origin = FloatPoint(xOffset, yOffset + lineHeight - origins.last().y);
2207     labelLine.line = line;
2208     labelLine.backgroundRect = FloatRect(xOffset, yOffset, lineWidthIgnoringTrailingWhitespace, lineHeight);
2209     labelLine.backgroundRect.inflateX(attachmentTitleBackgroundPadding);
2210     labelLine.backgroundRect = encloseRectToDevicePixels(labelLine.backgroundRect, attachment.document().deviceScaleFactor());
2211
2212     // If the text rects are close in size, the curved enclosing background won't
2213     // look right, so make them the same exact size.
2214     if (!lines.isEmpty()) {
2215         float previousBackgroundRectWidth = lines.last().backgroundRect.width();
2216         if (fabs(labelLine.backgroundRect.width() - previousBackgroundRectWidth) < attachmentTitleBackgroundRadius * 4) {
2217             float newBackgroundRectWidth = std::max(previousBackgroundRectWidth, labelLine.backgroundRect.width());
2218             labelLine.backgroundRect.inflateX((newBackgroundRectWidth - labelLine.backgroundRect.width()) / 2);
2219             lines.last().backgroundRect.inflateX((newBackgroundRectWidth - previousBackgroundRectWidth) / 2);
2220         }
2221     }
2222
2223     lines.append(labelLine);
2224 }
2225
2226 void AttachmentLayout::layOutTitle(const RenderAttachment& attachment)
2227 {
2228     CFStringRef language = 0; // By not specifying a language we use the system language.
2229     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, attachmentTitleFontSize, language));
2230     baseline = CGRound(attachmentIconBackgroundSize + attachmentIconToTitleMargin + CTFontGetAscent(font.get()));
2231
2232     String title = attachment.attachmentElement().attachmentTitle();
2233     if (title.isEmpty())
2234         return;
2235
2236     NSDictionary *textAttributes = @{
2237         (id)kCTFontAttributeName: (id)font.get(),
2238         (id)kCTForegroundColorAttributeName: titleTextColorForAttachment(attachment)
2239     };
2240     RetainPtr<NSAttributedString> attributedTitle = adoptNS([[NSAttributedString alloc] initWithString:title attributes:textAttributes]);
2241     RetainPtr<CTFramesetterRef> titleFramesetter = adoptCF(CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedTitle.get()));
2242
2243     CFRange fitRange;
2244     CGSize titleTextSize = CTFramesetterSuggestFrameSizeWithConstraints(titleFramesetter.get(), CFRangeMake(0, 0), nullptr, CGSizeMake(attachmentTitleMaximumWidth, CGFLOAT_MAX), &fitRange);
2245
2246     RetainPtr<CGPathRef> titlePath = adoptCF(CGPathCreateWithRect(CGRectMake(0, 0, titleTextSize.width, titleTextSize.height), nullptr));
2247     RetainPtr<CTFrameRef> titleFrame = adoptCF(CTFramesetterCreateFrame(titleFramesetter.get(), fitRange, titlePath.get(), nullptr));
2248
2249     CFArrayRef ctLines = CTFrameGetLines(titleFrame.get());
2250     CFIndex lineCount = CFArrayGetCount(ctLines);
2251     if (!lineCount)
2252         return;
2253
2254     Vector<CGPoint> origins(lineCount);
2255     CTFrameGetLineOrigins(titleFrame.get(), CFRangeMake(0, 0), origins.data());
2256
2257     // Lay out and record the first (attachmentTitleMaximumLineCount - 1) lines.
2258     CFIndex lineIndex = 0;
2259     CGFloat yOffset = attachmentIconBackgroundSize + attachmentIconToTitleMargin;
2260     for (; lineIndex < std::min(attachmentTitleMaximumLineCount - 1, lineCount); ++lineIndex) {
2261         CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
2262         addTitleLine(line, yOffset, origins, lineIndex, attachment);
2263     }
2264
2265     if (lineIndex == lineCount)
2266         return;
2267
2268     // We had text that didn't fit in the first (attachmentTitleMaximumLineCount - 1) lines.
2269     // Combine it into one last line, and center-truncate it.
2270     CTLineRef firstRemainingLine = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
2271     CFIndex remainingRangeStart = CTLineGetStringRange(firstRemainingLine).location;
2272     NSRange remainingRange = NSMakeRange(remainingRangeStart, [attributedTitle length] - remainingRangeStart);
2273     NSAttributedString *remainingString = [attributedTitle attributedSubstringFromRange:remainingRange];
2274     RetainPtr<CTLineRef> remainingLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)remainingString));
2275     RetainPtr<NSAttributedString> ellipsisString = adoptNS([[NSAttributedString alloc] initWithString:@"\u2026" attributes:textAttributes]);
2276     RetainPtr<CTLineRef> ellipsisLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)ellipsisString.get()));
2277     RetainPtr<CTLineRef> truncatedLine = adoptCF(CTLineCreateTruncatedLine(remainingLine.get(), attachmentTitleMaximumWidth, kCTLineTruncationMiddle, ellipsisLine.get()));
2278
2279     if (!truncatedLine)
2280         truncatedLine = remainingLine;
2281
2282     addTitleLine(truncatedLine.get(), yOffset, origins, lineIndex, attachment);
2283 }
2284
2285 void AttachmentLayout::layOutSubtitle(const RenderAttachment& attachment)
2286 {
2287     String subtitleText = attachment.attachmentElement().fastGetAttribute(subtitleAttr);
2288
2289     if (subtitleText.isEmpty())
2290         return;
2291
2292     CFStringRef language = 0; // By not specifying a language we use the system language.
2293     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateUIFontForLanguage(kCTFontUIFontSystem, attachmentSubtitleFontSize, language));
2294     NSDictionary *textAttributes = @{
2295         (id)kCTFontAttributeName: (id)font.get(),
2296         (id)kCTForegroundColorAttributeName: (NSColor *)cachedCGColor(attachmentSubtitleTextColor())
2297     };
2298     RetainPtr<NSAttributedString> attributedSubtitleText = adoptNS([[NSAttributedString alloc] initWithString:subtitleText attributes:textAttributes]);
2299     subtitleLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)attributedSubtitleText.get()));
2300
2301     CGRect lineBounds = CTLineGetBoundsWithOptions(subtitleLine.get(), 0);
2302
2303     // Center the line relative to the icon.
2304     CGFloat xOffset = (attachmentIconBackgroundSize / 2) - (lineBounds.size.width / 2);
2305     CGFloat yOffset = 0;
2306
2307     if (!lines.isEmpty())
2308         yOffset = lines.last().backgroundRect.maxY();
2309     else
2310         yOffset = attachmentIconBackgroundSize + attachmentIconToTitleMargin;
2311
2312     LabelLine labelLine;
2313     subtitleTextRect = FloatRect(xOffset, yOffset, lineBounds.size.width, lineBounds.size.height);
2314 }
2315
2316 AttachmentLayout::AttachmentLayout(const RenderAttachment& attachment)
2317 {
2318     layOutTitle(attachment);
2319     layOutSubtitle(attachment);
2320
2321     iconBackgroundRect = FloatRect(0, 0, attachmentIconBackgroundSize, attachmentIconBackgroundSize);
2322
2323     iconRect = iconBackgroundRect;
2324     iconRect.setSize(FloatSize(attachmentIconSize, attachmentIconSize));
2325     iconRect.move(attachmentIconBackgroundPadding / 2, attachmentIconBackgroundPadding / 2);
2326
2327     attachmentRect = iconBackgroundRect;
2328     for (const auto& line : lines)
2329         attachmentRect.unite(line.backgroundRect);
2330     attachmentRect.unite(subtitleTextRect);
2331     attachmentRect.inflate(attachmentMargin);
2332     attachmentRect = encloseRectToDevicePixels(attachmentRect, attachment.document().deviceScaleFactor());
2333 }
2334
2335 LayoutSize RenderThemeMac::attachmentIntrinsicSize(const RenderAttachment& attachment) const
2336 {
2337     AttachmentLayout layout(attachment);
2338     return LayoutSize(layout.attachmentRect.size());
2339 }
2340
2341 int RenderThemeMac::attachmentBaseline(const RenderAttachment& attachment) const
2342 {
2343     AttachmentLayout layout(attachment);
2344     return layout.baseline;
2345 }
2346
2347 static void paintAttachmentIconBackground(const RenderAttachment&, GraphicsContext& context, AttachmentLayout& layout)
2348 {
2349     // FIXME: Finder has a discontinuous behavior here when you have a background color other than white,
2350     // where it switches into 'bordered mode' and the border pops in on top of the background.
2351     bool paintBorder = true;
2352
2353     FloatRect backgroundRect = layout.iconBackgroundRect;
2354     if (paintBorder)
2355         backgroundRect.inflate(-attachmentIconSelectionBorderThickness);
2356
2357     context.fillRoundedRect(FloatRoundedRect(backgroundRect, FloatRoundedRect::Radii(attachmentIconBackgroundRadius)), attachmentIconBackgroundColor());
2358
2359     if (paintBorder) {
2360         FloatRect borderRect = layout.iconBackgroundRect;
2361         borderRect.inflate(-attachmentIconSelectionBorderThickness / 2);
2362
2363         FloatSize iconBackgroundRadiusSize(attachmentIconBackgroundRadius, attachmentIconBackgroundRadius);
2364         Path borderPath;
2365         borderPath.addRoundedRect(borderRect, iconBackgroundRadiusSize);
2366         context.setStrokeColor(attachmentIconBorderColor());
2367         context.setStrokeThickness(attachmentIconSelectionBorderThickness);
2368         context.strokePath(borderPath);
2369     }
2370 }
2371
2372 static RefPtr<Icon> iconForAttachment(const RenderAttachment& attachment)
2373 {
2374     String MIMEType = attachment.attachmentElement().attachmentType();
2375     if (!MIMEType.isEmpty()) {
2376         if (equalIgnoringASCIICase(MIMEType, "multipart/x-folder") || equalIgnoringASCIICase(MIMEType, "application/vnd.apple.folder")) {
2377             if (auto icon = Icon::createIconForUTI("public.directory"))
2378                 return icon;
2379         } else if (auto icon = Icon::createIconForMIMEType(MIMEType))
2380             return icon;
2381     }
2382
2383     if (File* file = attachment.attachmentElement().file()) {
2384         if (auto icon = Icon::createIconForFiles({ file->path() }))
2385             return icon;
2386     }
2387
2388     NSString *fileExtension = [static_cast<NSString *>(attachment.attachmentElement().attachmentTitle()) pathExtension];
2389     if (fileExtension.length) {
2390         if (auto icon = Icon::createIconForFileExtension(fileExtension))
2391             return icon;
2392     }
2393
2394     return Icon::createIconForUTI("public.data");
2395 }
2396
2397 static void paintAttachmentIcon(const RenderAttachment& attachment, GraphicsContext& context, AttachmentLayout& layout)
2398 {
2399     auto icon = iconForAttachment(attachment);
2400     if (!icon)
2401         return;
2402     icon->paint(context, layout.iconRect);
2403 }
2404
2405 static void paintAttachmentTitleBackground(const RenderAttachment& attachment, GraphicsContext& context, AttachmentLayout& layout)
2406 {
2407     if (layout.lines.isEmpty())
2408         return;
2409
2410     Vector<FloatRect> backgroundRects;
2411
2412     for (size_t i = 0; i < layout.lines.size(); ++i)
2413         backgroundRects.append(layout.lines[i].backgroundRect);
2414
2415     Color backgroundColor;
2416     if (attachment.frame().selection().isFocusedAndActive())
2417         backgroundColor = convertNSColorToColor([NSColor alternateSelectedControlColor]);
2418     else
2419         backgroundColor = attachmentTitleInactiveBackgroundColor();
2420
2421     context.setFillColor(backgroundColor);
2422
2423     Path backgroundPath = PathUtilities::pathWithShrinkWrappedRects(backgroundRects, attachmentTitleBackgroundRadius);
2424     context.fillPath(backgroundPath);
2425 }
2426
2427 static void paintAttachmentTitle(const RenderAttachment&, GraphicsContext& context, AttachmentLayout& layout)
2428 {
2429     for (const auto& line : layout.lines) {
2430         GraphicsContextStateSaver saver(context);
2431
2432         context.translate(toFloatSize(line.origin));
2433         context.scale(FloatSize(1, -1));
2434
2435         CGContextSetTextMatrix(context.platformContext(), CGAffineTransformIdentity);
2436         CTLineDraw(line.line.get(), context.platformContext());
2437     }
2438 }
2439
2440 static void paintAttachmentSubtitle(const RenderAttachment&, GraphicsContext& context, AttachmentLayout& layout)
2441 {
2442     GraphicsContextStateSaver saver(context);
2443
2444     context.translate(toFloatSize(layout.subtitleTextRect.minXMaxYCorner()));
2445     context.scale(FloatSize(1, -1));
2446
2447     CGContextSetTextMatrix(context.platformContext(), CGAffineTransformIdentity);
2448     CTLineDraw(layout.subtitleLine.get(), context.platformContext());
2449 }
2450
2451 static void paintAttachmentProgress(const RenderAttachment& attachment, GraphicsContext& context, AttachmentLayout& layout)
2452 {
2453     String progressString = attachment.attachmentElement().fastGetAttribute(progressAttr);
2454     if (progressString.isEmpty())
2455         return;
2456     bool validProgress;
2457     float progress = progressString.toFloat(&validProgress);
2458     if (!validProgress)
2459         return;
2460
2461     GraphicsContextStateSaver saver(context);
2462
2463     FloatRect progressBounds((attachmentIconBackgroundSize - attachmentProgressBarWidth) / 2, layout.iconBackgroundRect.maxY() + attachmentProgressBarOffset - attachmentProgressBarHeight, attachmentProgressBarWidth, attachmentProgressBarHeight);
2464
2465     FloatRect borderRect = progressBounds;
2466     borderRect.inflate(-0.5);
2467     FloatRect backgroundRect = borderRect;
2468     backgroundRect.inflate(-attachmentProgressBarBorderWidth / 2);
2469
2470     FloatRoundedRect backgroundRoundedRect(backgroundRect, FloatRoundedRect::Radii(backgroundRect.height() / 2));
2471     context.fillRoundedRect(backgroundRoundedRect, attachmentProgressBarBackgroundColor());
2472
2473     {
2474         GraphicsContextStateSaver clipSaver(context);
2475         context.clipRoundedRect(backgroundRoundedRect);
2476
2477         FloatRect progressRect = progressBounds;
2478         progressRect.setWidth(progressRect.width() * progress);
2479         progressRect = encloseRectToDevicePixels(progressRect, attachment.document().deviceScaleFactor());
2480
2481         context.fillRect(progressRect, attachmentProgressBarFillColor());
2482     }
2483
2484     Path borderPath;
2485     float borderRadius = borderRect.height() / 2;
2486     borderPath.addRoundedRect(borderRect, FloatSize(borderRadius, borderRadius));
2487     context.setStrokeColor(attachmentProgressBarBorderColor());
2488     context.setStrokeThickness(attachmentProgressBarBorderWidth);
2489     context.strokePath(borderPath);
2490 }
2491
2492 bool RenderThemeMac::paintAttachment(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& paintRect)
2493 {
2494     if (!is<RenderAttachment>(renderer))
2495         return false;
2496
2497     const RenderAttachment& attachment = downcast<RenderAttachment>(renderer);
2498
2499     AttachmentLayout layout(attachment);
2500
2501     GraphicsContext& context = paintInfo.context();
2502     LocalCurrentGraphicsContext localContext(context);
2503     GraphicsContextStateSaver saver(context);
2504
2505     context.translate(toFloatSize(paintRect.location()));
2506     context.translate(FloatSize((layout.attachmentRect.width() - attachmentIconBackgroundSize) / 2, 0));
2507
2508     bool useSelectedStyle = attachment.selectionState() != RenderObject::SelectionNone;
2509
2510     if (useSelectedStyle)
2511         paintAttachmentIconBackground(attachment, context, layout);
2512     paintAttachmentIcon(attachment, context, layout);
2513     if (useSelectedStyle)
2514         paintAttachmentTitleBackground(attachment, context, layout);
2515     paintAttachmentTitle(attachment, context, layout);
2516     paintAttachmentSubtitle(attachment, context, layout);
2517     paintAttachmentProgress(attachment, context, layout);
2518
2519     return true;
2520 }
2521
2522 #endif // ENABLE(ATTACHMENT_ELEMENT)
2523
2524 } // namespace WebCore
2525
2526 #endif // !PLATFORM(IOS)