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