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