Selects should scale when rendering while zoomed
[WebKit-https.git] / Source / WebCore / rendering / RenderThemeMac.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public License
15  * along with this library; see the file COPYING.LIB.  If not, write to
16  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19 #if !PLATFORM(IOS)
20
21 #import "config.h"
22 #import "RenderThemeMac.h"
23
24 #import "BitmapImage.h"
25 #import "CSSValueKeywords.h"
26 #import "CSSValueList.h"
27 #import "ColorMac.h"
28 #import "CoreGraphicsSPI.h"
29 #import "Document.h"
30 #import "Element.h"
31 #import "ExceptionCodePlaceholder.h"
32 #import "FileList.h"
33 #import "FloatRoundedRect.h"
34 #import "FocusController.h"
35 #import "Frame.h"
36 #import "FrameSelection.h"
37 #import "FrameView.h"
38 #import "GraphicsContextCG.h"
39 #import "HTMLAttachmentElement.h"
40 #import "HTMLAudioElement.h"
41 #import "HTMLInputElement.h"
42 #import "HTMLMediaElement.h"
43 #import "HTMLNames.h"
44 #import "HTMLPlugInImageElement.h"
45 #import "Icon.h"
46 #import "Image.h"
47 #import "ImageBuffer.h"
48 #import "LocalCurrentGraphicsContext.h"
49 #import "LocalizedStrings.h"
50 #import "MediaControlElements.h"
51 #import "NSColorSPI.h"
52 #import "NSSharingServicePickerSPI.h"
53 #import "Page.h"
54 #import "PaintInfo.h"
55 #import "PathUtilities.h"
56 #import "RenderAttachment.h"
57 #import "RenderLayer.h"
58 #import "RenderMedia.h"
59 #import "RenderMediaControlElements.h"
60 #import "RenderMediaControls.h"
61 #import "RenderProgress.h"
62 #import "RenderSlider.h"
63 #import "RenderSnapshottedPlugIn.h"
64 #import "RenderView.h"
65 #import "SharedBuffer.h"
66 #import "StringTruncator.h"
67 #import "StyleResolver.h"
68 #import "ThemeMac.h"
69 #import "TimeRanges.h"
70 #import "UserAgentScripts.h"
71 #import "UserAgentStyleSheets.h"
72 #import "WebCoreSystemInterface.h"
73 #import <wtf/RetainPtr.h>
74 #import <wtf/RetainPtr.h>
75 #import <wtf/StdLibExtras.h>
76 #import <wtf/text/StringBuilder.h>
77 #import <Carbon/Carbon.h>
78 #import <Cocoa/Cocoa.h>
79 #import <math.h>
80
81 #if ENABLE(METER_ELEMENT)
82 #import "RenderMeter.h"
83 #import "HTMLMeterElement.h"
84 #endif
85
86 #if defined(__LP64__) && __LP64__
87 #define HAVE_APPKIT_SERVICE_CONTROLS_SUPPORT 1
88 #else
89 #define HAVE_APPKIT_SERVICE_CONTROLS_SUPPORT 0
90 #endif
91
92 #if ENABLE(SERVICE_CONTROLS) && HAVE(APPKIT_SERVICE_CONTROLS_SUPPORT)
93
94 #if __has_include(<AppKit/AppKitDefines_Private.h>)
95 #import <AppKit/AppKitDefines_Private.h>
96 #else
97 #define APPKIT_PRIVATE_CLASS
98 #endif
99
100 #if __has_include(<AppKit/NSServicesRolloverButtonCell.h>)
101 #import <AppKit/NSServicesRolloverButtonCell.h>
102 #else
103 @interface NSServicesRolloverButtonCell : NSButtonCell
104 @end
105 #endif
106
107 @interface NSServicesRolloverButtonCell ()
108 + (NSServicesRolloverButtonCell *)serviceRolloverButtonCellForStyle:(NSSharingServicePickerStyle)style;
109 - (NSRect)rectForBounds:(NSRect)bounds preferredEdge:(NSRectEdge)preferredEdge;
110 @end
111
112 #endif // ENABLE(SERVICE_CONTROLS)
113
114 // The methods in this file are specific to the Mac OS X platform.
115
116 // FIXME: The platform-independent code in this class should be factored out and merged with RenderThemeSafari.
117
118 // We estimate the animation rate of a Mac OS X progress bar is 33 fps.
119 // Hard code the value here because we haven't found API for it.
120 const double progressAnimationFrameRate = 0.033;
121
122 // Mac OS X progress bar animation seems to have 256 frames.
123 const double progressAnimationNumFrames = 256;
124
125 @interface WebCoreRenderThemeNotificationObserver : NSObject
126 {
127     WebCore::RenderTheme *_theme;
128 }
129
130 - (id)initWithTheme:(WebCore::RenderTheme *)theme;
131 - (void)systemColorsDidChange:(NSNotification *)notification;
132
133 @end
134
135 @implementation WebCoreRenderThemeNotificationObserver
136
137 - (id)initWithTheme:(WebCore::RenderTheme *)theme
138 {
139     if (!(self = [super init]))
140         return nil;
141
142     _theme = theme;
143     return self;
144 }
145
146 - (void)systemColorsDidChange:(NSNotification *)unusedNotification
147 {
148     ASSERT_UNUSED(unusedNotification, [[unusedNotification name] isEqualToString:NSSystemColorsDidChangeNotification]);
149     _theme->platformColorsDidChange();
150 }
151
152 @end
153
154 @interface NSTextFieldCell (WKDetails)
155 - (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame inView:(NSView *)controlView includeFocus:(BOOL)includeFocus;
156 @end
157
158
159 @interface WebCoreTextFieldCell : NSTextFieldCell
160 - (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame inView:(NSView *)controlView includeFocus:(BOOL)includeFocus;
161 @end
162
163 @implementation WebCoreTextFieldCell
164 - (CFDictionaryRef)_coreUIDrawOptionsWithFrame:(NSRect)cellFrame inView:(NSView *)controlView includeFocus:(BOOL)includeFocus
165 {
166     // FIXME: This is a post-Lion-only workaround for <rdar://problem/11385461>. When that bug is resolved, we should remove this code.
167     CFMutableDictionaryRef coreUIDrawOptions = CFDictionaryCreateMutableCopy(NULL, 0, [super _coreUIDrawOptionsWithFrame:cellFrame inView:controlView includeFocus:includeFocus]);
168     CFDictionarySetValue(coreUIDrawOptions, @"borders only", kCFBooleanTrue);
169     return (CFDictionaryRef)[NSMakeCollectable(coreUIDrawOptions) autorelease];
170 }
171 @end
172
173 @interface WebCoreRenderThemeBundle : NSObject
174 @end
175
176 @implementation WebCoreRenderThemeBundle
177 @end
178
179 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
180 @interface NSSearchFieldCell()
181 @property (getter=isCenteredLook) BOOL centeredLook;
182 @end
183 #endif
184
185 namespace WebCore {
186
187 using namespace HTMLNames;
188
189 enum {
190     topMargin,
191     rightMargin,
192     bottomMargin,
193     leftMargin
194 };
195
196 enum {
197     topPadding,
198     rightPadding,
199     bottomPadding,
200     leftPadding
201 };
202
203 PassRefPtr<RenderTheme> RenderTheme::themeForPage(Page*)
204 {
205     static RenderTheme& rt = RenderThemeMac::create().leakRef();
206     return &rt;
207 }
208
209 Ref<RenderTheme> RenderThemeMac::create()
210 {
211     return adoptRef(*new RenderThemeMac);
212 }
213
214 RenderThemeMac::RenderThemeMac()
215     : m_isSliderThumbHorizontalPressed(false)
216     , m_isSliderThumbVerticalPressed(false)
217     , m_notificationObserver(adoptNS([[WebCoreRenderThemeNotificationObserver alloc] initWithTheme:this]))
218 {
219     [[NSNotificationCenter defaultCenter] addObserver:m_notificationObserver.get()
220                                                         selector:@selector(systemColorsDidChange:)
221                                                             name:NSSystemColorsDidChangeNotification
222                                                           object:nil];
223 }
224
225 RenderThemeMac::~RenderThemeMac()
226 {
227     [[NSNotificationCenter defaultCenter] removeObserver:m_notificationObserver.get()];
228 }
229
230 NSView* RenderThemeMac::documentViewFor(const RenderObject& o) const
231 {
232     ControlStates states(extractControlStatesForRenderer(o));
233     return ThemeMac::ensuredView(&o.view().frameView(), states);
234 }
235
236 #if ENABLE(VIDEO)
237 String RenderThemeMac::mediaControlsStyleSheet()
238 {
239 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
240     if (m_mediaControlsStyleSheet.isEmpty())
241         m_mediaControlsStyleSheet = [NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsApple" ofType:@"css"] encoding:NSUTF8StringEncoding error:nil];
242     return m_mediaControlsStyleSheet;
243 #else
244     return emptyString();
245 #endif
246 }
247
248 String RenderThemeMac::mediaControlsScript()
249 {
250 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
251     if (m_mediaControlsScript.isEmpty()) {
252         StringBuilder scriptBuilder;
253         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsLocalizedStrings" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
254         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsApple" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
255         m_mediaControlsScript = scriptBuilder.toString();
256     }
257     return m_mediaControlsScript;
258 #else
259     return emptyString();
260 #endif
261 }
262
263 #endif // ENABLE(VIDEO)
264
265
266 #if ENABLE(SERVICE_CONTROLS)
267 String RenderThemeMac::imageControlsStyleSheet() const
268 {
269     return String(imageControlsMacUserAgentStyleSheet, sizeof(imageControlsMacUserAgentStyleSheet));
270 }
271 #endif
272
273 Color RenderThemeMac::platformActiveSelectionBackgroundColor() const
274 {
275     NSColor* color = [[NSColor selectedTextBackgroundColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
276     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
277 }
278
279 Color RenderThemeMac::platformInactiveSelectionBackgroundColor() const
280 {
281     NSColor* color = [[NSColor secondarySelectedControlColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
282     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
283 }
284
285 Color RenderThemeMac::platformActiveListBoxSelectionBackgroundColor() const
286 {
287     NSColor* color = [[NSColor alternateSelectedControlColor] colorUsingColorSpaceName:NSDeviceRGBColorSpace];
288     return Color(static_cast<int>(255.0 * [color redComponent]), static_cast<int>(255.0 * [color greenComponent]), static_cast<int>(255.0 * [color blueComponent]));
289 }
290
291 Color RenderThemeMac::platformActiveListBoxSelectionForegroundColor() const
292 {
293     return Color::white;
294 }
295
296 Color RenderThemeMac::platformInactiveListBoxSelectionForegroundColor() const
297 {
298     return Color::black;
299 }
300
301 Color RenderThemeMac::platformFocusRingColor() const
302 {
303     if (usesTestModeFocusRingColor())
304         return oldAquaFocusRingColor();
305
306     return systemColor(CSSValueWebkitFocusRingColor);
307 }
308
309 int RenderThemeMac::platformFocusRingMaxWidth() const
310 {
311     // FIXME: Shouldn't this function be named platformFocusRingMinWidth? But also, I'm not sure if this function is needed - looks like
312     // all platforms just used 0 for this before <http://trac.webkit.org/changeset/168397>.
313     return 0;
314 }
315
316 Color RenderThemeMac::platformInactiveListBoxSelectionBackgroundColor() const
317 {
318     return platformInactiveSelectionBackgroundColor();
319 }
320
321 static FontWeight toFontWeight(NSInteger appKitFontWeight)
322 {
323     ASSERT(appKitFontWeight > 0 && appKitFontWeight < 15);
324     if (appKitFontWeight > 14)
325         appKitFontWeight = 14;
326     else if (appKitFontWeight < 1)
327         appKitFontWeight = 1;
328
329     static const FontWeight fontWeights[] = {
330         FontWeight100,
331         FontWeight100,
332         FontWeight200,
333         FontWeight300,
334         FontWeight400,
335         FontWeight500,
336         FontWeight600,
337         FontWeight600,
338         FontWeight700,
339         FontWeight800,
340         FontWeight800,
341         FontWeight900,
342         FontWeight900,
343         FontWeight900
344     };
345     return fontWeights[appKitFontWeight - 1];
346 }
347
348 void RenderThemeMac::updateCachedSystemFontDescription(CSSValueID cssValueId, FontDescription& fontDescription) const
349 {
350     NSFont* font;
351     // System-font-ness can't be encapsulated by simply a font name. Instead, we must use a token
352     // which FontCache will look for.
353     // Make sure we keep this list of possible tokens in sync with FontCascade::primaryFontIsSystemFont()
354     AtomicString fontName;
355     switch (cssValueId) {
356         case CSSValueSmallCaption:
357             font = [NSFont systemFontOfSize:[NSFont smallSystemFontSize]];
358             break;
359         case CSSValueMenu:
360             font = [NSFont menuFontOfSize:[NSFont systemFontSize]];
361             fontName = AtomicString("-apple-menu", AtomicString::ConstructFromLiteral);
362             break;
363         case CSSValueStatusBar:
364             font = [NSFont labelFontOfSize:[NSFont labelFontSize]];
365             fontName = AtomicString("-apple-status-bar", AtomicString::ConstructFromLiteral);
366             break;
367         case CSSValueWebkitMiniControl:
368             font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSMiniControlSize]];
369             break;
370         case CSSValueWebkitSmallControl:
371             font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSSmallControlSize]];
372             break;
373         case CSSValueWebkitControl:
374             font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:NSRegularControlSize]];
375             break;
376         default:
377             font = [NSFont systemFontOfSize:[NSFont systemFontSize]];
378     }
379
380     if (!font)
381         return;
382
383     if (fontName.isNull())
384         fontName = AtomicString("-apple-system", AtomicString::ConstructFromLiteral);
385
386     NSFontManager *fontManager = [NSFontManager sharedFontManager];
387     fontDescription.setIsAbsoluteSize(true);
388     fontDescription.setOneFamily(fontName);
389     fontDescription.setSpecifiedSize([font pointSize]);
390     fontDescription.setWeight(toFontWeight([fontManager weightOfFont:font]));
391     fontDescription.setIsItalic([fontManager traitsOfFont:font] & NSItalicFontMask);
392 }
393
394 static RGBA32 convertNSColorToColor(NSColor *color)
395 {
396     NSColor *colorInColorSpace = [color colorUsingColorSpaceName:NSDeviceRGBColorSpace];
397     if (colorInColorSpace) {
398         static const double scaleFactor = nextafter(256.0, 0.0);
399         return makeRGB(static_cast<int>(scaleFactor * [colorInColorSpace redComponent]),
400             static_cast<int>(scaleFactor * [colorInColorSpace greenComponent]),
401             static_cast<int>(scaleFactor * [colorInColorSpace blueComponent]));
402     }
403
404     // This conversion above can fail if the NSColor in question is an NSPatternColor
405     // (as many system colors are). These colors are actually a repeating pattern
406     // not just a solid color. To work around this we simply draw a 1x1 image of
407     // the color and use that pixel's color. It might be better to use an average of
408     // the colors in the pattern instead.
409     NSBitmapImageRep *offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
410                                                                              pixelsWide:1
411                                                                              pixelsHigh:1
412                                                                           bitsPerSample:8
413                                                                         samplesPerPixel:4
414                                                                                hasAlpha:YES
415                                                                                isPlanar:NO
416                                                                          colorSpaceName:NSDeviceRGBColorSpace
417                                                                             bytesPerRow:4
418                                                                            bitsPerPixel:32];
419
420     [NSGraphicsContext saveGraphicsState];
421     [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep]];
422     NSEraseRect(NSMakeRect(0, 0, 1, 1));
423     [color drawSwatchInRect:NSMakeRect(0, 0, 1, 1)];
424     [NSGraphicsContext restoreGraphicsState];
425
426     NSUInteger pixel[4];
427     [offscreenRep getPixel:pixel atX:0 y:0];
428
429     [offscreenRep release];
430
431     return makeRGB(pixel[0], pixel[1], pixel[2]);
432 }
433
434 static RGBA32 menuBackgroundColor()
435 {
436     NSBitmapImageRep *offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
437                                                                              pixelsWide:1
438                                                                              pixelsHigh:1
439                                                                           bitsPerSample:8
440                                                                         samplesPerPixel:4
441                                                                                hasAlpha:YES
442                                                                                isPlanar:NO
443                                                                          colorSpaceName:NSDeviceRGBColorSpace
444                                                                             bytesPerRow:4
445                                                                            bitsPerPixel:32];
446
447     CGContextRef context = static_cast<CGContextRef>([[NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep] graphicsPort]);
448     CGRect rect = CGRectMake(0, 0, 1, 1);
449     HIThemeMenuDrawInfo drawInfo;
450     drawInfo.version =  0;
451     drawInfo.menuType = kThemeMenuTypePopUp;
452     HIThemeDrawMenuBackground(&rect, &drawInfo, context, kHIThemeOrientationInverted);
453
454     NSUInteger pixel[4];
455     [offscreenRep getPixel:pixel atX:0 y:0];
456
457     [offscreenRep release];
458
459     return makeRGB(pixel[0], pixel[1], pixel[2]);
460 }
461
462 void RenderThemeMac::platformColorsDidChange()
463 {
464     m_systemColorCache.clear();
465     RenderTheme::platformColorsDidChange();
466 }
467
468 Color RenderThemeMac::systemColor(CSSValueID cssValueID) const
469 {
470     auto addResult = m_systemColorCache.add(cssValueID, Color());
471     if (!addResult.isNewEntry)
472         return addResult.iterator->value;
473
474     Color color;
475     switch (cssValueID) {
476     case CSSValueActiveborder:
477         color = convertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
478         break;
479     case CSSValueActivebuttontext:
480 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
481         // There is no corresponding NSColor for this so we use a hard coded value.
482         color = Color::white;
483 #else
484         color = convertNSColorToColor([NSColor controlTextColor]);
485 #endif
486         break;
487     case CSSValueActivecaption:
488         color = convertNSColorToColor([NSColor windowFrameTextColor]);
489         break;
490     case CSSValueAppworkspace:
491         color = convertNSColorToColor([NSColor headerColor]);
492         break;
493     case CSSValueBackground:
494         // Use theme independent default
495         break;
496     case CSSValueButtonface:
497         // We use this value instead of NSColor's controlColor to avoid website incompatibilities.
498         // We may want to change this to use the NSColor in future.
499         color = 0xFFC0C0C0;
500         break;
501     case CSSValueButtonhighlight:
502         color = convertNSColorToColor([NSColor controlHighlightColor]);
503         break;
504     case CSSValueButtonshadow:
505         color = convertNSColorToColor([NSColor controlShadowColor]);
506         break;
507     case CSSValueButtontext:
508         color = convertNSColorToColor([NSColor controlTextColor]);
509         break;
510     case CSSValueCaptiontext:
511         color = convertNSColorToColor([NSColor textColor]);
512         break;
513     case CSSValueGraytext:
514         color = convertNSColorToColor([NSColor disabledControlTextColor]);
515         break;
516     case CSSValueHighlight:
517         color = convertNSColorToColor([NSColor selectedTextBackgroundColor]);
518         break;
519     case CSSValueHighlighttext:
520         color = convertNSColorToColor([NSColor selectedTextColor]);
521         break;
522     case CSSValueInactiveborder:
523         color = convertNSColorToColor([NSColor controlBackgroundColor]);
524         break;
525     case CSSValueInactivecaption:
526         color = convertNSColorToColor([NSColor controlBackgroundColor]);
527         break;
528     case CSSValueInactivecaptiontext:
529         color = convertNSColorToColor([NSColor textColor]);
530         break;
531     case CSSValueInfobackground:
532         // There is no corresponding NSColor for this so we use a hard coded value.
533         color = 0xFFFBFCC5;
534         break;
535     case CSSValueInfotext:
536         color = convertNSColorToColor([NSColor textColor]);
537         break;
538     case CSSValueMenu:
539         color = menuBackgroundColor();
540         break;
541     case CSSValueMenutext:
542         color = convertNSColorToColor([NSColor selectedMenuItemTextColor]);
543         break;
544     case CSSValueScrollbar:
545         color = convertNSColorToColor([NSColor scrollBarColor]);
546         break;
547     case CSSValueText:
548         color = convertNSColorToColor([NSColor textColor]);
549         break;
550     case CSSValueThreeddarkshadow:
551         color = convertNSColorToColor([NSColor controlDarkShadowColor]);
552         break;
553     case CSSValueThreedshadow:
554         color = convertNSColorToColor([NSColor shadowColor]);
555         break;
556     case CSSValueThreedface:
557         // We use this value instead of NSColor's controlColor to avoid website incompatibilities.
558         // We may want to change this to use the NSColor in future.
559         color = 0xFFC0C0C0;
560         break;
561     case CSSValueThreedhighlight:
562         color = convertNSColorToColor([NSColor highlightColor]);
563         break;
564     case CSSValueThreedlightshadow:
565         color = convertNSColorToColor([NSColor controlLightHighlightColor]);
566         break;
567     case CSSValueWebkitFocusRingColor:
568         color = convertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
569         break;
570     case CSSValueWindow:
571         color = convertNSColorToColor([NSColor windowBackgroundColor]);
572         break;
573     case CSSValueWindowframe:
574         color = convertNSColorToColor([NSColor windowFrameColor]);
575         break;
576     case CSSValueWindowtext:
577         color = convertNSColorToColor([NSColor windowFrameTextColor]);
578         break;
579 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
580     case CSSValueAppleWirelessPlaybackTargetActive:
581         color = convertNSColorToColor([NSColor systemBlueColor]);
582         break;
583     case CSSValueAppleSystemBlue:
584         color = convertNSColorToColor([NSColor systemBlueColor]);
585         break;
586     case CSSValueAppleSystemBrown:
587         color = convertNSColorToColor([NSColor systemBrownColor]);
588         break;
589     case CSSValueAppleSystemGray:
590         color = convertNSColorToColor([NSColor systemGrayColor]);
591         break;
592     case CSSValueAppleSystemGreen:
593         color = convertNSColorToColor([NSColor systemGreenColor]);
594         break;
595     case CSSValueAppleSystemOrange:
596         color = convertNSColorToColor([NSColor systemOrangeColor]);
597         break;
598     case CSSValueAppleSystemPink:
599         color = convertNSColorToColor([NSColor systemPinkColor]);
600         break;
601     case CSSValueAppleSystemPurple:
602         color = convertNSColorToColor([NSColor systemPurpleColor]);
603         break;
604     case CSSValueAppleSystemRed:
605         color = convertNSColorToColor([NSColor systemRedColor]);
606         break;
607     case CSSValueAppleSystemYellow:
608         color = convertNSColorToColor([NSColor systemYellowColor]);
609         break;
610 #endif
611     default:
612         break;
613     }
614
615     if (!color.isValid())
616         color = RenderTheme::systemColor(cssValueID);
617
618     addResult.iterator->value = color;
619
620     return addResult.iterator->value;
621 }
622
623 bool RenderThemeMac::usesTestModeFocusRingColor() const
624 {
625     return WebCore::usesTestModeFocusRingColor();
626 }
627
628 bool RenderThemeMac::isControlStyled(const RenderStyle& style, const BorderData& border,
629                                      const FillLayer& background, const Color& backgroundColor) const
630 {
631     if (style.appearance() == TextFieldPart || style.appearance() == TextAreaPart || style.appearance() == ListboxPart)
632         return style.border() != border;
633
634     // FIXME: This is horrible, but there is not much else that can be done.  Menu lists cannot draw properly when
635     // scaled.  They can't really draw properly when transformed either.  We can't detect the transform case at style
636     // adjustment time so that will just have to stay broken.  We can however detect that we're zooming.  If zooming
637     // is in effect we treat it like the control is styled.
638     if (style.appearance() == MenulistPart && style.effectiveZoom() != 1.0f)
639         return true;
640
641     return RenderTheme::isControlStyled(style, border, background, backgroundColor);
642 }
643
644 static FloatRect inflateRect(const FloatRect& rect, const IntSize& size, const int* margins, float zoomLevel)
645 {
646     // Only do the inflation if the available width/height are too small. Otherwise try to
647     // fit the glow/check space into the available box's width/height.
648     int widthDelta = rect.width() - (size.width() + margins[leftMargin] * zoomLevel + margins[rightMargin] * zoomLevel);
649     int heightDelta = rect.height() - (size.height() + margins[topMargin] * zoomLevel + margins[bottomMargin] * zoomLevel);
650     FloatRect result(rect);
651     if (widthDelta < 0) {
652         result.setX(result.x() - margins[leftMargin] * zoomLevel);
653         result.setWidth(result.width() - widthDelta);
654     }
655     if (heightDelta < 0) {
656         result.setY(result.y() - margins[topMargin] * zoomLevel);
657         result.setHeight(result.height() - heightDelta);
658     }
659     return result;
660 }
661
662 void RenderThemeMac::adjustRepaintRect(const RenderObject& renderer, FloatRect& rect)
663 {
664     ControlPart part = renderer.style().appearance();
665
666 #if USE(NEW_THEME)
667     switch (part) {
668         case CheckboxPart:
669         case RadioPart:
670         case PushButtonPart:
671         case SquareButtonPart:
672         case DefaultButtonPart:
673         case ButtonPart:
674         case InnerSpinButtonPart:
675             return RenderTheme::adjustRepaintRect(renderer, rect);
676         default:
677             break;
678     }
679 #endif
680
681     float zoomLevel = renderer.style().effectiveZoom();
682
683     if (part == MenulistPart) {
684         setPopupButtonCellState(renderer, IntSize(rect.size()));
685         IntSize size = popupButtonSizes()[[popupButton() controlSize]];
686         size.setHeight(size.height() * zoomLevel);
687         size.setWidth(rect.width());
688         rect = inflateRect(rect, size, popupButtonMargins(), zoomLevel);
689     }
690 }
691
692 FloatRect RenderThemeMac::convertToPaintingRect(const RenderObject& inputRenderer, const RenderObject& partRenderer, const FloatRect& inputRect, const IntRect& r) const
693 {
694     FloatRect partRect(inputRect);
695
696     // Compute an offset between the part renderer and the input renderer
697     FloatSize offsetFromInputRenderer;
698     const RenderObject* renderer = &partRenderer;
699     while (renderer && renderer != &inputRenderer) {
700         RenderElement* containingRenderer = renderer->container();
701         ASSERT(containingRenderer);
702         offsetFromInputRenderer -= roundedIntSize(renderer->offsetFromContainer(*containingRenderer, LayoutPoint()));
703         renderer = containingRenderer;
704     }
705     // If the input renderer was not a container, something went wrong
706     ASSERT(renderer == &inputRenderer);
707     // Move the rect into partRenderer's coords
708     partRect.move(offsetFromInputRenderer);
709     // Account for the local drawing offset (tx, ty)
710     partRect.move(r.x(), r.y());
711
712     return partRect;
713 }
714
715 void RenderThemeMac::updateCheckedState(NSCell* cell, const RenderObject& o)
716 {
717     bool oldIndeterminate = [cell state] == NSMixedState;
718     bool indeterminate = isIndeterminate(o);
719     bool checked = isChecked(o);
720
721     if (oldIndeterminate != indeterminate) {
722         [cell setState:indeterminate ? NSMixedState : (checked ? NSOnState : NSOffState)];
723         return;
724     }
725
726     bool oldChecked = [cell state] == NSOnState;
727     if (checked != oldChecked)
728         [cell setState:checked ? NSOnState : NSOffState];
729 }
730
731 void RenderThemeMac::updateEnabledState(NSCell* cell, const RenderObject& o)
732 {
733     bool oldEnabled = [cell isEnabled];
734     bool enabled = isEnabled(o);
735     if (enabled != oldEnabled)
736         [cell setEnabled:enabled];
737 }
738
739 void RenderThemeMac::updateFocusedState(NSCell* cell, const RenderObject& o)
740 {
741     bool oldFocused = [cell showsFirstResponder];
742     bool focused = isFocused(o) && o.style().outlineStyleIsAuto();
743     if (focused != oldFocused)
744         [cell setShowsFirstResponder:focused];
745 }
746
747 void RenderThemeMac::updatePressedState(NSCell* cell, const RenderObject& o)
748 {
749     bool oldPressed = [cell isHighlighted];
750     bool pressed = is<Element>(o.node()) && downcast<Element>(*o.node()).active();
751     if (pressed != oldPressed)
752         [cell setHighlighted:pressed];
753 }
754
755 bool RenderThemeMac::controlSupportsTints(const RenderObject& o) const
756 {
757     // An alternate way to implement this would be to get the appropriate cell object
758     // and call the private _needRedrawOnWindowChangedKeyState method. An advantage of
759     // that would be that we would match AppKit behavior more closely, but a disadvantage
760     // would be that we would rely on an AppKit SPI method.
761
762     if (!isEnabled(o))
763         return false;
764
765     // Checkboxes only have tint when checked.
766     if (o.style().appearance() == CheckboxPart)
767         return isChecked(o);
768
769     // For now assume other controls have tint if enabled.
770     return true;
771 }
772
773 NSControlSize RenderThemeMac::controlSizeForFont(RenderStyle& style) const
774 {
775     int fontSize = style.fontSize();
776     if (fontSize >= 16)
777         return NSRegularControlSize;
778     if (fontSize >= 11)
779         return NSSmallControlSize;
780     return NSMiniControlSize;
781 }
782
783 NSControlSize RenderThemeMac::controlSizeForCell(NSCell*, const IntSize* sizes, const IntSize& minSize, float zoomLevel) const
784 {
785     if (minSize.width() >= static_cast<int>(sizes[NSRegularControlSize].width() * zoomLevel)
786         && minSize.height() >= static_cast<int>(sizes[NSRegularControlSize].height() * zoomLevel))
787         return NSRegularControlSize;
788
789     if (minSize.width() >= static_cast<int>(sizes[NSSmallControlSize].width() * zoomLevel)
790         && minSize.height() >= static_cast<int>(sizes[NSSmallControlSize].height() * zoomLevel))
791         return NSSmallControlSize;
792
793     return NSMiniControlSize;
794 }
795
796 void RenderThemeMac::setControlSize(NSCell* cell, const IntSize* sizes, const IntSize& minSize, float zoomLevel)
797 {
798     NSControlSize size = controlSizeForCell(cell, sizes, minSize, zoomLevel);
799     if (size != [cell controlSize]) // Only update if we have to, since AppKit does work even if the size is the same.
800         [cell setControlSize:size];
801 }
802
803 IntSize RenderThemeMac::sizeForFont(RenderStyle& style, const IntSize* sizes) const
804 {
805     if (style.effectiveZoom() != 1.0f) {
806         IntSize result = sizes[controlSizeForFont(style)];
807         return IntSize(result.width() * style.effectiveZoom(), result.height() * style.effectiveZoom());
808     }
809     return sizes[controlSizeForFont(style)];
810 }
811
812 IntSize RenderThemeMac::sizeForSystemFont(RenderStyle& style, const IntSize* sizes) const
813 {
814     if (style.effectiveZoom() != 1.0f) {
815         IntSize result = sizes[controlSizeForSystemFont(style)];
816         return IntSize(result.width() * style.effectiveZoom(), result.height() * style.effectiveZoom());
817     }
818     return sizes[controlSizeForSystemFont(style)];
819 }
820
821 void RenderThemeMac::setSizeFromFont(RenderStyle& style, const IntSize* sizes) const
822 {
823     // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
824     IntSize size = sizeForFont(style, sizes);
825     if (style.width().isIntrinsicOrAuto() && size.width() > 0)
826         style.setWidth(Length(size.width(), Fixed));
827     if (style.height().isAuto() && size.height() > 0)
828         style.setHeight(Length(size.height(), Fixed));
829 }
830
831 void RenderThemeMac::setFontFromControlSize(StyleResolver&, RenderStyle& style, NSControlSize controlSize) const
832 {
833     FontDescription fontDescription;
834     fontDescription.setIsAbsoluteSize(true);
835
836     NSFont* font = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:controlSize]];
837     fontDescription.setOneFamily(AtomicString("-apple-system", AtomicString::ConstructFromLiteral));
838     fontDescription.setComputedSize([font pointSize] * style.effectiveZoom());
839     fontDescription.setSpecifiedSize([font pointSize] * style.effectiveZoom());
840
841     // Reset line height
842     style.setLineHeight(RenderStyle::initialLineHeight());
843
844     if (style.setFontDescription(fontDescription))
845         style.fontCascade().update(0);
846 }
847
848 NSControlSize RenderThemeMac::controlSizeForSystemFont(RenderStyle& style) const
849 {
850     int fontSize = style.fontSize();
851     if (fontSize >= [NSFont systemFontSizeForControlSize:NSRegularControlSize])
852         return NSRegularControlSize;
853     if (fontSize >= [NSFont systemFontSizeForControlSize:NSSmallControlSize])
854         return NSSmallControlSize;
855     return NSMiniControlSize;
856 }
857
858 bool RenderThemeMac::paintTextField(const RenderObject& o, const PaintInfo& paintInfo, const FloatRect& r)
859 {
860     LocalCurrentGraphicsContext localContext(paintInfo.context);
861
862     NSTextFieldCell *textField = this->textField();
863
864     GraphicsContextStateSaver stateSaver(*paintInfo.context);
865
866     [textField setEnabled:(isEnabled(o) && !isReadOnlyControl(o))];
867     [textField drawWithFrame:NSRect(r) inView:documentViewFor(o)];
868
869     [textField setControlView:nil];
870
871     return false;
872 }
873
874 void RenderThemeMac::adjustTextFieldStyle(StyleResolver&, RenderStyle&, Element*) const
875 {
876 }
877
878 bool RenderThemeMac::paintTextArea(const RenderObject& o, const PaintInfo& paintInfo, const FloatRect& r)
879 {
880     LocalCurrentGraphicsContext localContext(paintInfo.context);
881     wkDrawBezeledTextArea(r, isEnabled(o) && !isReadOnlyControl(o));
882     return false;
883 }
884
885 void RenderThemeMac::adjustTextAreaStyle(StyleResolver&, RenderStyle&, Element*) const
886 {
887 }
888
889 const int* RenderThemeMac::popupButtonMargins() const
890 {
891     static const int margins[3][4] =
892     {
893         { 0, 3, 1, 3 },
894         { 0, 3, 2, 3 },
895         { 0, 1, 0, 1 }
896     };
897     return margins[[popupButton() controlSize]];
898 }
899
900 const IntSize* RenderThemeMac::popupButtonSizes() const
901 {
902     static const IntSize sizes[3] = { IntSize(0, 21), IntSize(0, 18), IntSize(0, 15) };
903     return sizes;
904 }
905
906 const int* RenderThemeMac::popupButtonPadding(NSControlSize size) const
907 {
908     static const int padding[3][4] =
909     {
910         { 2, 26, 3, 8 },
911         { 2, 23, 3, 8 },
912         { 2, 22, 3, 10 }
913     };
914     return padding[size];
915 }
916
917 bool RenderThemeMac::paintMenuList(const RenderObject& renderer, const PaintInfo& paintInfo, const FloatRect& rect)
918 {
919     LocalCurrentGraphicsContext localContext(paintInfo.context);
920     setPopupButtonCellState(renderer, IntSize(rect.size()));
921
922     NSPopUpButtonCell* popupButton = this->popupButton();
923
924     float zoomLevel = renderer.style().effectiveZoom();
925     IntSize size = popupButtonSizes()[[popupButton controlSize]];
926     size.setHeight(size.height() * zoomLevel);
927     size.setWidth(rect.width());
928
929     // Now inflate it to account for the shadow.
930     FloatRect inflatedRect = rect;
931     if (rect.width() >= minimumMenuListSize(renderer.style()))
932         inflatedRect = inflateRect(rect, size, popupButtonMargins(), zoomLevel);
933
934     GraphicsContextStateSaver stateSaver(*paintInfo.context);
935
936     // Before Yosemite we did not want the cell to ever draw outside the given rectangle.
937 #if __MAC_OS_X_VERSION_MIN_REQUIRED < 101000
938     paintInfo.context->clip(inflatedRect);
939 #endif
940
941     if (zoomLevel != 1.0f) {
942         inflatedRect.setWidth(inflatedRect.width() / zoomLevel);
943         inflatedRect.setHeight(inflatedRect.height() / zoomLevel);
944         paintInfo.context->translate(inflatedRect.x(), inflatedRect.y());
945         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
946         paintInfo.context->translate(-inflatedRect.x(), -inflatedRect.y());
947     }
948
949     NSView *view = documentViewFor(renderer);
950     Page* page = renderer.document().page();
951     float pageScaleFactor = page->pageScaleFactor();
952     float deviceScaleFactor = page->deviceScaleFactor();
953     bool shouldDrawFocusRing = isFocused(renderer) && renderer.style().outlineStyleIsAuto();
954     bool shouldUseImageBuffer = zoomLevel != 1.0f || pageScaleFactor != 1.0f;
955     bool shouldDrawCell = true;
956     if (ThemeMac::drawCellOrFocusRingWithViewIntoContext(popupButton, paintInfo.context, inflatedRect, view, shouldDrawCell, shouldDrawFocusRing, shouldUseImageBuffer, deviceScaleFactor))
957         page->focusController().setFocusedElementNeedsRepaint();
958
959     [popupButton setControlView:nil];
960
961     return false;
962 }
963
964 #if ENABLE(METER_ELEMENT)
965
966 IntSize RenderThemeMac::meterSizeForBounds(const RenderMeter& renderMeter, const IntRect& bounds) const
967 {
968     if (NoControlPart == renderMeter.style().appearance())
969         return bounds.size();
970
971     NSLevelIndicatorCell* cell = levelIndicatorFor(renderMeter);
972     // Makes enough room for cell's intrinsic size.
973     NSSize cellSize = [cell cellSizeForBounds:IntRect(IntPoint(), bounds.size())];
974     return IntSize(bounds.width() < cellSize.width ? cellSize.width : bounds.width(),
975                    bounds.height() < cellSize.height ? cellSize.height : bounds.height());
976 }
977
978 bool RenderThemeMac::paintMeter(const RenderObject& renderObject, const PaintInfo& paintInfo, const IntRect& rect)
979 {
980     if (!is<RenderMeter>(renderObject))
981         return true;
982
983     LocalCurrentGraphicsContext localContext(paintInfo.context);
984
985     NSLevelIndicatorCell* cell = levelIndicatorFor(downcast<RenderMeter>(renderObject));
986     GraphicsContextStateSaver stateSaver(*paintInfo.context);
987
988     [cell drawWithFrame:rect inView:documentViewFor(renderObject)];
989     [cell setControlView:nil];
990     return false;
991 }
992
993 bool RenderThemeMac::supportsMeter(ControlPart part) const
994 {
995     switch (part) {
996     case RelevancyLevelIndicatorPart:
997     case DiscreteCapacityLevelIndicatorPart:
998     case RatingLevelIndicatorPart:
999     case MeterPart:
1000     case ContinuousCapacityLevelIndicatorPart:
1001         return true;
1002     default:
1003         return false;
1004     }
1005 }
1006
1007 NSLevelIndicatorStyle RenderThemeMac::levelIndicatorStyleFor(ControlPart part) const
1008 {
1009     switch (part) {
1010     case RelevancyLevelIndicatorPart:
1011         return NSRelevancyLevelIndicatorStyle;
1012     case DiscreteCapacityLevelIndicatorPart:
1013         return NSDiscreteCapacityLevelIndicatorStyle;
1014     case RatingLevelIndicatorPart:
1015         return NSRatingLevelIndicatorStyle;
1016     case MeterPart:
1017     case ContinuousCapacityLevelIndicatorPart:
1018     default:
1019         return NSContinuousCapacityLevelIndicatorStyle;
1020     }
1021
1022 }
1023
1024 NSLevelIndicatorCell* RenderThemeMac::levelIndicatorFor(const RenderMeter& renderMeter) const
1025 {
1026     const RenderStyle& style = renderMeter.style();
1027     ASSERT(style.appearance() != NoControlPart);
1028
1029     if (!m_levelIndicator)
1030         m_levelIndicator = adoptNS([[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle]);
1031     NSLevelIndicatorCell* cell = m_levelIndicator.get();
1032
1033     HTMLMeterElement* element = renderMeter.meterElement();
1034     double value = element->value();
1035
1036     // Because NSLevelIndicatorCell does not support optimum-in-the-middle type coloring,
1037     // we explicitly control the color instead giving low and high value to NSLevelIndicatorCell as is.
1038     switch (element->gaugeRegion()) {
1039     case HTMLMeterElement::GaugeRegionOptimum:
1040         // Make meter the green
1041         [cell setWarningValue:value + 1];
1042         [cell setCriticalValue:value + 2];
1043         break;
1044     case HTMLMeterElement::GaugeRegionSuboptimal:
1045         // Make the meter yellow
1046         [cell setWarningValue:value - 1];
1047         [cell setCriticalValue:value + 1];
1048         break;
1049     case HTMLMeterElement::GaugeRegionEvenLessGood:
1050         // Make the meter red
1051         [cell setWarningValue:value - 2];
1052         [cell setCriticalValue:value - 1];
1053         break;
1054     }
1055
1056     [cell setLevelIndicatorStyle:levelIndicatorStyleFor(style.appearance())];
1057     [cell setBaseWritingDirection:style.isLeftToRightDirection() ? NSWritingDirectionLeftToRight : NSWritingDirectionRightToLeft];
1058     [cell setMinValue:element->min()];
1059     [cell setMaxValue:element->max()];
1060     RetainPtr<NSNumber> valueObject = [NSNumber numberWithDouble:value];
1061     [cell setObjectValue:valueObject.get()];
1062
1063     return cell;
1064 }
1065
1066 #endif
1067
1068 const IntSize* RenderThemeMac::progressBarSizes() const
1069 {
1070     static const IntSize sizes[3] = { IntSize(0, 20), IntSize(0, 12), IntSize(0, 12) };
1071     return sizes;
1072 }
1073
1074 const int* RenderThemeMac::progressBarMargins(NSControlSize controlSize) const
1075 {
1076     static const int margins[3][4] =
1077     {
1078         { 0, 0, 1, 0 },
1079         { 0, 0, 1, 0 },
1080         { 0, 0, 1, 0 },
1081     };
1082     return margins[controlSize];
1083 }
1084
1085 IntRect RenderThemeMac::progressBarRectForBounds(const RenderObject& renderObject, const IntRect& bounds) const
1086 {
1087     // Workaround until <rdar://problem/15855086> is fixed.
1088     int maxDimension = static_cast<int>(std::numeric_limits<ushort>::max());
1089     IntRect progressBarBounds(bounds.x(), bounds.y(), std::min(bounds.width(), maxDimension), std::min(bounds.height(), maxDimension));
1090     if (NoControlPart == renderObject.style().appearance())
1091         return progressBarBounds;
1092
1093     float zoomLevel = renderObject.style().effectiveZoom();
1094     NSControlSize controlSize = controlSizeForFont(renderObject.style());
1095     IntSize size = progressBarSizes()[controlSize];
1096     size.setHeight(size.height() * zoomLevel);
1097     size.setWidth(progressBarBounds.width());
1098
1099     // Now inflate it to account for the shadow.
1100     IntRect inflatedRect = progressBarBounds;
1101     if (progressBarBounds.height() <= minimumProgressBarHeight(renderObject.style()))
1102         inflatedRect = IntRect(inflateRect(inflatedRect, size, progressBarMargins(controlSize), zoomLevel));
1103
1104     return inflatedRect;
1105 }
1106
1107 int RenderThemeMac::minimumProgressBarHeight(RenderStyle& style) const
1108 {
1109     return sizeForSystemFont(style, progressBarSizes()).height();
1110 }
1111
1112 double RenderThemeMac::animationRepeatIntervalForProgressBar(RenderProgress&) const
1113 {
1114     return progressAnimationFrameRate;
1115 }
1116
1117 double RenderThemeMac::animationDurationForProgressBar(RenderProgress&) const
1118 {
1119     return progressAnimationNumFrames * progressAnimationFrameRate;
1120 }
1121
1122 void RenderThemeMac::adjustProgressBarStyle(StyleResolver&, RenderStyle&, Element*) const
1123 {
1124 }
1125
1126 bool RenderThemeMac::paintProgressBar(const RenderObject& renderObject, const PaintInfo& paintInfo, const IntRect& rect)
1127 {
1128     if (!is<RenderProgress>(renderObject))
1129         return true;
1130
1131     IntRect inflatedRect = progressBarRectForBounds(renderObject, rect);
1132     NSControlSize controlSize = controlSizeForFont(renderObject.style());
1133
1134     const auto& renderProgress = downcast<RenderProgress>(renderObject);
1135     HIThemeTrackDrawInfo trackInfo;
1136     trackInfo.version = 0;
1137     if (controlSize == NSRegularControlSize)
1138         trackInfo.kind = renderProgress.position() < 0 ? kThemeLargeIndeterminateBar : kThemeLargeProgressBar;
1139     else
1140         trackInfo.kind = renderProgress.position() < 0 ? kThemeMediumIndeterminateBar : kThemeMediumProgressBar;
1141
1142     float deviceScaleFactor = renderObject.document().deviceScaleFactor();
1143     trackInfo.bounds = IntRect(IntPoint(), inflatedRect.size());
1144     trackInfo.min = 0;
1145     trackInfo.max = std::numeric_limits<SInt32>::max();
1146     trackInfo.value = lround(renderProgress.position() * nextafter(trackInfo.max, 0));
1147     trackInfo.trackInfo.progress.phase = lround(renderProgress.animationProgress() * nextafter(progressAnimationNumFrames, 0) * deviceScaleFactor);
1148     trackInfo.attributes = kThemeTrackHorizontal;
1149     trackInfo.enableState = isActive(renderObject) ? kThemeTrackActive : kThemeTrackInactive;
1150     trackInfo.reserved = 0;
1151     trackInfo.filler1 = 0;
1152
1153     std::unique_ptr<ImageBuffer> imageBuffer = ImageBuffer::createCompatibleBuffer(inflatedRect.size(), deviceScaleFactor, ColorSpaceDeviceRGB, paintInfo.context, true);
1154     if (!imageBuffer)
1155         return true;
1156
1157     ContextContainer cgContextContainer(imageBuffer->context());
1158     CGContextRef cgContext = cgContextContainer.context();
1159     HIThemeDrawTrack(&trackInfo, 0, cgContext, kHIThemeOrientationNormal);
1160
1161     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1162
1163     if (!renderProgress.style().isLeftToRightDirection()) {
1164         paintInfo.context->translate(2 * inflatedRect.x() + inflatedRect.width(), 0);
1165         paintInfo.context->scale(FloatSize(-1, 1));
1166     }
1167
1168     paintInfo.context->drawImageBuffer(imageBuffer.get(), ColorSpaceDeviceRGB, inflatedRect.location());
1169     return false;
1170 }
1171
1172 const float baseFontSize = 11.0f;
1173 const float baseArrowHeight = 4.0f;
1174 const float baseArrowWidth = 5.0f;
1175 const float baseSpaceBetweenArrows = 2.0f;
1176 const int arrowPaddingLeft = 6;
1177 const int arrowPaddingRight = 6;
1178 const int paddingBeforeSeparator = 4;
1179 const int baseBorderRadius = 5;
1180 const int styledPopupPaddingLeft = 8;
1181 const int styledPopupPaddingTop = 1;
1182 const int styledPopupPaddingBottom = 2;
1183
1184 static void TopGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1185 {
1186     static const float dark[4] = { 1.0f, 1.0f, 1.0f, 0.4f };
1187     static const float light[4] = { 1.0f, 1.0f, 1.0f, 0.15f };
1188     float a = inData[0];
1189     int i = 0;
1190     for (i = 0; i < 4; i++)
1191         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1192 }
1193
1194 static void BottomGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1195 {
1196     static const float dark[4] = { 1.0f, 1.0f, 1.0f, 0.0f };
1197     static const float light[4] = { 1.0f, 1.0f, 1.0f, 0.3f };
1198     float a = inData[0];
1199     int i = 0;
1200     for (i = 0; i < 4; i++)
1201         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1202 }
1203
1204 static void MainGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1205 {
1206     static const float dark[4] = { 0.0f, 0.0f, 0.0f, 0.15f };
1207     static const float light[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
1208     float a = inData[0];
1209     int i = 0;
1210     for (i = 0; i < 4; i++)
1211         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1212 }
1213
1214 static void TrackGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
1215 {
1216     static const float dark[4] = { 0.0f, 0.0f, 0.0f, 0.678f };
1217     static const float light[4] = { 0.0f, 0.0f, 0.0f, 0.13f };
1218     float a = inData[0];
1219     int i = 0;
1220     for (i = 0; i < 4; i++)
1221         outData[i] = (1.0f - a) * dark[i] + a * light[i];
1222 }
1223
1224 void RenderThemeMac::paintMenuListButtonGradients(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1225 {
1226     if (r.isEmpty())
1227         return;
1228
1229     ContextContainer cgContextContainer(paintInfo.context);
1230     CGContextRef context = cgContextContainer.context();
1231
1232     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1233
1234     FloatRoundedRect border = FloatRoundedRect(o.style().getRoundedBorderFor(r));
1235     int radius = border.radii().topLeft().width();
1236
1237     CGColorSpaceRef cspace = deviceRGBColorSpaceRef();
1238
1239     FloatRect topGradient(r.x(), r.y(), r.width(), r.height() / 2.0f);
1240     struct CGFunctionCallbacks topCallbacks = { 0, TopGradientInterpolate, NULL };
1241     RetainPtr<CGFunctionRef> topFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &topCallbacks));
1242     RetainPtr<CGShadingRef> topShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(topGradient.x(), topGradient.y()), CGPointMake(topGradient.x(), topGradient.maxY()), topFunction.get(), false, false));
1243
1244     FloatRect bottomGradient(r.x() + radius, r.y() + r.height() / 2.0f, r.width() - 2.0f * radius, r.height() / 2.0f);
1245     struct CGFunctionCallbacks bottomCallbacks = { 0, BottomGradientInterpolate, NULL };
1246     RetainPtr<CGFunctionRef> bottomFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &bottomCallbacks));
1247     RetainPtr<CGShadingRef> bottomShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bottomGradient.x(),  bottomGradient.y()), CGPointMake(bottomGradient.x(), bottomGradient.maxY()), bottomFunction.get(), false, false));
1248
1249     struct CGFunctionCallbacks mainCallbacks = { 0, MainGradientInterpolate, NULL };
1250     RetainPtr<CGFunctionRef> mainFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &mainCallbacks));
1251     RetainPtr<CGShadingRef> mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(r.x(),  r.y()), CGPointMake(r.x(), r.maxY()), mainFunction.get(), false, false));
1252
1253     RetainPtr<CGShadingRef> leftShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(r.x(),  r.y()), CGPointMake(r.x() + radius, r.y()), mainFunction.get(), false, false));
1254
1255     RetainPtr<CGShadingRef> rightShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(r.maxX(),  r.y()), CGPointMake(r.maxX() - radius, r.y()), mainFunction.get(), false, false));
1256
1257     {
1258         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1259         CGContextClipToRect(context, r);
1260         paintInfo.context->clipRoundedRect(border);
1261         context = cgContextContainer.context();
1262         CGContextDrawShading(context, mainShading.get());
1263     }
1264
1265     {
1266         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1267         CGContextClipToRect(context, topGradient);
1268         paintInfo.context->clipRoundedRect(FloatRoundedRect(enclosingIntRect(topGradient), border.radii().topLeft(), border.radii().topRight(), IntSize(), IntSize()));
1269         context = cgContextContainer.context();
1270         CGContextDrawShading(context, topShading.get());
1271     }
1272
1273     if (!bottomGradient.isEmpty()) {
1274         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1275         CGContextClipToRect(context, bottomGradient);
1276         paintInfo.context->clipRoundedRect(FloatRoundedRect(enclosingIntRect(bottomGradient), IntSize(), IntSize(), border.radii().bottomLeft(), border.radii().bottomRight()));
1277         context = cgContextContainer.context();
1278         CGContextDrawShading(context, bottomShading.get());
1279     }
1280
1281     {
1282         GraphicsContextStateSaver stateSaver(*paintInfo.context);
1283         CGContextClipToRect(context, r);
1284         paintInfo.context->clipRoundedRect(border);
1285         context = cgContextContainer.context();
1286         CGContextDrawShading(context, leftShading.get());
1287         CGContextDrawShading(context, rightShading.get());
1288     }
1289 }
1290
1291 bool RenderThemeMac::paintMenuListButtonDecorations(const RenderBox& renderer, const PaintInfo& paintInfo, const FloatRect& rect)
1292 {
1293     IntRect bounds = IntRect(rect.x() + renderer.style().borderLeftWidth(),
1294         rect.y() + renderer.style().borderTopWidth(),
1295         rect.width() - renderer.style().borderLeftWidth() - renderer.style().borderRightWidth(),
1296         rect.height() - renderer.style().borderTopWidth() - renderer.style().borderBottomWidth());
1297     // Draw the gradients to give the styled popup menu a button appearance
1298     paintMenuListButtonGradients(renderer, paintInfo, bounds);
1299
1300     // 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
1301     float fontScale = std::min(renderer.style().fontSize() / baseFontSize, bounds.height() / (baseArrowHeight * 2 + baseSpaceBetweenArrows));
1302     float centerY = bounds.y() + bounds.height() / 2.0f;
1303     float arrowHeight = baseArrowHeight * fontScale;
1304     float arrowWidth = baseArrowWidth * fontScale;
1305     float leftEdge = bounds.maxX() - arrowPaddingRight * renderer.style().effectiveZoom() - arrowWidth;
1306     float spaceBetweenArrows = baseSpaceBetweenArrows * fontScale;
1307
1308     if (bounds.width() < arrowWidth + arrowPaddingLeft * renderer.style().effectiveZoom())
1309         return false;
1310
1311     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1312
1313     paintInfo.context->setFillColor(renderer.style().visitedDependentColor(CSSPropertyColor), renderer.style().colorSpace());
1314     paintInfo.context->setStrokeStyle(NoStroke);
1315
1316     FloatPoint arrow1[3];
1317     arrow1[0] = FloatPoint(leftEdge, centerY - spaceBetweenArrows / 2.0f);
1318     arrow1[1] = FloatPoint(leftEdge + arrowWidth, centerY - spaceBetweenArrows / 2.0f);
1319     arrow1[2] = FloatPoint(leftEdge + arrowWidth / 2.0f, centerY - spaceBetweenArrows / 2.0f - arrowHeight);
1320
1321     // Draw the top arrow
1322     paintInfo.context->drawConvexPolygon(3, arrow1, true);
1323
1324     FloatPoint arrow2[3];
1325     arrow2[0] = FloatPoint(leftEdge, centerY + spaceBetweenArrows / 2.0f);
1326     arrow2[1] = FloatPoint(leftEdge + arrowWidth, centerY + spaceBetweenArrows / 2.0f);
1327     arrow2[2] = FloatPoint(leftEdge + arrowWidth / 2.0f, centerY + spaceBetweenArrows / 2.0f + arrowHeight);
1328
1329     // Draw the bottom arrow
1330     paintInfo.context->drawConvexPolygon(3, arrow2, true);
1331
1332     Color leftSeparatorColor(0, 0, 0, 40);
1333     Color rightSeparatorColor(255, 255, 255, 40);
1334
1335     // FIXME: Should the separator thickness and space be scaled up by fontScale?
1336     int separatorSpace = 2; // Deliberately ignores zoom since it looks nicer if it stays thin.
1337     int leftEdgeOfSeparator = static_cast<int>(leftEdge - arrowPaddingLeft * renderer.style().effectiveZoom()); // FIXME: Round?
1338
1339     // Draw the separator to the left of the arrows
1340     paintInfo.context->setStrokeThickness(1); // Deliberately ignores zoom since it looks nicer if it stays thin.
1341     paintInfo.context->setStrokeStyle(SolidStroke);
1342     paintInfo.context->setStrokeColor(leftSeparatorColor, ColorSpaceDeviceRGB);
1343     paintInfo.context->drawLine(IntPoint(leftEdgeOfSeparator, bounds.y()),
1344                                 IntPoint(leftEdgeOfSeparator, bounds.maxY()));
1345
1346     paintInfo.context->setStrokeColor(rightSeparatorColor, ColorSpaceDeviceRGB);
1347     paintInfo.context->drawLine(IntPoint(leftEdgeOfSeparator + separatorSpace, bounds.y()),
1348                                 IntPoint(leftEdgeOfSeparator + separatorSpace, bounds.maxY()));
1349     return false;
1350 }
1351
1352 static const IntSize* menuListButtonSizes()
1353 {
1354     static const IntSize sizes[3] = { IntSize(0, 21), IntSize(0, 18), IntSize(0, 15) };
1355     return sizes;
1356 }
1357
1358 void RenderThemeMac::adjustMenuListStyle(StyleResolver& styleResolver, RenderStyle& style, Element* e) const
1359 {
1360     NSControlSize controlSize = controlSizeForFont(style);
1361
1362     style.resetBorder();
1363     style.resetPadding();
1364
1365     // Height is locked to auto.
1366     style.setHeight(Length(Auto));
1367
1368     // White-space is locked to pre
1369     style.setWhiteSpace(PRE);
1370
1371     // Set the foreground color to black or gray when we have the aqua look.
1372     // Cast to RGB32 is to work around a compiler bug.
1373     style.setColor(e && !e->isDisabledFormControl() ? static_cast<RGBA32>(Color::black) : Color::darkGray);
1374
1375     // Set the button's vertical size.
1376     setSizeFromFont(style, menuListButtonSizes());
1377
1378     // 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
1379     // a reasonable control size, but once that control size is determined, we throw that font away and use the appropriate
1380     // system font for the control size instead.
1381     setFontFromControlSize(styleResolver, style, controlSize);
1382
1383     style.setBoxShadow(nullptr);
1384 }
1385
1386 int RenderThemeMac::popupInternalPaddingLeft(RenderStyle& style) const
1387 {
1388     if (style.appearance() == MenulistPart)
1389         return popupButtonPadding(controlSizeForFont(style))[leftPadding] * style.effectiveZoom();
1390     if (style.appearance() == MenulistButtonPart)
1391         return styledPopupPaddingLeft * style.effectiveZoom();
1392     return 0;
1393 }
1394
1395 int RenderThemeMac::popupInternalPaddingRight(RenderStyle& style) const
1396 {
1397     if (style.appearance() == MenulistPart)
1398         return popupButtonPadding(controlSizeForFont(style))[rightPadding] * style.effectiveZoom();
1399     if (style.appearance() == MenulistButtonPart) {
1400         float fontScale = style.fontSize() / baseFontSize;
1401         float arrowWidth = baseArrowWidth * fontScale;
1402         return static_cast<int>(ceilf(arrowWidth + (arrowPaddingLeft + arrowPaddingRight + paddingBeforeSeparator) * style.effectiveZoom()));
1403     }
1404     return 0;
1405 }
1406
1407 int RenderThemeMac::popupInternalPaddingTop(RenderStyle& style) const
1408 {
1409     if (style.appearance() == MenulistPart)
1410         return popupButtonPadding(controlSizeForFont(style))[topPadding] * style.effectiveZoom();
1411     if (style.appearance() == MenulistButtonPart)
1412         return styledPopupPaddingTop * style.effectiveZoom();
1413     return 0;
1414 }
1415
1416 int RenderThemeMac::popupInternalPaddingBottom(RenderStyle& style) const
1417 {
1418     if (style.appearance() == MenulistPart)
1419         return popupButtonPadding(controlSizeForFont(style))[bottomPadding] * style.effectiveZoom();
1420     if (style.appearance() == MenulistButtonPart)
1421         return styledPopupPaddingBottom * style.effectiveZoom();
1422     return 0;
1423 }
1424
1425 PopupMenuStyle::PopupMenuSize RenderThemeMac::popupMenuSize(const RenderStyle& style, IntRect& rect) const
1426 {
1427     NSPopUpButtonCell* popupButton = this->popupButton();
1428     NSControlSize size = controlSizeForCell(popupButton, popupButtonSizes(), rect.size(), style.effectiveZoom());
1429     switch (size) {
1430     case NSRegularControlSize:
1431         return PopupMenuStyle::PopupMenuSizeNormal;
1432     case NSSmallControlSize:
1433         return PopupMenuStyle::PopupMenuSizeSmall;
1434     case NSMiniControlSize:
1435         return PopupMenuStyle::PopupMenuSizeMini;
1436     default:
1437         return PopupMenuStyle::PopupMenuSizeNormal;
1438     }
1439 }
1440
1441 void RenderThemeMac::adjustMenuListButtonStyle(StyleResolver&, RenderStyle& style, Element*) const
1442 {
1443     float fontScale = style.fontSize() / baseFontSize;
1444
1445     style.resetPadding();
1446     style.setBorderRadius(IntSize(int(baseBorderRadius + fontScale - 1), int(baseBorderRadius + fontScale - 1))); // FIXME: Round up?
1447
1448     const int minHeight = 15;
1449     style.setMinHeight(Length(minHeight, Fixed));
1450
1451     style.setLineHeight(RenderStyle::initialLineHeight());
1452 }
1453
1454 void RenderThemeMac::setPopupButtonCellState(const RenderObject& o, const IntSize& buttonSize)
1455 {
1456     NSPopUpButtonCell* popupButton = this->popupButton();
1457
1458     // Set the control size based off the rectangle we're painting into.
1459     setControlSize(popupButton, popupButtonSizes(), buttonSize, o.style().effectiveZoom());
1460
1461     // Update the various states we respond to.
1462     updateCheckedState(popupButton, o);
1463     updateEnabledState(popupButton, o);
1464     updatePressedState(popupButton, o);
1465 }
1466
1467 const IntSize* RenderThemeMac::menuListSizes() const
1468 {
1469     static const IntSize sizes[3] = { IntSize(9, 0), IntSize(5, 0), IntSize(0, 0) };
1470     return sizes;
1471 }
1472
1473 int RenderThemeMac::minimumMenuListSize(RenderStyle& style) const
1474 {
1475     return sizeForSystemFont(style, menuListSizes()).width();
1476 }
1477
1478 const int trackWidth = 5;
1479 const int trackRadius = 2;
1480
1481 void RenderThemeMac::adjustSliderTrackStyle(StyleResolver&, RenderStyle& style, Element*) const
1482 {
1483     style.setBoxShadow(nullptr);
1484 }
1485
1486 bool RenderThemeMac::paintSliderTrack(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1487 {
1488     IntRect bounds = r;
1489     float zoomLevel = o.style().effectiveZoom();
1490     float zoomedTrackWidth = trackWidth * zoomLevel;
1491
1492     if (o.style().appearance() ==  SliderHorizontalPart || o.style().appearance() ==  MediaSliderPart) {
1493         bounds.setHeight(zoomedTrackWidth);
1494         bounds.setY(r.y() + r.height() / 2 - zoomedTrackWidth / 2);
1495     } else if (o.style().appearance() == SliderVerticalPart) {
1496         bounds.setWidth(zoomedTrackWidth);
1497         bounds.setX(r.x() + r.width() / 2 - zoomedTrackWidth / 2);
1498     }
1499
1500     LocalCurrentGraphicsContext localContext(paintInfo.context);
1501     CGContextRef context = localContext.cgContext();
1502     CGColorSpaceRef cspace = deviceRGBColorSpaceRef();
1503
1504 #if ENABLE(DATALIST_ELEMENT)
1505     paintSliderTicks(o, paintInfo, r);
1506 #endif
1507
1508     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1509     CGContextClipToRect(context, bounds);
1510
1511     struct CGFunctionCallbacks mainCallbacks = { 0, TrackGradientInterpolate, NULL };
1512     RetainPtr<CGFunctionRef> mainFunction = adoptCF(CGFunctionCreate(NULL, 1, NULL, 4, NULL, &mainCallbacks));
1513     RetainPtr<CGShadingRef> mainShading;
1514     if (o.style().appearance() == SliderVerticalPart)
1515         mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.maxY()), CGPointMake(bounds.maxX(), bounds.maxY()), mainFunction.get(), false, false));
1516     else
1517         mainShading = adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.y()), CGPointMake(bounds.x(), bounds.maxY()), mainFunction.get(), false, false));
1518
1519     IntSize radius(trackRadius, trackRadius);
1520     paintInfo.context->clipRoundedRect(FloatRoundedRect(bounds, radius, radius, radius, radius));
1521     context = localContext.cgContext();
1522     CGContextDrawShading(context, mainShading.get());
1523
1524     return false;
1525 }
1526
1527 void RenderThemeMac::adjustSliderThumbStyle(StyleResolver& styleResolver, RenderStyle& style, Element* element) const
1528 {
1529     RenderTheme::adjustSliderThumbStyle(styleResolver, style, element);
1530     style.setBoxShadow(nullptr);
1531 }
1532
1533 const float verticalSliderHeightPadding = 0.1f;
1534
1535 bool RenderThemeMac::paintSliderThumb(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1536 {
1537     NSSliderCell* sliderThumbCell = o.style().appearance() == SliderThumbVerticalPart
1538         ? sliderThumbVertical()
1539         : sliderThumbHorizontal();
1540
1541     LocalCurrentGraphicsContext localContext(paintInfo.context);
1542
1543     // Update the various states we respond to.
1544     updateEnabledState(sliderThumbCell, o);
1545         Element* focusDelegate = is<Element>(o.node()) ? downcast<Element>(*o.node()).focusDelegate() : nullptr;
1546     if (focusDelegate)
1547         updateFocusedState(sliderThumbCell, *focusDelegate->renderer());
1548
1549     // Update the pressed state using the NSCell tracking methods, since that's how NSSliderCell keeps track of it.
1550     bool oldPressed;
1551     if (o.style().appearance() == SliderThumbVerticalPart)
1552         oldPressed = m_isSliderThumbVerticalPressed;
1553     else
1554         oldPressed = m_isSliderThumbHorizontalPressed;
1555
1556     bool pressed = isPressed(o);
1557
1558     if (o.style().appearance() == SliderThumbVerticalPart)
1559         m_isSliderThumbVerticalPressed = pressed;
1560     else
1561         m_isSliderThumbHorizontalPressed = pressed;
1562
1563     NSView *view = documentViewFor(o);
1564
1565     if (pressed != oldPressed) {
1566         if (pressed)
1567             [sliderThumbCell startTrackingAt:NSPoint() inView:view];
1568         else
1569             [sliderThumbCell stopTracking:NSPoint() at:NSPoint() inView:view mouseIsUp:YES];
1570     }
1571
1572     FloatRect bounds = r;
1573     // Make the height of the vertical slider slightly larger so NSSliderCell will draw a vertical slider.
1574     if (o.style().appearance() == SliderThumbVerticalPart)
1575         bounds.setHeight(bounds.height() + verticalSliderHeightPadding * o.style().effectiveZoom());
1576
1577     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1578     float zoomLevel = o.style().effectiveZoom();
1579
1580     FloatRect unzoomedRect = bounds;
1581     if (zoomLevel != 1.0f) {
1582         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1583         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1584         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
1585         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
1586         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
1587     }
1588
1589     [sliderThumbCell drawKnob:unzoomedRect];
1590     [sliderThumbCell setControlView:nil];
1591
1592     return false;
1593 }
1594
1595 bool RenderThemeMac::paintSearchField(const RenderObject& o, const PaintInfo& paintInfo, const IntRect& r)
1596 {
1597     LocalCurrentGraphicsContext localContext(paintInfo.context);
1598     NSSearchFieldCell* search = this->search();
1599
1600     setSearchCellState(o, r);
1601
1602     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1603
1604     float zoomLevel = o.style().effectiveZoom();
1605
1606     IntRect unzoomedRect = r;
1607
1608     if (zoomLevel != 1.0f) {
1609         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
1610         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
1611         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
1612         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
1613         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
1614     }
1615
1616     // Set the search button to nil before drawing.  Then reset it so we can draw it later.
1617     [search setSearchButtonCell:nil];
1618
1619     NSView *documentView = documentViewFor(o);
1620     [search drawWithFrame:NSRect(unzoomedRect) inView:documentView];
1621
1622     [search setControlView:nil];
1623     [search resetSearchButtonCell];
1624
1625     if (isFocused(o) && o.style().outlineStyleIsAuto()) {
1626         if (wkDrawCellFocusRingWithFrameAtTime(search, NSRect(unzoomedRect), documentView, std::numeric_limits<double>::max()))
1627             o.document().page()->focusController().setFocusedElementNeedsRepaint();
1628     }
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(input->renderBox()->pixelSnappedBorderBoxRect())];
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(input->renderBox()->pixelSnappedBorderBoxRect())];
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(input->renderBox()->pixelSnappedBorderBoxRect())];
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->hasLayer() && renderBox->layer() && renderBox->layer()->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)