AR Badging on transparent thumbnail images makes the glyph look really dark
[WebKit-https.git] / Source / WebCore / rendering / RenderThemeIOS.mm
1 /*
2  * Copyright (C) 2005-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "RenderThemeIOS.h"
28
29 #if PLATFORM(IOS)
30
31 #import "BitmapImage.h"
32 #import "CSSPrimitiveValue.h"
33 #import "CSSToLengthConversionData.h"
34 #import "CSSValueKeywords.h"
35 #import "DateComponents.h"
36 #import "Document.h"
37 #import "File.h"
38 #import "FloatRoundedRect.h"
39 #import "FontCache.h"
40 #import "FontCascade.h"
41 #import "Frame.h"
42 #import "FrameSelection.h"
43 #import "FrameView.h"
44 #import "GeometryUtilities.h"
45 #import "Gradient.h"
46 #import "GraphicsContext.h"
47 #import "GraphicsContextCG.h"
48 #import "HTMLAttachmentElement.h"
49 #import "HTMLInputElement.h"
50 #import "HTMLNames.h"
51 #import "HTMLSelectElement.h"
52 #import "IOSurface.h"
53 #import "Icon.h"
54 #import "LocalizedDateCache.h"
55 #import "NodeRenderStyle.h"
56 #import "Page.h"
57 #import "PaintInfo.h"
58 #import "PathUtilities.h"
59 #import "PlatformLocale.h"
60 #import "RenderAttachment.h"
61 #import "RenderObject.h"
62 #import "RenderProgress.h"
63 #import "RenderStyle.h"
64 #import "RenderView.h"
65 #import "RuntimeEnabledFeatures.h"
66 #import "UTIUtilities.h"
67 #import "UserAgentScripts.h"
68 #import "UserAgentStyleSheets.h"
69 #import "WebCoreThreadRun.h"
70 #import <CoreGraphics/CoreGraphics.h>
71 #import <CoreImage/CoreImage.h>
72 #import <objc/runtime.h>
73 #import <pal/spi/cocoa/CoreTextSPI.h>
74 #import <pal/spi/ios/UIKitSPI.h>
75 #import <wtf/NeverDestroyed.h>
76 #import <wtf/RefPtr.h>
77 #import <wtf/SoftLinking.h>
78 #import <wtf/StdLibExtras.h>
79
80 #if USE(SYSTEM_PREVIEW) && USE(APPLE_INTERNAL_SDK)
81 #import <WebKitAdditions/SystemPreviewArtwork.cpp>
82 #endif
83
84 SOFT_LINK_FRAMEWORK(UIKit)
85 SOFT_LINK_CLASS(UIKit, UIApplication)
86 SOFT_LINK_CLASS(UIKit, UIColor)
87 SOFT_LINK_CLASS(UIKit, UIDocumentInteractionController)
88 SOFT_LINK_CLASS(UIKit, UIImage)
89 SOFT_LINK_CONSTANT(UIKit, UIContentSizeCategoryDidChangeNotification, CFStringRef)
90 #define UIContentSizeCategoryDidChangeNotification getUIContentSizeCategoryDidChangeNotification()
91
92 @interface WebCoreRenderThemeBundle : NSObject
93 @end
94
95 @implementation WebCoreRenderThemeBundle
96 @end
97
98 namespace WebCore {
99
100 using namespace HTMLNames;
101
102 const float ControlBaseHeight = 20;
103 const float ControlBaseFontSize = 11;
104
105 struct IOSGradient {
106     float* start; // points to static float[4]
107     float* end; // points to static float[4]
108     IOSGradient(float start[4], float end[4])
109         : start(start)
110         , end(end)
111     {
112     }
113 };
114
115 typedef IOSGradient* IOSGradientRef;
116
117 enum Interpolation
118 {
119     LinearInterpolation,
120     ExponentialInterpolation
121 };
122
123 static void interpolateLinearGradient(void *info, const CGFloat *inData, CGFloat *outData)
124 {
125     IOSGradientRef gradient = static_cast<IOSGradientRef>(info);
126     float alpha = inData[0];
127     float inverse = 1.0f - alpha;
128
129     outData[0] = inverse * gradient->start[0] + alpha * gradient->end[0];
130     outData[1] = inverse * gradient->start[1] + alpha * gradient->end[1];
131     outData[2] = inverse * gradient->start[2] + alpha * gradient->end[2];
132     outData[3] = inverse * gradient->start[3] + alpha * gradient->end[3];
133 }
134
135 static void interpolateExponentialGradient(void *info, const CGFloat *inData, CGFloat *outData)
136 {
137     IOSGradientRef gradient = static_cast<IOSGradientRef>(info);
138     float a = inData[0];
139     for (int paintInfo = 0; paintInfo < 4; ++paintInfo) {
140         float end = logf(std::max(gradient->end[paintInfo], 0.01f));
141         float start = logf(std::max(gradient->start[paintInfo], 0.01f));
142         outData[paintInfo] = expf(start - (end + start) * a);
143     }
144 }
145
146 static CGFunctionRef getSharedFunctionRef(IOSGradientRef gradient, Interpolation interpolation)
147 {
148     CGFunctionRef function = nullptr;
149
150     static HashMap<IOSGradientRef, CGFunctionRef>* linearFunctionRefs;
151     static HashMap<IOSGradientRef, CGFunctionRef>* exponentialFunctionRefs;
152
153     if (interpolation == LinearInterpolation) {
154         if (!linearFunctionRefs)
155             linearFunctionRefs = new HashMap<IOSGradientRef, CGFunctionRef>;
156         else
157             function = linearFunctionRefs->get(gradient);
158     
159         if (!function) {
160             static struct CGFunctionCallbacks linearFunctionCallbacks =  { 0, interpolateLinearGradient, 0 };
161             linearFunctionRefs->set(gradient, function = CGFunctionCreate(gradient, 1, nullptr, 4, nullptr, &linearFunctionCallbacks));
162         }
163
164         return function;
165     }
166
167     if (!exponentialFunctionRefs)
168         exponentialFunctionRefs = new HashMap<IOSGradientRef, CGFunctionRef>;
169     else
170         function = exponentialFunctionRefs->get(gradient);
171
172     if (!function) {
173         static struct CGFunctionCallbacks exponentialFunctionCallbacks =  { 0, interpolateExponentialGradient, 0 };
174         exponentialFunctionRefs->set(gradient, function = CGFunctionCreate(gradient, 1, 0, 4, 0, &exponentialFunctionCallbacks));
175     }
176
177     return function;
178 }
179
180 static void drawAxialGradient(CGContextRef context, IOSGradientRef gradient, const FloatPoint& startPoint, const FloatPoint& stopPoint, Interpolation interpolation)
181 {
182     RetainPtr<CGShadingRef> shading = adoptCF(CGShadingCreateAxial(sRGBColorSpaceRef(), startPoint, stopPoint, getSharedFunctionRef(gradient, interpolation), false, false));
183     CGContextDrawShading(context, shading.get());
184 }
185
186 static void drawRadialGradient(CGContextRef context, IOSGradientRef gradient, const FloatPoint& startPoint, float startRadius, const FloatPoint& stopPoint, float stopRadius, Interpolation interpolation)
187 {
188     RetainPtr<CGShadingRef> shading = adoptCF(CGShadingCreateRadial(sRGBColorSpaceRef(), startPoint, startRadius, stopPoint, stopRadius, getSharedFunctionRef(gradient, interpolation), false, false));
189     CGContextDrawShading(context, shading.get());
190 }
191
192 enum IOSGradientType {
193     InsetGradient,
194     ShineGradient,
195     ShadeGradient,
196     ConvexGradient,
197     ConcaveGradient,
198     SliderTrackGradient,
199     ReadonlySliderTrackGradient,
200     SliderThumbOpaquePressedGradient,
201 };
202
203 static IOSGradientRef getInsetGradient()
204 {
205     static float end[4] = { 0 / 255.0, 0 / 255.0, 0 / 255.0, 0 };
206     static float start[4] = { 0 / 255.0, 0 / 255.0, 0 / 255.0, 0.2 };
207     static NeverDestroyed<IOSGradient> gradient(start, end);
208     return &gradient.get();
209 }
210
211 static IOSGradientRef getShineGradient()
212 {
213     static float end[4] = { 1, 1, 1, 0.8 };
214     static float start[4] = { 1, 1, 1, 0 };
215     static NeverDestroyed<IOSGradient> gradient(start, end);
216     return &gradient.get();
217 }
218
219 static IOSGradientRef getShadeGradient()
220 {
221     static float end[4] = { 178 / 255.0, 178 / 255.0, 178 / 255.0, 0.65 };
222     static float start[4] = { 252 / 255.0, 252 / 255.0, 252 / 255.0, 0.65 };
223     static NeverDestroyed<IOSGradient> gradient(start, end);
224     return &gradient.get();
225 }
226
227 static IOSGradientRef getConvexGradient()
228 {
229     static float end[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.05 };
230     static float start[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.43 };
231     static NeverDestroyed<IOSGradient> gradient(start, end);
232     return &gradient.get();
233 }
234
235 static IOSGradientRef getConcaveGradient()
236 {
237     static float end[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.46 };
238     static float start[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0 };
239     static NeverDestroyed<IOSGradient> gradient(start, end);
240     return &gradient.get();
241 }
242
243 static IOSGradientRef getSliderTrackGradient()
244 {
245     static float end[4] = { 132 / 255.0, 132 / 255.0, 132 / 255.0, 1 };
246     static float start[4] = { 74 / 255.0, 77 / 255.0, 80 / 255.0, 1 };
247     static NeverDestroyed<IOSGradient> gradient(start, end);
248     return &gradient.get();
249 }
250
251 static IOSGradientRef getReadonlySliderTrackGradient()
252 {
253     static float end[4] = { 132 / 255.0, 132 / 255.0, 132 / 255.0, 0.4 };
254     static float start[4] = { 74 / 255.0, 77 / 255.0, 80 /255.0, 0.4 };
255     static NeverDestroyed<IOSGradient> gradient(start, end);
256     return &gradient.get();
257 }
258
259 static IOSGradientRef getSliderThumbOpaquePressedGradient()
260 {
261     static float end[4] = { 144 / 255.0, 144 / 255.0, 144 / 255.0, 1};
262     static float start[4] = { 55 / 255.0, 55 / 255.0, 55 / 255.0, 1 };
263     static NeverDestroyed<IOSGradient> gradient(start, end);
264     return &gradient.get();
265 }
266
267 static IOSGradientRef gradientWithName(IOSGradientType gradientType)
268 {
269     switch (gradientType) {
270     case InsetGradient:
271         return getInsetGradient();
272     case ShineGradient:
273         return getShineGradient();
274     case ShadeGradient:
275         return getShadeGradient();
276     case ConvexGradient:
277         return getConvexGradient();
278     case ConcaveGradient:
279         return getConcaveGradient();
280     case SliderTrackGradient:
281         return getSliderTrackGradient();
282     case ReadonlySliderTrackGradient:
283         return getReadonlySliderTrackGradient();
284     case SliderThumbOpaquePressedGradient:
285         return getSliderThumbOpaquePressedGradient();
286     }
287     ASSERT_NOT_REACHED();
288     return nullptr;
289 }
290
291 static void contentSizeCategoryDidChange(CFNotificationCenterRef, void*, CFStringRef name, const void*, CFDictionaryRef)
292 {
293     ASSERT_UNUSED(name, CFEqual(name, UIContentSizeCategoryDidChangeNotification));
294     WebThreadRun(^{
295         Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment();
296     });
297 }
298
299 RenderThemeIOS::RenderThemeIOS()
300 {
301     CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), this, contentSizeCategoryDidChange, UIContentSizeCategoryDidChangeNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
302 }
303
304 RenderTheme& RenderTheme::singleton()
305 {
306     static NeverDestroyed<RenderThemeIOS> theme;
307     return theme;
308 }
309
310 static String& _contentSizeCategory()
311 {
312     static NeverDestroyed<String> _contentSizeCategory;
313     return _contentSizeCategory.get();
314 }
315
316 CFStringRef RenderThemeIOS::contentSizeCategory()
317 {
318     if (!_contentSizeCategory().isNull())
319         return (__bridge CFStringRef)static_cast<NSString*>(_contentSizeCategory());
320     return (CFStringRef)[[getUIApplicationClass() sharedApplication] preferredContentSizeCategory];
321 }
322
323 void RenderThemeIOS::setContentSizeCategory(const String& contentSizeCategory)
324 {
325     _contentSizeCategory() = contentSizeCategory;
326 }
327
328 const Color& RenderThemeIOS::shadowColor() const
329 {
330     static NeverDestroyed<Color> color(0.0f, 0.0f, 0.0f, 0.7f);
331     return color;
332 }
333
334 FloatRect RenderThemeIOS::addRoundedBorderClip(const RenderObject& box, GraphicsContext& context, const IntRect& rect)
335 {
336     // To fix inner border bleeding issues <rdar://problem/9812507>, we clip to the outer border and assert that
337     // the border is opaque or transparent, unless we're checked because checked radio/checkboxes show no bleeding.
338     auto& style = box.style();
339     RoundedRect border = isChecked(box) ? style.getRoundedInnerBorderFor(rect) : style.getRoundedBorderFor(rect);
340
341     if (border.isRounded())
342         context.clipRoundedRect(FloatRoundedRect(border));
343     else
344         context.clip(border.rect());
345
346     if (isChecked(box)) {
347         ASSERT(style.visitedDependentColor(CSSPropertyBorderTopColor).alpha() % 255 == 0);
348         ASSERT(style.visitedDependentColor(CSSPropertyBorderRightColor).alpha() % 255 == 0);
349         ASSERT(style.visitedDependentColor(CSSPropertyBorderBottomColor).alpha() % 255 == 0);
350         ASSERT(style.visitedDependentColor(CSSPropertyBorderLeftColor).alpha() % 255 == 0);
351     }
352
353     return border.rect();
354 }
355
356 void RenderThemeIOS::adjustCheckboxStyle(StyleResolver&, RenderStyle& style, const Element*) const
357 {
358     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
359         return;
360
361     int size = std::max(style.computedFontPixelSize(), 10U);
362     style.setWidth({ size, Fixed });
363     style.setHeight({ size, Fixed });
364 }
365
366 static CGPoint shortened(CGPoint start, CGPoint end, float width)
367 {
368     float x = end.x - start.x;
369     float y = end.y - start.y;
370     float ratio = (!x && !y) ? 0 : width / sqrtf(x * x + y * y);
371     return CGPointMake(start.x + x * ratio, start.y + y * ratio);
372 }
373
374 static void drawJoinedLines(CGContextRef context, CGPoint points[], unsigned count, bool antialias, CGLineCap lineCap)
375 {
376     CGContextSetShouldAntialias(context, antialias);
377     CGContextBeginPath(context);
378     CGContextSetLineCap(context, lineCap);
379     CGContextMoveToPoint(context, points[0].x, points[0].y);
380     
381     for (unsigned i = 1; i < count; ++i)
382         CGContextAddLineToPoint(context, points[i].x, points[i].y);
383
384     CGContextStrokePath(context);
385 }
386
387 bool RenderThemeIOS::paintCheckboxDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
388 {
389     GraphicsContextStateSaver stateSaver(paintInfo.context());
390     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
391
392     float width = clip.width();
393     float height = clip.height();
394
395     CGContextRef cgContext = paintInfo.context().platformContext();
396     if (isChecked(box)) {
397         drawAxialGradient(cgContext, gradientWithName(ConcaveGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
398
399         static const float thicknessRatio = 2 / 14.0;
400         static const CGSize size = { 14.0f, 14.0f };
401         static const CGPoint pathRatios[3] = {
402             { 2.5f / size.width, 7.5f / size.height },
403             { 5.5f / size.width, 10.5f / size.height },
404             { 11.5f / size.width, 2.5f / size.height }
405         };
406
407         float lineWidth = std::min(width, height) * 2.0f * thicknessRatio;
408
409         CGPoint line[3] = {
410             CGPointMake(clip.x() + width * pathRatios[0].x, clip.y() + height * pathRatios[0].y),
411             CGPointMake(clip.x() + width * pathRatios[1].x, clip.y() + height * pathRatios[1].y),
412             CGPointMake(clip.x() + width * pathRatios[2].x, clip.y() + height * pathRatios[2].y)
413         };
414         CGPoint shadow[3] = {
415             shortened(line[0], line[1], lineWidth / 4.0f),
416             line[1],
417             shortened(line[2], line[1], lineWidth / 4.0f)
418         };
419
420         lineWidth = std::max<float>(lineWidth, 1);
421         CGContextSetLineWidth(cgContext, lineWidth);
422         CGContextSetStrokeColorWithColor(cgContext, cachedCGColor(Color(0.0f, 0.0f, 0.0f, 0.7f)));
423         drawJoinedLines(cgContext, shadow, 3, true, kCGLineCapSquare);
424
425         lineWidth = std::max<float>(std::min(clip.width(), clip.height()) * thicknessRatio, 1);
426         CGContextSetLineWidth(cgContext, lineWidth);
427         CGContextSetStrokeColorWithColor(cgContext, cachedCGColor(Color(1.0f, 1.0f, 1.0f, 240 / 255.0f)));
428         drawJoinedLines(cgContext, line, 3, true, kCGLineCapButt);
429     } else {
430         FloatPoint bottomCenter(clip.x() + clip.width() / 2.0f, clip.maxY());
431         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
432         drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0, bottomCenter, sqrtf((width * width) / 4.0f + height * height), ExponentialInterpolation);
433     }
434
435     return false;
436 }
437
438 int RenderThemeIOS::baselinePosition(const RenderBox& box) const
439 {
440     if (box.style().appearance() == CheckboxPart || box.style().appearance() == RadioPart)
441         return box.marginTop() + box.height() - 2; // The baseline is 2px up from the bottom of the checkbox/radio in AppKit.
442     if (box.style().appearance() == MenulistPart)
443         return box.marginTop() + box.height() - 5; // This is to match AppKit. There might be a better way to calculate this though.
444     return RenderTheme::baselinePosition(box);
445 }
446
447 bool RenderThemeIOS::isControlStyled(const RenderStyle& style, const BorderData& border, const FillLayer& background, const Color& backgroundColor) const
448 {
449     // Buttons and MenulistButtons are styled if they contain a background image.
450     if (style.appearance() == PushButtonPart || style.appearance() == MenulistButtonPart)
451         return !style.visitedDependentColor(CSSPropertyBackgroundColor).isVisible() || style.backgroundLayers().hasImage();
452
453     if (style.appearance() == TextFieldPart || style.appearance() == TextAreaPart)
454         return style.backgroundLayers() != background;
455
456     return RenderTheme::isControlStyled(style, border, background, backgroundColor);
457 }
458
459 void RenderThemeIOS::adjustRadioStyle(StyleResolver&, RenderStyle& style, const Element*) const
460 {
461     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
462         return;
463
464     int size = std::max(style.computedFontPixelSize(), 10U);
465     style.setWidth({ size, Fixed });
466     style.setHeight({ size, Fixed });
467     style.setBorderRadius({ size / 2, size / 2 });
468 }
469
470 bool RenderThemeIOS::paintRadioDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
471 {
472     GraphicsContextStateSaver stateSaver(paintInfo.context());
473     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
474
475     CGContextRef cgContext = paintInfo.context().platformContext();
476     if (isChecked(box)) {
477         drawAxialGradient(cgContext, gradientWithName(ConcaveGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
478
479         // The inner circle is 6 / 14 the size of the surrounding circle, 
480         // leaving 8 / 14 around it. (8 / 14) / 2 = 2 / 7.
481
482         static const float InnerInverseRatio = 2 / 7.0;
483
484         clip.inflateX(-clip.width() * InnerInverseRatio);
485         clip.inflateY(-clip.height() * InnerInverseRatio);
486
487         paintInfo.context().drawRaisedEllipse(clip, Color::white, shadowColor());
488
489         FloatSize radius(clip.width() / 2.0f, clip.height() / 2.0f);
490         paintInfo.context().clipRoundedRect(FloatRoundedRect(clip, radius, radius, radius, radius));
491     }
492     FloatPoint bottomCenter(clip.x() + clip.width() / 2.0, clip.maxY());
493     drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
494     drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0, bottomCenter, std::max(clip.width(), clip.height()), ExponentialInterpolation);
495     return false;
496 }
497
498 bool RenderThemeIOS::paintTextFieldDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
499 {
500     auto& style = box.style();
501     FloatPoint point(rect.x() + style.borderLeftWidth(), rect.y() + style.borderTopWidth());
502
503     GraphicsContextStateSaver stateSaver(paintInfo.context());
504
505     paintInfo.context().clipRoundedRect(style.getRoundedBorderFor(LayoutRect(rect)).pixelSnappedRoundedRectForPainting(box.document().deviceScaleFactor()));
506
507     // This gradient gets drawn black when printing.
508     // Do not draw the gradient if there is no visible top border.
509     bool topBorderIsInvisible = !style.hasBorder() || !style.borderTopWidth() || style.borderTopIsTransparent();
510     if (!box.view().printing() && !topBorderIsInvisible)
511         drawAxialGradient(paintInfo.context().platformContext(), gradientWithName(InsetGradient), point, FloatPoint(CGPointMake(point.x(), point.y() + 3.0f)), LinearInterpolation);
512     return false;
513 }
514
515 bool RenderThemeIOS::paintTextAreaDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
516 {
517     return paintTextFieldDecorations(box, paintInfo, rect);
518 }
519
520 const int MenuListMinHeight = 15;
521
522 const float MenuListBaseHeight = 20;
523 const float MenuListBaseFontSize = 11;
524
525 const float MenuListArrowWidth = 7;
526 const float MenuListArrowHeight = 6;
527 const float MenuListButtonPaddingAfter = 19;
528
529 LengthBox RenderThemeIOS::popupInternalPaddingBox(const RenderStyle& style) const
530 {
531     if (style.appearance() == MenulistButtonPart) {
532         if (style.direction() == RTL)
533             return { 0, 0, 0, static_cast<int>(MenuListButtonPaddingAfter + style.borderTopWidth()) };
534         return { 0, static_cast<int>(MenuListButtonPaddingAfter + style.borderTopWidth()), 0, 0 };
535     }
536     return { 0, 0, 0, 0 };
537 }
538
539 void RenderThemeIOS::adjustRoundBorderRadius(RenderStyle& style, RenderBox& box)
540 {
541     if (style.appearance() == NoControlPart || style.backgroundLayers().hasImage())
542         return;
543
544     // FIXME: We should not be relying on border radius for the appearance of our controls <rdar://problem/7675493>.
545     style.setBorderRadius({ { std::min(box.width(), box.height()) / 2, Fixed }, { box.height() / 2, Fixed } });
546 }
547
548 static void applyCommonButtonPaddingToStyle(RenderStyle& style, const Element& element)
549 {
550     Document& document = element.document();
551     RefPtr<CSSPrimitiveValue> emSize = CSSPrimitiveValue::create(0.5, CSSPrimitiveValue::CSS_EMS);
552     int pixels = emSize->computeLength<int>(CSSToLengthConversionData(&style, document.renderStyle(), document.renderView(), document.frame()->pageZoomFactor()));
553     style.setPaddingBox(LengthBox(0, pixels, 0, pixels));
554 }
555
556 static void adjustSelectListButtonStyle(RenderStyle& style, const Element& element)
557 {
558     // Enforce "padding: 0 0.5em".
559     applyCommonButtonPaddingToStyle(style, element);
560
561     // Enforce "line-height: normal".
562     style.setLineHeight(Length(-100.0, Percent));
563 }
564     
565 class RenderThemeMeasureTextClient : public MeasureTextClient {
566 public:
567     RenderThemeMeasureTextClient(const FontCascade& font, const RenderStyle& style)
568         : m_font(font)
569         , m_style(style)
570     {
571     }
572     float measureText(const String& string) const override
573     {
574         TextRun run = RenderBlock::constructTextRun(string, m_style);
575         return m_font.width(run);
576     }
577 private:
578     const FontCascade& m_font;
579     const RenderStyle& m_style;
580 };
581
582 static void adjustInputElementButtonStyle(RenderStyle& style, const HTMLInputElement& inputElement)
583 {
584     // Always Enforce "padding: 0 0.5em".
585     applyCommonButtonPaddingToStyle(style, inputElement);
586
587     // Don't adjust the style if the width is specified.
588     if (style.width().isFixed() && style.width().value() > 0)
589         return;
590
591     // Don't adjust for unsupported date input types.
592     DateComponents::Type dateType = inputElement.dateType();
593     if (dateType == DateComponents::Invalid || dateType == DateComponents::Week)
594         return;
595
596     // Enforce the width and set the box-sizing to content-box to not conflict with the padding.
597     FontCascade font = style.fontCascade();
598     
599     float maximumWidth = localizedDateCache().maximumWidthForDateType(dateType, font, RenderThemeMeasureTextClient(font, style));
600
601     ASSERT(maximumWidth >= 0);
602
603     if (maximumWidth > 0) {
604         int width = static_cast<int>(maximumWidth + MenuListButtonPaddingAfter);
605         style.setWidth(Length(width, Fixed));
606         style.setBoxSizing(BoxSizing::ContentBox);
607     }
608 }
609
610 void RenderThemeIOS::adjustMenuListButtonStyle(StyleResolver&, RenderStyle& style, const Element* element) const
611 {
612     // Set the min-height to be at least MenuListMinHeight.
613     if (style.height().isAuto())
614         style.setMinHeight(Length(std::max(MenuListMinHeight, static_cast<int>(MenuListBaseHeight / MenuListBaseFontSize * style.fontDescription().computedSize())), Fixed));
615     else
616         style.setMinHeight(Length(MenuListMinHeight, Fixed));
617
618     if (!element)
619         return;
620
621     // Enforce some default styles in the case that this is a non-multiple <select> element,
622     // or a date input. We don't force these if this is just an element with
623     // "-webkit-appearance: menulist-button".
624     if (is<HTMLSelectElement>(*element) && !element->hasAttributeWithoutSynchronization(HTMLNames::multipleAttr))
625         adjustSelectListButtonStyle(style, *element);
626     else if (is<HTMLInputElement>(*element))
627         adjustInputElementButtonStyle(style, downcast<HTMLInputElement>(*element));
628 }
629
630 bool RenderThemeIOS::paintMenuListButtonDecorations(const RenderBox& box, const PaintInfo& paintInfo, const FloatRect& rect)
631 {
632     auto& style = box.style();
633     bool isRTL = style.direction() == RTL;
634     float borderTopWidth = style.borderTopWidth();
635     FloatRect clip(rect.x() + style.borderLeftWidth(), rect.y() + style.borderTopWidth(), rect.width() - style.borderLeftWidth() - style.borderRightWidth(), rect.height() - style.borderTopWidth() - style.borderBottomWidth());
636     CGContextRef cgContext = paintInfo.context().platformContext();
637
638     float adjustLeft = 0.5;
639     float adjustRight = 0.5;
640     float adjustTop = 0.5;
641     float adjustBottom = 0.5;
642
643     // Paint title portion.
644     {
645         float leftInset = isRTL ? MenuListButtonPaddingAfter : 0;
646         FloatRect titleClip(clip.x() + leftInset - adjustLeft, clip.y() - adjustTop, clip.width() - MenuListButtonPaddingAfter + adjustLeft, clip.height() + adjustTop + adjustBottom);
647
648         GraphicsContextStateSaver stateSaver(paintInfo.context());
649
650         FloatSize topLeftRadius;
651         FloatSize topRightRadius;
652         FloatSize bottomLeftRadius;
653         FloatSize bottomRightRadius;
654
655         if (isRTL) {
656             topRightRadius = FloatSize(valueForLength(style.borderTopRightRadius().width, rect.width()) - style.borderRightWidth(), valueForLength(style.borderTopRightRadius().height, rect.height()) - style.borderTopWidth());
657             bottomRightRadius = FloatSize(valueForLength(style.borderBottomRightRadius().width, rect.width()) - style.borderRightWidth(), valueForLength(style.borderBottomRightRadius().height, rect.height()) - style.borderBottomWidth());
658         } else {
659             topLeftRadius = FloatSize(valueForLength(style.borderTopLeftRadius().width, rect.width()) - style.borderLeftWidth(), valueForLength(style.borderTopLeftRadius().height, rect.height()) - style.borderTopWidth());
660             bottomLeftRadius = FloatSize(valueForLength(style.borderBottomLeftRadius().width, rect.width()) - style.borderLeftWidth(), valueForLength(style.borderBottomLeftRadius().height, rect.height()) - style.borderBottomWidth());
661         }
662
663         paintInfo.context().clipRoundedRect(FloatRoundedRect(titleClip,
664             topLeftRadius, topRightRadius,
665             bottomLeftRadius, bottomRightRadius));
666
667         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), titleClip.location(), FloatPoint(titleClip.x(), titleClip.maxY()), LinearInterpolation);
668         drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(titleClip.x(), titleClip.maxY()), titleClip.location(), ExponentialInterpolation);
669     }
670
671     // Draw the separator after the initial padding.
672
673     float separatorPosition = isRTL ? (clip.x() + MenuListButtonPaddingAfter) : (clip.maxX() - MenuListButtonPaddingAfter);
674
675     box.drawLineForBoxSide(paintInfo.context(), FloatRect(FloatPoint(separatorPosition - borderTopWidth, clip.y()), FloatPoint(separatorPosition, clip.maxY())), BSRight, style.visitedDependentColor(CSSPropertyBorderTopColor), style.borderTopStyle(), 0, 0);
676
677     FloatRect buttonClip;
678     if (isRTL)
679         buttonClip = FloatRect(clip.x() - adjustTop, clip.y() - adjustTop, MenuListButtonPaddingAfter + adjustTop + adjustLeft, clip.height() + adjustTop + adjustBottom);
680     else
681         buttonClip = FloatRect(separatorPosition - adjustTop, clip.y() - adjustTop, MenuListButtonPaddingAfter + adjustTop + adjustRight, clip.height() + adjustTop + adjustBottom);
682
683     // Now paint the button portion.
684     {
685         GraphicsContextStateSaver stateSaver(paintInfo.context());
686
687         FloatSize topLeftRadius;
688         FloatSize topRightRadius;
689         FloatSize bottomLeftRadius;
690         FloatSize bottomRightRadius;
691
692         if (isRTL) {
693             topLeftRadius = FloatSize(valueForLength(style.borderTopLeftRadius().width, rect.width()) - style.borderLeftWidth(), valueForLength(style.borderTopLeftRadius().height, rect.height()) - style.borderTopWidth());
694             bottomLeftRadius = FloatSize(valueForLength(style.borderBottomLeftRadius().width, rect.width()) - style.borderLeftWidth(), valueForLength(style.borderBottomLeftRadius().height, rect.height()) - style.borderBottomWidth());
695         } else {
696             topRightRadius = FloatSize(valueForLength(style.borderTopRightRadius().width, rect.width()) - style.borderRightWidth(), valueForLength(style.borderTopRightRadius().height, rect.height()) - style.borderTopWidth());
697             bottomRightRadius = FloatSize(valueForLength(style.borderBottomRightRadius().width, rect.width()) - style.borderRightWidth(), valueForLength(style.borderBottomRightRadius().height, rect.height()) - style.borderBottomWidth());
698         }
699
700         paintInfo.context().clipRoundedRect(FloatRoundedRect(buttonClip,
701             topLeftRadius, topRightRadius,
702             bottomLeftRadius, bottomRightRadius));
703
704         paintInfo.context().fillRect(buttonClip, style.visitedDependentColor(CSSPropertyBorderTopColor));
705
706         drawAxialGradient(cgContext, gradientWithName(isFocused(box) && !isReadOnlyControl(box) ? ConcaveGradient : ConvexGradient), buttonClip.location(), FloatPoint(buttonClip.x(), buttonClip.maxY()), LinearInterpolation);
707     }
708
709     // Paint Indicators.
710
711     if (box.isMenuList() && downcast<HTMLSelectElement>(box.element())->multiple()) {
712         int size = 2;
713         int count = 3;
714         int padding = 3;
715
716         FloatRect ellipse(buttonClip.x() + (buttonClip.width() - count * (size + padding) + padding) / 2.0, buttonClip.maxY() - 10.0, size, size);
717
718         for (int i = 0; i < count; ++i) {
719             paintInfo.context().drawRaisedEllipse(ellipse, Color::white, Color(0.0f, 0.0f, 0.0f, 0.5f));
720             ellipse.move(size + padding, 0);
721         }
722     }  else {
723         float centerX = floorf(buttonClip.x() + buttonClip.width() / 2.0) - 0.5;
724         float centerY = floorf(buttonClip.y() + buttonClip.height() * 3.0 / 8.0);
725
726         Vector<FloatPoint> arrow = {
727             { centerX - MenuListArrowWidth / 2, centerY },
728             { centerX + MenuListArrowWidth / 2, centerY },
729             { centerX, centerY + MenuListArrowHeight }
730         };
731
732         Vector<FloatPoint> shadow = {
733             { arrow[0].x(), arrow[0].y() + 1 },
734             { arrow[1].x(), arrow[1].y() + 1 },
735             { arrow[2].x(), arrow[2].y() + 1 }
736         };
737
738         float opacity = isReadOnlyControl(box) ? 0.2 : 0.5;
739         paintInfo.context().setStrokeColor(Color(0.0f, 0.0f, 0.0f, opacity));
740         paintInfo.context().setFillColor(Color(0.0f, 0.0f, 0.0f, opacity));
741         paintInfo.context().drawPath(Path::polygonPathFromPoints(shadow));
742
743         paintInfo.context().setStrokeColor(Color::white);
744         paintInfo.context().setFillColor(Color::white);
745         paintInfo.context().drawPath(Path::polygonPathFromPoints(arrow));
746     }
747
748     return false;
749 }
750
751 const CGFloat kTrackThickness = 4.0;
752 const CGFloat kTrackRadius = kTrackThickness / 2.0;
753 const int kDefaultSliderThumbSize = 16;
754
755 void RenderThemeIOS::adjustSliderTrackStyle(StyleResolver& selector, RenderStyle& style, const Element* element) const
756 {
757     RenderTheme::adjustSliderTrackStyle(selector, style, element);
758
759     // FIXME: We should not be relying on border radius for the appearance of our controls <rdar://problem/7675493>.
760     int radius = static_cast<int>(kTrackRadius);
761     style.setBorderRadius({ { radius, Fixed }, { radius, Fixed } });
762 }
763
764 bool RenderThemeIOS::paintSliderTrack(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
765 {
766     IntRect trackClip = rect;
767     auto& style = box.style();
768
769     bool isHorizontal = true;
770     switch (style.appearance()) {
771     case SliderHorizontalPart:
772         isHorizontal = true;
773         // Inset slightly so the thumb covers the edge.
774         if (trackClip.width() > 2) {
775             trackClip.setWidth(trackClip.width() - 2);
776             trackClip.setX(trackClip.x() + 1);
777         }
778         trackClip.setHeight(static_cast<int>(kTrackThickness));
779         trackClip.setY(rect.y() + rect.height() / 2 - kTrackThickness / 2);
780         break;
781     case SliderVerticalPart:
782         isHorizontal = false;
783         // Inset slightly so the thumb covers the edge.
784         if (trackClip.height() > 2) {
785             trackClip.setHeight(trackClip.height() - 2);
786             trackClip.setY(trackClip.y() + 1);
787         }
788         trackClip.setWidth(kTrackThickness);
789         trackClip.setX(rect.x() + rect.width() / 2 - kTrackThickness / 2);
790         break;
791     default:
792         ASSERT_NOT_REACHED();
793     }
794
795     ASSERT(trackClip.width() >= 0);
796     ASSERT(trackClip.height() >= 0);
797     CGFloat cornerWidth = trackClip.width() < kTrackThickness ? trackClip.width() / 2.0f : kTrackRadius;
798     CGFloat cornerHeight = trackClip.height() < kTrackThickness ? trackClip.height() / 2.0f : kTrackRadius;
799
800     bool readonly = isReadOnlyControl(box);
801
802 #if ENABLE(DATALIST_ELEMENT)
803     paintSliderTicks(box, paintInfo, trackClip);
804 #endif
805
806     // Draw the track gradient.
807     {
808         GraphicsContextStateSaver stateSaver(paintInfo.context());
809
810         IntSize cornerSize(cornerWidth, cornerHeight);
811         FloatRoundedRect innerBorder(trackClip, cornerSize, cornerSize, cornerSize, cornerSize);
812         paintInfo.context().clipRoundedRect(innerBorder);
813
814         CGContextRef cgContext = paintInfo.context().platformContext();
815         IOSGradientRef gradient = readonly ? gradientWithName(ReadonlySliderTrackGradient) : gradientWithName(SliderTrackGradient);
816         if (isHorizontal)
817             drawAxialGradient(cgContext, gradient, trackClip.location(), FloatPoint(trackClip.x(), trackClip.maxY()), LinearInterpolation);
818         else
819             drawAxialGradient(cgContext, gradient, trackClip.location(), FloatPoint(trackClip.maxX(), trackClip.y()), LinearInterpolation);
820     }
821
822     // Draw the track border.
823     {
824         GraphicsContextStateSaver stateSaver(paintInfo.context());
825
826         CGContextRef cgContext = paintInfo.context().platformContext();
827         if (readonly)
828             paintInfo.context().setStrokeColor(Color(178, 178, 178));
829         else
830             paintInfo.context().setStrokeColor(Color(76, 76, 76));
831
832         RetainPtr<CGMutablePathRef> roundedRectPath = adoptCF(CGPathCreateMutable());
833         CGPathAddRoundedRect(roundedRectPath.get(), 0, trackClip, cornerWidth, cornerHeight);
834         CGContextAddPath(cgContext, roundedRectPath.get());
835         CGContextSetLineWidth(cgContext, 1);
836         CGContextStrokePath(cgContext);
837     }
838
839     return false;
840 }
841
842 void RenderThemeIOS::adjustSliderThumbSize(RenderStyle& style, const Element*) const
843 {
844     if (style.appearance() != SliderThumbHorizontalPart && style.appearance() != SliderThumbVerticalPart)
845         return;
846
847     // Enforce "border-radius: 50%".
848     style.setBorderRadius({ { 50, Percent }, { 50, Percent } });
849
850     // Enforce a 16x16 size if no size is provided.
851     if (style.width().isIntrinsicOrAuto() || style.height().isAuto()) {
852         style.setWidth({ kDefaultSliderThumbSize, Fixed });
853         style.setHeight({ kDefaultSliderThumbSize, Fixed });
854     }
855 }
856
857 bool RenderThemeIOS::paintSliderThumbDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
858 {
859     GraphicsContextStateSaver stateSaver(paintInfo.context());
860     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
861
862     CGContextRef cgContext = paintInfo.context().platformContext();
863     FloatPoint bottomCenter(clip.x() + clip.width() / 2.0f, clip.maxY());
864     if (isPressed(box))
865         drawAxialGradient(cgContext, gradientWithName(SliderThumbOpaquePressedGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
866     else {
867         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
868         drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0.0f, bottomCenter, std::max(clip.width(), clip.height()), ExponentialInterpolation);
869     }
870
871     return false;
872 }
873
874 Seconds RenderThemeIOS::animationRepeatIntervalForProgressBar(RenderProgress&) const
875 {
876     return 0_s;
877 }
878
879 Seconds RenderThemeIOS::animationDurationForProgressBar(RenderProgress&) const
880 {
881     return 0_s;
882 }
883
884 bool RenderThemeIOS::paintProgressBar(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& rect)
885 {
886     if (!is<RenderProgress>(renderer))
887         return true;
888
889     const int progressBarHeight = 9;
890     const float verticalOffset = (rect.height() - progressBarHeight) / 2.0;
891
892     GraphicsContextStateSaver stateSaver(paintInfo.context());
893     if (rect.width() < 10 || rect.height() < 9) {
894         // The rect is smaller than the standard progress bar. We clip to the element's rect to avoid
895         // leaking pixels outside the repaint rect.
896         paintInfo.context().clip(rect);
897     }
898
899     // 1) Draw the progress bar track.
900     // 1.1) Draw the white background with grey gradient border.
901     GraphicsContext& context = paintInfo.context();
902     context.setStrokeThickness(0.68);
903     context.setStrokeStyle(SolidStroke);
904
905     const float verticalRenderingPosition = rect.y() + verticalOffset;
906     RefPtr<Gradient> strokeGradient = Gradient::create(Gradient::LinearData { FloatPoint(rect.x(), verticalRenderingPosition), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1) });
907     strokeGradient->addColorStop(0.0, Color(0x8d, 0x8d, 0x8d));
908     strokeGradient->addColorStop(0.45, Color(0xee, 0xee, 0xee));
909     strokeGradient->addColorStop(0.55, Color(0xee, 0xee, 0xee));
910     strokeGradient->addColorStop(1.0, Color(0x8d, 0x8d, 0x8d));
911     context.setStrokeGradient(strokeGradient.releaseNonNull());
912
913     context.setFillColor(Color(255, 255, 255));
914
915     Path trackPath;
916     FloatRect trackRect(rect.x() + 0.25, verticalRenderingPosition + 0.25, rect.width() - 0.5, progressBarHeight - 0.5);
917     FloatSize roundedCornerRadius(5, 4);
918     trackPath.addRoundedRect(trackRect, roundedCornerRadius);
919     context.drawPath(trackPath);
920
921     // 1.2) Draw top gradient on the upper half. It is supposed to overlay the fill from the background and darker the stroked path.
922     FloatRect border(rect.x(), rect.y() + verticalOffset, rect.width(), progressBarHeight);
923     paintInfo.context().clipRoundedRect(FloatRoundedRect(border, roundedCornerRadius, roundedCornerRadius, roundedCornerRadius, roundedCornerRadius));
924
925     float upperGradientHeight = progressBarHeight / 2.;
926     RefPtr<Gradient> upperGradient = Gradient::create(Gradient::LinearData { FloatPoint(rect.x(), verticalRenderingPosition + 0.5), FloatPoint(rect.x(), verticalRenderingPosition + upperGradientHeight - 1.5) });
927     upperGradient->addColorStop(0.0, Color(133, 133, 133, 188));
928     upperGradient->addColorStop(1.0, Color(18, 18, 18, 51));
929     context.setFillGradient(upperGradient.releaseNonNull());
930
931     context.fillRect(FloatRect(rect.x(), verticalRenderingPosition, rect.width(), upperGradientHeight));
932
933     const auto& renderProgress = downcast<RenderProgress>(renderer);
934     if (renderProgress.isDeterminate()) {
935         // 2) Draw the progress bar.
936         double position = clampTo(renderProgress.position(), 0.0, 1.0);
937         double barWidth = position * rect.width();
938         RefPtr<Gradient> barGradient = Gradient::create(Gradient::LinearData { FloatPoint(rect.x(), verticalRenderingPosition + 0.5), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1) });
939         barGradient->addColorStop(0.0, Color(195, 217, 247));
940         barGradient->addColorStop(0.45, Color(118, 164, 228));
941         barGradient->addColorStop(0.49, Color(118, 164, 228));
942         barGradient->addColorStop(0.51, Color(36, 114, 210));
943         barGradient->addColorStop(0.55, Color(36, 114, 210));
944         barGradient->addColorStop(1.0, Color(57, 142, 244));
945         context.setFillGradient(barGradient.releaseNonNull());
946
947         RefPtr<Gradient> barStrokeGradient = Gradient::create(Gradient::LinearData { FloatPoint(rect.x(), verticalRenderingPosition), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1) });
948         barStrokeGradient->addColorStop(0.0, Color(95, 107, 183));
949         barStrokeGradient->addColorStop(0.5, Color(66, 106, 174, 240));
950         barStrokeGradient->addColorStop(1.0, Color(38, 104, 166));
951         context.setStrokeGradient(barStrokeGradient.releaseNonNull());
952
953         Path barPath;
954         int left = rect.x();
955         if (!renderProgress.style().isLeftToRightDirection())
956             left = rect.maxX() - barWidth;
957         FloatRect barRect(left + 0.25, verticalRenderingPosition + 0.25, std::max(barWidth - 0.5, 0.0), progressBarHeight - 0.5);
958         barPath.addRoundedRect(barRect, roundedCornerRadius);
959         context.drawPath(barPath);
960     }
961
962     return false;
963 }
964
965 #if ENABLE(DATALIST_ELEMENT)
966 IntSize RenderThemeIOS::sliderTickSize() const
967 {
968     // FIXME: <rdar://problem/12271791> MERGEBOT: Correct values for slider tick of <input type="range"> elements (requires ENABLE_DATALIST_ELEMENT)
969     return IntSize(1, 3);
970 }
971
972 int RenderThemeIOS::sliderTickOffsetFromTrackCenter() const
973 {
974     // FIXME: <rdar://problem/12271791> MERGEBOT: Correct values for slider tick of <input type="range"> elements (requires ENABLE_DATALIST_ELEMENT)
975     return -9;
976 }
977 #endif
978
979 void RenderThemeIOS::adjustSearchFieldStyle(StyleResolver& selector, RenderStyle& style, const Element* element) const
980 {
981     RenderTheme::adjustSearchFieldStyle(selector, style, element);
982
983     if (!element)
984         return;
985
986     if (!style.hasBorder())
987         return;
988
989     RenderBox* box = element->renderBox();
990     if (!box)
991         return;
992
993     adjustRoundBorderRadius(style, *box);
994 }
995
996 bool RenderThemeIOS::paintSearchFieldDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
997 {
998     return paintTextFieldDecorations(box, paintInfo, rect);
999 }
1000
1001 void RenderThemeIOS::adjustButtonStyle(StyleResolver& selector, RenderStyle& style, const Element* element) const
1002 {
1003     RenderTheme::adjustButtonStyle(selector, style, element);
1004
1005     // Set padding: 0 1.0em; on buttons.
1006     // CSSPrimitiveValue::computeLengthInt only needs the element's style to calculate em lengths.
1007     // Since the element might not be in a document, just pass nullptr for the root element style
1008     // and the render view.
1009     RefPtr<CSSPrimitiveValue> emSize = CSSPrimitiveValue::create(1.0, CSSPrimitiveValue::CSS_EMS);
1010     int pixels = emSize->computeLength<int>(CSSToLengthConversionData(&style, nullptr, nullptr, 1.0, false));
1011     style.setPaddingBox(LengthBox(0, pixels, 0, pixels));
1012
1013     if (!element)
1014         return;
1015
1016     RenderBox* box = element->renderBox();
1017     if (!box)
1018         return;
1019
1020     adjustRoundBorderRadius(style, *box);
1021 }
1022
1023 bool RenderThemeIOS::paintButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
1024 {
1025     return paintPushButtonDecorations(box, paintInfo, rect);
1026 }
1027
1028 bool RenderThemeIOS::paintPushButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
1029 {
1030     GraphicsContextStateSaver stateSaver(paintInfo.context());
1031     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
1032
1033     CGContextRef cgContext = paintInfo.context().platformContext();
1034     if (box.style().visitedDependentColor(CSSPropertyBackgroundColor).isDark())
1035         drawAxialGradient(cgContext, gradientWithName(ConvexGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
1036     else {
1037         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
1038         drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(clip.x(), clip.maxY()), clip.location(), ExponentialInterpolation);
1039     }
1040     return false;
1041 }
1042
1043 void RenderThemeIOS::setButtonSize(RenderStyle& style) const
1044 {
1045     // If the width and height are both specified, then we have nothing to do.
1046     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
1047         return;
1048
1049     // Use the font size to determine the intrinsic width of the control.
1050     style.setHeight(Length(static_cast<int>(ControlBaseHeight / ControlBaseFontSize * style.fontDescription().computedSize()), Fixed));
1051 }
1052
1053 const int kThumbnailBorderStrokeWidth = 1;
1054 const int kThumbnailBorderCornerRadius = 1;
1055 const int kVisibleBackgroundImageWidth = 1;
1056 const int kMultipleThumbnailShrinkSize = 2;
1057
1058 bool RenderThemeIOS::paintFileUploadIconDecorations(const RenderObject&, const RenderObject& buttonRenderer, const PaintInfo& paintInfo, const IntRect& rect, Icon* icon, FileUploadDecorations fileUploadDecorations)
1059 {
1060     GraphicsContextStateSaver stateSaver(paintInfo.context());
1061
1062     IntSize cornerSize(kThumbnailBorderCornerRadius, kThumbnailBorderCornerRadius);
1063     Color pictureFrameColor = buttonRenderer.style().visitedDependentColor(CSSPropertyBorderTopColor);
1064
1065     IntRect thumbnailPictureFrameRect = rect;
1066     IntRect thumbnailRect = rect;
1067     thumbnailRect.contract(2 * kThumbnailBorderStrokeWidth, 2 * kThumbnailBorderStrokeWidth);
1068     thumbnailRect.move(kThumbnailBorderStrokeWidth, kThumbnailBorderStrokeWidth);
1069
1070     if (fileUploadDecorations == MultipleFiles) {
1071         // Smaller thumbnails for multiple selection appearance.
1072         thumbnailPictureFrameRect.contract(kMultipleThumbnailShrinkSize, kMultipleThumbnailShrinkSize);
1073         thumbnailRect.contract(kMultipleThumbnailShrinkSize, kMultipleThumbnailShrinkSize);
1074
1075         // Background picture frame and simple background icon with a gradient matching the button.
1076         Color backgroundImageColor = Color(buttonRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor).rgb());
1077         paintInfo.context().fillRoundedRect(FloatRoundedRect(thumbnailPictureFrameRect, cornerSize, cornerSize, cornerSize, cornerSize), pictureFrameColor);
1078         paintInfo.context().fillRect(thumbnailRect, backgroundImageColor);
1079         {
1080             GraphicsContextStateSaver stateSaver2(paintInfo.context());
1081             CGContextRef cgContext = paintInfo.context().platformContext();
1082             paintInfo.context().clip(thumbnailRect);
1083             if (backgroundImageColor.isDark())
1084                 drawAxialGradient(cgContext, gradientWithName(ConvexGradient), thumbnailRect.location(), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), LinearInterpolation);
1085             else {
1086                 drawAxialGradient(cgContext, gradientWithName(ShadeGradient), thumbnailRect.location(), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), LinearInterpolation);
1087                 drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), thumbnailRect.location(), ExponentialInterpolation);
1088             }
1089         }
1090
1091         // Move the rects for the Foreground picture frame and icon.
1092         int inset = kVisibleBackgroundImageWidth + kThumbnailBorderStrokeWidth;
1093         thumbnailPictureFrameRect.move(inset, inset);
1094         thumbnailRect.move(inset, inset);
1095     }
1096
1097     // Foreground picture frame and icon.
1098     paintInfo.context().fillRoundedRect(FloatRoundedRect(thumbnailPictureFrameRect, cornerSize, cornerSize, cornerSize, cornerSize), pictureFrameColor);
1099     icon->paint(paintInfo.context(), thumbnailRect);
1100
1101     return false;
1102 }
1103
1104 Color RenderThemeIOS::platformActiveSelectionBackgroundColor(OptionSet<StyleColor::Options>) const
1105 {
1106     return Color::transparent;
1107 }
1108
1109 Color RenderThemeIOS::platformInactiveSelectionBackgroundColor(OptionSet<StyleColor::Options>) const
1110 {
1111     return Color::transparent;
1112 }
1113
1114 bool RenderThemeIOS::shouldHaveSpinButton(const HTMLInputElement&) const
1115 {
1116     return false;
1117 }
1118
1119 bool RenderThemeIOS::shouldHaveCapsLockIndicator(const HTMLInputElement&) const
1120 {
1121     return false;
1122 }
1123
1124 FontCascadeDescription& RenderThemeIOS::cachedSystemFontDescription(CSSValueID valueID) const
1125 {
1126     static NeverDestroyed<FontCascadeDescription> systemFont;
1127     static NeverDestroyed<FontCascadeDescription> headlineFont;
1128     static NeverDestroyed<FontCascadeDescription> bodyFont;
1129     static NeverDestroyed<FontCascadeDescription> subheadlineFont;
1130     static NeverDestroyed<FontCascadeDescription> footnoteFont;
1131     static NeverDestroyed<FontCascadeDescription> caption1Font;
1132     static NeverDestroyed<FontCascadeDescription> caption2Font;
1133     static NeverDestroyed<FontCascadeDescription> shortHeadlineFont;
1134     static NeverDestroyed<FontCascadeDescription> shortBodyFont;
1135     static NeverDestroyed<FontCascadeDescription> shortSubheadlineFont;
1136     static NeverDestroyed<FontCascadeDescription> shortFootnoteFont;
1137     static NeverDestroyed<FontCascadeDescription> shortCaption1Font;
1138     static NeverDestroyed<FontCascadeDescription> tallBodyFont;
1139 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1140     static NeverDestroyed<FontCascadeDescription> title0Font;
1141 #endif
1142     static NeverDestroyed<FontCascadeDescription> title1Font;
1143     static NeverDestroyed<FontCascadeDescription> title2Font;
1144     static NeverDestroyed<FontCascadeDescription> title3Font;
1145 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1146     static NeverDestroyed<FontCascadeDescription> title4Font;
1147 #endif
1148
1149     static CFStringRef userTextSize = contentSizeCategory();
1150
1151     if (userTextSize != contentSizeCategory()) {
1152         userTextSize = contentSizeCategory();
1153
1154         headlineFont.get().setIsAbsoluteSize(false);
1155         bodyFont.get().setIsAbsoluteSize(false);
1156         subheadlineFont.get().setIsAbsoluteSize(false);
1157         footnoteFont.get().setIsAbsoluteSize(false);
1158         caption1Font.get().setIsAbsoluteSize(false);
1159         caption2Font.get().setIsAbsoluteSize(false);
1160         shortHeadlineFont.get().setIsAbsoluteSize(false);
1161         shortBodyFont.get().setIsAbsoluteSize(false);
1162         shortSubheadlineFont.get().setIsAbsoluteSize(false);
1163         shortFootnoteFont.get().setIsAbsoluteSize(false);
1164         shortCaption1Font.get().setIsAbsoluteSize(false);
1165         tallBodyFont.get().setIsAbsoluteSize(false);
1166     }
1167
1168     switch (valueID) {
1169     case CSSValueAppleSystemHeadline:
1170         return headlineFont;
1171     case CSSValueAppleSystemBody:
1172         return bodyFont;
1173 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1174     case CSSValueAppleSystemTitle0:
1175         return title0Font;
1176 #endif
1177     case CSSValueAppleSystemTitle1:
1178         return title1Font;
1179     case CSSValueAppleSystemTitle2:
1180         return title2Font;
1181     case CSSValueAppleSystemTitle3:
1182         return title3Font;
1183 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1184     case CSSValueAppleSystemTitle4:
1185         return title4Font;
1186 #endif
1187     case CSSValueAppleSystemSubheadline:
1188         return subheadlineFont;
1189     case CSSValueAppleSystemFootnote:
1190         return footnoteFont;
1191     case CSSValueAppleSystemCaption1:
1192         return caption1Font;
1193     case CSSValueAppleSystemCaption2:
1194         return caption2Font;
1195         // Short version.
1196     case CSSValueAppleSystemShortHeadline:
1197         return shortHeadlineFont;
1198     case CSSValueAppleSystemShortBody:
1199         return shortBodyFont;
1200     case CSSValueAppleSystemShortSubheadline:
1201         return shortSubheadlineFont;
1202     case CSSValueAppleSystemShortFootnote:
1203         return shortFootnoteFont;
1204     case CSSValueAppleSystemShortCaption1:
1205         return shortCaption1Font;
1206         // Tall version.
1207     case CSSValueAppleSystemTallBody:
1208         return tallBodyFont;
1209     default:
1210         return systemFont;
1211     }
1212 }
1213
1214 static inline FontSelectionValue cssWeightOfSystemFont(CTFontRef font)
1215 {
1216     RetainPtr<CFDictionaryRef> traits = adoptCF(CTFontCopyTraits(font));
1217     CFNumberRef resultRef = (CFNumberRef)CFDictionaryGetValue(traits.get(), kCTFontWeightTrait);
1218     float result = 0;
1219     CFNumberGetValue(resultRef, kCFNumberFloatType, &result);
1220     // These numbers were experimentally gathered from weights of the system font.
1221     static float weightThresholds[] = { -0.6, -0.365, -0.115, 0.130, 0.235, 0.350, 0.5, 0.7 };
1222     for (unsigned i = 0; i < WTF_ARRAY_LENGTH(weightThresholds); ++i) {
1223         if (result < weightThresholds[i])
1224             return FontSelectionValue((static_cast<int>(i) + 1) * 100);
1225     }
1226     return FontSelectionValue(900);
1227 }
1228
1229 void RenderThemeIOS::updateCachedSystemFontDescription(CSSValueID valueID, FontCascadeDescription& fontDescription) const
1230 {
1231     RetainPtr<CTFontDescriptorRef> fontDescriptor;
1232     CFStringRef textStyle;
1233     switch (valueID) {
1234     case CSSValueAppleSystemHeadline:
1235         textStyle = kCTUIFontTextStyleHeadline;
1236         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1237         break;
1238     case CSSValueAppleSystemBody:
1239         textStyle = kCTUIFontTextStyleBody;
1240         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1241         break;
1242 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1243     case CSSValueAppleSystemTitle0:
1244         textStyle = kCTUIFontTextStyleTitle0;
1245         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1246         break;
1247 #endif
1248     case CSSValueAppleSystemTitle1:
1249         textStyle = kCTUIFontTextStyleTitle1;
1250         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1251         break;
1252     case CSSValueAppleSystemTitle2:
1253         textStyle = kCTUIFontTextStyleTitle2;
1254         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1255         break;
1256     case CSSValueAppleSystemTitle3:
1257         textStyle = kCTUIFontTextStyleTitle3;
1258         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1259         break;
1260 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1261     case CSSValueAppleSystemTitle4:
1262         textStyle = kCTUIFontTextStyleTitle4;
1263         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1264         break;
1265 #endif
1266     case CSSValueAppleSystemSubheadline:
1267         textStyle = kCTUIFontTextStyleSubhead;
1268         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1269         break;
1270     case CSSValueAppleSystemFootnote:
1271         textStyle = kCTUIFontTextStyleFootnote;
1272         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1273         break;
1274     case CSSValueAppleSystemCaption1:
1275         textStyle = kCTUIFontTextStyleCaption1;
1276         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1277         break;
1278     case CSSValueAppleSystemCaption2:
1279         textStyle = kCTUIFontTextStyleCaption2;
1280         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1281         break;
1282
1283     // Short version.
1284     case CSSValueAppleSystemShortHeadline:
1285         textStyle = kCTUIFontTextStyleShortHeadline;
1286         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1287         break;
1288     case CSSValueAppleSystemShortBody:
1289         textStyle = kCTUIFontTextStyleShortBody;
1290         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1291         break;
1292     case CSSValueAppleSystemShortSubheadline:
1293         textStyle = kCTUIFontTextStyleShortSubhead;
1294         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1295         break;
1296     case CSSValueAppleSystemShortFootnote:
1297         textStyle = kCTUIFontTextStyleShortFootnote;
1298         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1299         break;
1300     case CSSValueAppleSystemShortCaption1:
1301         textStyle = kCTUIFontTextStyleShortCaption1;
1302         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1303         break;
1304
1305     // Tall version.
1306     case CSSValueAppleSystemTallBody:
1307         textStyle = kCTUIFontTextStyleTallBody;
1308         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), nullptr));
1309         break;
1310
1311     default:
1312         textStyle = kCTFontDescriptorTextStyleEmphasized;
1313         fontDescriptor = adoptCF(CTFontDescriptorCreateForUIType(kCTFontUIFontSystem, 0, nullptr));
1314     }
1315
1316     ASSERT(fontDescriptor);
1317     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 0, nullptr));
1318     fontDescription.setIsAbsoluteSize(true);
1319     fontDescription.setOneFamily(textStyle);
1320     fontDescription.setSpecifiedSize(CTFontGetSize(font.get()));
1321     fontDescription.setWeight(cssWeightOfSystemFont(font.get()));
1322     fontDescription.setItalic(normalItalicValue());
1323 }
1324
1325 #if ENABLE(VIDEO)
1326 String RenderThemeIOS::mediaControlsStyleSheet()
1327 {
1328 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1329     if (m_legacyMediaControlsStyleSheet.isEmpty())
1330         m_legacyMediaControlsStyleSheet = [NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsiOS" ofType:@"css"] encoding:NSUTF8StringEncoding error:nil];
1331     return m_legacyMediaControlsStyleSheet;
1332 #else
1333     return emptyString();
1334 #endif
1335 }
1336
1337 String RenderThemeIOS::modernMediaControlsStyleSheet()
1338 {
1339 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1340     if (RuntimeEnabledFeatures::sharedFeatures().modernMediaControlsEnabled()) {
1341         if (m_mediaControlsStyleSheet.isEmpty())
1342             m_mediaControlsStyleSheet = [NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"modern-media-controls" ofType:@"css" inDirectory:@"modern-media-controls"] encoding:NSUTF8StringEncoding error:nil];
1343         return m_mediaControlsStyleSheet;
1344     }
1345     return emptyString();
1346 #else
1347     return emptyString();
1348 #endif
1349 }
1350
1351 void RenderThemeIOS::purgeCaches()
1352 {
1353     m_legacyMediaControlsScript.clearImplIfNotShared();
1354     m_mediaControlsScript.clearImplIfNotShared();
1355     m_legacyMediaControlsStyleSheet.clearImplIfNotShared();
1356     m_mediaControlsStyleSheet.clearImplIfNotShared();
1357 }
1358
1359 String RenderThemeIOS::mediaControlsScript()
1360 {
1361 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1362     if (RuntimeEnabledFeatures::sharedFeatures().modernMediaControlsEnabled()) {
1363         if (m_mediaControlsScript.isEmpty()) {
1364             NSBundle *bundle = [NSBundle bundleForClass:[WebCoreRenderThemeBundle class]];
1365
1366             StringBuilder scriptBuilder;
1367             scriptBuilder.append([NSString stringWithContentsOfFile:[bundle pathForResource:@"modern-media-controls-localized-strings" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1368             scriptBuilder.append([NSString stringWithContentsOfFile:[bundle pathForResource:@"modern-media-controls" ofType:@"js" inDirectory:@"modern-media-controls"] encoding:NSUTF8StringEncoding error:nil]);
1369             m_mediaControlsScript = scriptBuilder.toString();
1370         }
1371         return m_mediaControlsScript;
1372     }
1373
1374     if (m_legacyMediaControlsScript.isEmpty()) {
1375         NSBundle *bundle = [NSBundle bundleForClass:[WebCoreRenderThemeBundle class]];
1376
1377         StringBuilder scriptBuilder;
1378         scriptBuilder.append([NSString stringWithContentsOfFile:[bundle pathForResource:@"mediaControlsLocalizedStrings" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1379         scriptBuilder.append([NSString stringWithContentsOfFile:[bundle pathForResource:@"mediaControlsApple" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1380         scriptBuilder.append([NSString stringWithContentsOfFile:[bundle pathForResource:@"mediaControlsiOS" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1381
1382         m_legacyMediaControlsScript = scriptBuilder.toString();
1383     }
1384     return m_legacyMediaControlsScript;
1385 #else
1386     return emptyString();
1387 #endif
1388 }
1389
1390 String RenderThemeIOS::mediaControlsBase64StringForIconNameAndType(const String& iconName, const String& iconType)
1391 {
1392 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1393     if (!RuntimeEnabledFeatures::sharedFeatures().modernMediaControlsEnabled())
1394         return emptyString();
1395
1396     String directory = "modern-media-controls/images";
1397     NSBundle *bundle = [NSBundle bundleForClass:[WebCoreRenderThemeBundle class]];
1398     return [[NSData dataWithContentsOfFile:[bundle pathForResource:iconName ofType:iconType inDirectory:directory]] base64EncodedStringWithOptions:0];
1399 #else
1400     return emptyString();
1401 #endif
1402 }
1403
1404 #endif // ENABLE(VIDEO)
1405
1406 Color RenderThemeIOS::systemColor(CSSValueID cssValueID, OptionSet<StyleColor::Options> options) const
1407 {
1408     const bool forVisitedLink = options.contains(StyleColor::Options::ForVisitedLink);
1409
1410     // The system color cache below can't handle visited links. The only color value
1411     // that cares about visited links is CSSValueWebkitLink, so handle it here by
1412     // calling through to RenderTheme's base implementation.
1413     if (forVisitedLink && cssValueID == CSSValueWebkitLink)
1414         return RenderTheme::systemColor(cssValueID, options);
1415
1416     ASSERT(!forVisitedLink);
1417
1418     auto addResult = m_systemColorCache.add(cssValueID, Color());
1419     if (!addResult.isNewEntry)
1420         return addResult.iterator->value;
1421
1422     Color color;
1423     switch (cssValueID) {
1424     case CSSValueAppleWirelessPlaybackTargetActive:
1425         color = [getUIColorClass() systemBlueColor].CGColor;
1426         break;
1427     case CSSValueAppleSystemBlue:
1428         color = [getUIColorClass() systemBlueColor].CGColor;
1429         break;
1430     case CSSValueAppleSystemGray:
1431         color = [getUIColorClass() systemGrayColor].CGColor;
1432         break;
1433     case CSSValueAppleSystemGreen:
1434         color = [getUIColorClass() systemGreenColor].CGColor;
1435         break;
1436     case CSSValueAppleSystemOrange:
1437         color = [getUIColorClass() systemOrangeColor].CGColor;
1438         break;
1439     case CSSValueAppleSystemPink:
1440         color = [getUIColorClass() systemPinkColor].CGColor;
1441         break;
1442     case CSSValueAppleSystemRed:
1443         color = [getUIColorClass() systemRedColor].CGColor;
1444         break;
1445     case CSSValueAppleSystemYellow:
1446         color = [getUIColorClass() systemYellowColor].CGColor;
1447         break;
1448     default:
1449         break;
1450     }
1451
1452     if (!color.isValid())
1453         color = RenderTheme::systemColor(cssValueID, options);
1454
1455     addResult.iterator->value = color;
1456
1457     return addResult.iterator->value;
1458 }
1459
1460 #if ENABLE(ATTACHMENT_ELEMENT)
1461
1462 const CGSize attachmentSize = { 160, 119 };
1463
1464 const CGFloat attachmentBorderRadius = 16;
1465 static Color attachmentBorderColor() { return Color(204, 204, 204); }
1466
1467 static Color attachmentProgressColor() { return Color(222, 222, 222); }
1468 const CGFloat attachmentProgressBorderThickness = 3;
1469
1470 const CGFloat attachmentProgressSize = 36;
1471 const CGFloat attachmentIconSize = 48;
1472
1473 const CGFloat attachmentItemMargin = 8;
1474
1475 const CGFloat attachmentWrappingTextMaximumWidth = 140;
1476 const CFIndex attachmentWrappingTextMaximumLineCount = 2;
1477
1478 static RetainPtr<CTFontRef> attachmentActionFont()
1479 {
1480     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(kCTUIFontTextStyleShortFootnote, RenderThemeIOS::contentSizeCategory(), 0));
1481     RetainPtr<CTFontDescriptorRef> emphasizedFontDescriptor = adoptCF(CTFontDescriptorCreateCopyWithAttributes(fontDescriptor.get(),
1482         (CFDictionaryRef)@{
1483             (id)kCTFontDescriptorTextStyleAttribute: (id)kCTFontDescriptorTextStyleEmphasized
1484     }));
1485     return adoptCF(CTFontCreateWithFontDescriptor(emphasizedFontDescriptor.get(), 0, nullptr));
1486 }
1487
1488 static UIColor *attachmentActionColor(const RenderAttachment& attachment)
1489 {
1490     return [getUIColorClass() colorWithCGColor:cachedCGColor(attachment.style().visitedDependentColor(CSSPropertyColor))];
1491 }
1492
1493 static RetainPtr<CTFontRef> attachmentTitleFont()
1494 {
1495     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(kCTUIFontTextStyleShortCaption1, RenderThemeIOS::contentSizeCategory(), 0));
1496     return adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 0, nullptr));
1497 }
1498
1499 static UIColor *attachmentTitleColor() { return [getUIColorClass() systemGrayColor]; }
1500
1501 static RetainPtr<CTFontRef> attachmentSubtitleFont() { return attachmentTitleFont(); }
1502 static UIColor *attachmentSubtitleColor() { return [getUIColorClass() systemGrayColor]; }
1503
1504 struct RenderAttachmentInfo {
1505     explicit RenderAttachmentInfo(const RenderAttachment&);
1506
1507     FloatRect iconRect;
1508     FloatRect attachmentRect;
1509     FloatRect progressRect;
1510
1511     BOOL hasProgress { NO };
1512     float progress;
1513
1514     RetainPtr<UIImage> icon;
1515
1516     int baseline { 0 };
1517
1518     struct LabelLine {
1519         FloatRect rect;
1520         RetainPtr<CTLineRef> line;
1521     };
1522     Vector<LabelLine> lines;
1523
1524     CGFloat contentYOrigin { 0 };
1525
1526 private:
1527     void buildWrappedLines(const String&, CTFontRef, UIColor *, unsigned maximumLineCount);
1528     void buildSingleLine(const String&, CTFontRef, UIColor *);
1529
1530     void addLine(CTLineRef);
1531 };
1532
1533 void RenderAttachmentInfo::addLine(CTLineRef line)
1534 {
1535     CGRect lineBounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsExcludeTypographicLeading);
1536     CGFloat trailingWhitespaceWidth = CTLineGetTrailingWhitespaceWidth(line);
1537     CGFloat lineWidthIgnoringTrailingWhitespace = lineBounds.size.width - trailingWhitespaceWidth;
1538     CGFloat lineHeight = CGCeiling(lineBounds.size.height + lineBounds.origin.y);
1539
1540     CGFloat xOffset = (attachmentRect.width() / 2) - (lineWidthIgnoringTrailingWhitespace / 2);
1541     LabelLine labelLine;
1542     labelLine.line = line;
1543     labelLine.rect = FloatRect(xOffset, 0, lineWidthIgnoringTrailingWhitespace, lineHeight);
1544
1545     lines.append(labelLine);
1546 }
1547
1548 void RenderAttachmentInfo::buildWrappedLines(const String& text, CTFontRef font, UIColor *color, unsigned maximumLineCount)
1549 {
1550     if (text.isEmpty())
1551         return;
1552
1553     NSDictionary *textAttributes = @{
1554         (id)kCTFontAttributeName: (id)font,
1555         (id)kCTForegroundColorAttributeName: color
1556     };
1557     RetainPtr<NSAttributedString> attributedText = adoptNS([[NSAttributedString alloc] initWithString:text attributes:textAttributes]);
1558     RetainPtr<CTFramesetterRef> framesetter = adoptCF(CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedText.get()));
1559
1560     CFRange fitRange;
1561     CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter.get(), CFRangeMake(0, 0), nullptr, CGSizeMake(attachmentWrappingTextMaximumWidth, CGFLOAT_MAX), &fitRange);
1562
1563     RetainPtr<CGPathRef> textPath = adoptCF(CGPathCreateWithRect(CGRectMake(0, 0, textSize.width, textSize.height), nullptr));
1564     RetainPtr<CTFrameRef> textFrame = adoptCF(CTFramesetterCreateFrame(framesetter.get(), fitRange, textPath.get(), nullptr));
1565
1566     CFArrayRef ctLines = CTFrameGetLines(textFrame.get());
1567     CFIndex lineCount = CFArrayGetCount(ctLines);
1568     if (!lineCount)
1569         return;
1570
1571     // Lay out and record the first (maximumLineCount - 1) lines.
1572     CFIndex lineIndex = 0;
1573     CFIndex nonTruncatedLineCount = std::min<CFIndex>(maximumLineCount - 1, lineCount);
1574     for (; lineIndex < nonTruncatedLineCount; ++lineIndex)
1575         addLine((CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex));
1576
1577     if (lineIndex == lineCount)
1578         return;
1579
1580     // We had text that didn't fit in the first (maximumLineCount - 1) lines.
1581     // Combine it into one last line, and center-truncate it.
1582     CTLineRef firstRemainingLine = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
1583     CFIndex remainingRangeStart = CTLineGetStringRange(firstRemainingLine).location;
1584     NSRange remainingRange = NSMakeRange(remainingRangeStart, [attributedText length] - remainingRangeStart);
1585     NSAttributedString *remainingString = [attributedText attributedSubstringFromRange:remainingRange];
1586     RetainPtr<CTLineRef> remainingLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)remainingString));
1587     RetainPtr<NSAttributedString> ellipsisString = adoptNS([[NSAttributedString alloc] initWithString:@"\u2026" attributes:textAttributes]);
1588     RetainPtr<CTLineRef> ellipsisLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)ellipsisString.get()));
1589     RetainPtr<CTLineRef> truncatedLine = adoptCF(CTLineCreateTruncatedLine(remainingLine.get(), attachmentWrappingTextMaximumWidth, kCTLineTruncationMiddle, ellipsisLine.get()));
1590
1591     if (!truncatedLine)
1592         truncatedLine = remainingLine;
1593
1594     addLine(truncatedLine.get());
1595 }
1596
1597 void RenderAttachmentInfo::buildSingleLine(const String& text, CTFontRef font, UIColor *color)
1598 {
1599     if (text.isEmpty())
1600         return;
1601
1602     NSDictionary *textAttributes = @{
1603         (id)kCTFontAttributeName: (id)font,
1604         (id)kCTForegroundColorAttributeName: color
1605     };
1606     RetainPtr<NSAttributedString> attributedText = adoptNS([[NSAttributedString alloc] initWithString:text attributes:textAttributes]);
1607
1608     addLine(adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)attributedText.get())).get());
1609 }
1610
1611 static BOOL getAttachmentProgress(const RenderAttachment& attachment, float& progress)
1612 {
1613     auto& progressString = attachment.attachmentElement().attributeWithoutSynchronization(progressAttr);
1614     if (progressString.isEmpty())
1615         return NO;
1616     bool validProgress;
1617     progress = std::max<float>(std::min<float>(progressString.toFloat(&validProgress), 1), 0);
1618     return validProgress;
1619 }
1620
1621 static RetainPtr<UIImage> iconForAttachment(const RenderAttachment& attachment, FloatSize& size)
1622 {
1623     auto documentInteractionController = adoptNS([allocUIDocumentInteractionControllerInstance() init]);
1624
1625     String fileName;
1626     if (File* file = attachment.attachmentElement().file())
1627         fileName = file->name();
1628
1629     if (fileName.isEmpty())
1630         fileName = attachment.attachmentElement().attachmentTitle();
1631     [documentInteractionController setName:fileName];
1632
1633     String attachmentType = attachment.attachmentElement().attachmentType();
1634     if (!attachmentType.isEmpty()) {
1635         String UTI;
1636         if (isDeclaredUTI(attachmentType))
1637             UTI = attachmentType;
1638         else
1639             UTI = UTIFromMIMEType(attachmentType);
1640
1641         [documentInteractionController setUTI:static_cast<NSString *>(UTI)];
1642     }
1643
1644     NSArray *icons = [documentInteractionController icons];
1645     if (!icons.count)
1646         return nil;
1647
1648     RetainPtr<UIImage> result = icons.lastObject;
1649
1650     BOOL useHeightForClosestMatch = [result size].height > [result size].width;
1651     CGFloat bestMatchRatio = -1;
1652
1653     for (UIImage *icon in icons) {
1654         CGFloat iconSize = useHeightForClosestMatch ? icon.size.height : icon.size.width;
1655
1656         CGFloat matchRatio = (attachmentIconSize / iconSize) - 1.0f;
1657         if (matchRatio < 0.3f) {
1658             matchRatio = CGFAbs(matchRatio);
1659             if ((bestMatchRatio == -1) || (matchRatio < bestMatchRatio)) {
1660                 result = icon;
1661                 bestMatchRatio = matchRatio;
1662             }
1663         }
1664     }
1665
1666     CGFloat iconAspect = [result size].width / [result size].height;
1667     size = largestRectWithAspectRatioInsideRect(iconAspect, FloatRect(0, 0, attachmentIconSize, attachmentIconSize)).size();
1668
1669     return result;
1670 }
1671
1672 RenderAttachmentInfo::RenderAttachmentInfo(const RenderAttachment& attachment)
1673 {
1674     attachmentRect = FloatRect(0, 0, attachment.width().toFloat(), attachment.height().toFloat());
1675
1676     hasProgress = getAttachmentProgress(attachment, progress);
1677
1678     String title = attachment.attachmentElement().attachmentTitle();
1679     String action = attachment.attachmentElement().attributeWithoutSynchronization(actionAttr);
1680     String subtitle = attachment.attachmentElement().attributeWithoutSynchronization(subtitleAttr);
1681
1682     CGFloat yOffset = 0;
1683
1684     if (hasProgress) {
1685         progressRect = FloatRect((attachmentRect.width() / 2) - (attachmentProgressSize / 2), 0, attachmentProgressSize, attachmentProgressSize);
1686         yOffset += attachmentProgressSize + attachmentItemMargin;
1687     }
1688
1689     if (action.isEmpty() && !hasProgress) {
1690         FloatSize iconSize;
1691         icon = iconForAttachment(attachment, iconSize);
1692         if (icon) {
1693             iconRect = FloatRect(FloatPoint((attachmentRect.width() / 2) - (iconSize.width() / 2), 0), iconSize);
1694             yOffset += iconRect.height() + attachmentItemMargin;
1695         }
1696     } else
1697         buildWrappedLines(action, attachmentActionFont().get(), attachmentActionColor(attachment), attachmentWrappingTextMaximumLineCount);
1698
1699     bool forceSingleLineTitle = !action.isEmpty() || !subtitle.isEmpty() || hasProgress;
1700     buildWrappedLines(title, attachmentTitleFont().get(), attachmentTitleColor(), forceSingleLineTitle ? 1 : attachmentWrappingTextMaximumLineCount);
1701     buildSingleLine(subtitle, attachmentSubtitleFont().get(), attachmentSubtitleColor());
1702
1703     if (!lines.isEmpty()) {
1704         for (auto& line : lines) {
1705             line.rect.setY(yOffset);
1706             yOffset += line.rect.height() + attachmentItemMargin;
1707         }
1708     }
1709
1710     yOffset -= attachmentItemMargin;
1711
1712     contentYOrigin = (attachmentRect.height() / 2) - (yOffset / 2);
1713 }
1714
1715 LayoutSize RenderThemeIOS::attachmentIntrinsicSize(const RenderAttachment&) const
1716 {
1717     return LayoutSize(FloatSize(attachmentSize));
1718 }
1719
1720 int RenderThemeIOS::attachmentBaseline(const RenderAttachment& attachment) const
1721 {
1722     RenderAttachmentInfo info(attachment);
1723     return info.baseline;
1724 }
1725
1726 static void paintAttachmentIcon(GraphicsContext& context, RenderAttachmentInfo& info)
1727 {
1728     if (!info.icon)
1729         return;
1730
1731     RefPtr<Image> iconImage = BitmapImage::create([info.icon CGImage]);
1732     if (!iconImage)
1733         return;
1734
1735     context.drawImage(*iconImage, info.iconRect);
1736 }
1737
1738 static void paintAttachmentText(GraphicsContext& context, RenderAttachmentInfo& info)
1739 {
1740     for (const auto& line : info.lines) {
1741         GraphicsContextStateSaver saver(context);
1742
1743         context.translate(toFloatSize(line.rect.minXMaxYCorner()));
1744         context.scale(FloatSize(1, -1));
1745
1746         CGContextSetTextPosition(context.platformContext(), 0, 0);
1747         CTLineDraw(line.line.get(), context.platformContext());
1748     }
1749 }
1750
1751 static void paintAttachmentProgress(GraphicsContext& context, RenderAttachmentInfo& info)
1752 {
1753     GraphicsContextStateSaver saver(context);
1754
1755     context.setStrokeThickness(attachmentProgressBorderThickness);
1756     context.setStrokeColor(attachmentProgressColor());
1757     context.setFillColor(attachmentProgressColor());
1758     context.strokeEllipse(info.progressRect);
1759
1760     FloatPoint center = info.progressRect.center();
1761
1762     Path progressPath;
1763     progressPath.moveTo(center);
1764     progressPath.addLineTo(FloatPoint(center.x(), info.progressRect.y()));
1765     progressPath.addArc(center, info.progressRect.width() / 2, -M_PI_2, info.progress * 2 * M_PI - M_PI_2, 0);
1766     progressPath.closeSubpath();
1767     context.fillPath(progressPath);
1768 }
1769
1770 static Path attachmentBorderPath(RenderAttachmentInfo& info)
1771 {
1772     Path borderPath;
1773     borderPath.addRoundedRect(info.attachmentRect, FloatSize(attachmentBorderRadius, attachmentBorderRadius));
1774     return borderPath;
1775 }
1776
1777 static void paintAttachmentBorder(GraphicsContext& context, Path& borderPath)
1778 {
1779     context.setStrokeColor(attachmentBorderColor());
1780     context.setStrokeThickness(1);
1781     context.strokePath(borderPath);
1782 }
1783
1784 bool RenderThemeIOS::paintAttachment(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& paintRect)
1785 {
1786     if (!is<RenderAttachment>(renderer))
1787         return false;
1788
1789     const RenderAttachment& attachment = downcast<RenderAttachment>(renderer);
1790
1791     RenderAttachmentInfo info(attachment);
1792
1793     GraphicsContext& context = paintInfo.context();
1794     GraphicsContextStateSaver saver(context);
1795
1796     context.translate(toFloatSize(paintRect.location()));
1797
1798     if (attachment.shouldDrawBorder()) {
1799         auto borderPath = attachmentBorderPath(info);
1800         paintAttachmentBorder(context, borderPath);
1801         context.clipPath(borderPath);
1802     }
1803
1804     context.translate(FloatSize(0, info.contentYOrigin));
1805
1806     if (info.hasProgress)
1807         paintAttachmentProgress(context, info);
1808     else if (info.icon)
1809         paintAttachmentIcon(context, info);
1810
1811     paintAttachmentText(context, info);
1812
1813     return true;
1814 }
1815
1816 #endif // ENABLE(ATTACHMENT_ELEMENT)
1817
1818 #if PLATFORM(WATCHOS)
1819
1820 String RenderThemeIOS::extraDefaultStyleSheet()
1821 {
1822     return ASCIILiteral("* { -webkit-text-size-adjust: auto; -webkit-hyphens: auto !important; }");
1823 }
1824
1825 #endif
1826
1827 #if USE(SYSTEM_PREVIEW)
1828 void RenderThemeIOS::paintSystemPreviewBadge(Image& image, const PaintInfo& paintInfo, const FloatRect& rect)
1829 {
1830     static const int largeBadgeDimension = 70;
1831     static const int largeBadgeOffset = 20;
1832
1833     static const int smallBadgeDimension = 35;
1834     static const int smallBadgeOffset = 8;
1835
1836     static const int minimumSizeForLargeBadge = 240;
1837
1838     bool useSmallBadge = rect.width() < minimumSizeForLargeBadge || rect.height() < minimumSizeForLargeBadge;
1839     int badgeOffset = useSmallBadge ? smallBadgeOffset : largeBadgeOffset;
1840     int badgeDimension = useSmallBadge ? smallBadgeDimension : largeBadgeDimension;
1841
1842     int minimumDimension = badgeDimension + 2 * badgeOffset;
1843     if (rect.width() < minimumDimension || rect.height() < minimumDimension)
1844         return;
1845
1846     CGRect absoluteBadgeRect = CGRectMake(rect.x() + rect.width() - badgeDimension - badgeOffset, rect.y() + badgeOffset, badgeDimension, badgeDimension);
1847     CGRect insetBadgeRect = CGRectMake(rect.width() - badgeDimension - badgeOffset, badgeOffset, badgeDimension, badgeDimension);
1848     CGRect badgeRect = CGRectMake(0, 0, badgeDimension, badgeDimension);
1849
1850     CIImage *inputImage = [CIImage imageWithCGImage:image.nativeImage().get()];
1851
1852     // Create a circle to be used for the clipping path in the badge, as well as the drop shadow.
1853     RetainPtr<CGPathRef> circle = adoptCF(CGPathCreateWithRoundedRect(absoluteBadgeRect, badgeDimension / 2, badgeDimension / 2, nullptr));
1854
1855     auto& graphicsContext = paintInfo.context();
1856     if (graphicsContext.paintingDisabled())
1857         return;
1858
1859     CGContextRef ctx = graphicsContext.platformContext();
1860     if (!ctx)
1861         return;
1862
1863     CGContextSaveGState(ctx);
1864
1865     // Draw a drop shadow around the circle.
1866     CGFloat shadowColorComponents[4] = { 0, 0, 0, 0.1 };
1867     RetainPtr<CGColorRef> shadowColor = adoptCF(CGColorCreate(sRGBColorSpaceRef(), shadowColorComponents));
1868     // The circle must have an alpha channel value of 1 for the shadow color to appear.
1869     CGFloat circleColorComponents[4] = { 0, 0, 0, 1 };
1870     RetainPtr<CGColorRef> circleColor = adoptCF(CGColorCreate(sRGBColorSpaceRef(), circleColorComponents));
1871     CGContextSetFillColorWithColor(ctx, circleColor.get());
1872     CGContextSetShadowWithColor(ctx, CGSizeZero, 16, shadowColor.get());
1873
1874     // Clip out the circle to only show the shadow.
1875     CGContextBeginPath(ctx);
1876     CGContextAddRect(ctx, rect);
1877     CGContextAddPath(ctx, circle.get());
1878     CGContextClosePath(ctx);
1879     CGContextEOClip(ctx);
1880
1881     // Draw a slightly smaller circle with a shadow, otherwise we'll see a fringe of the solid
1882     // black circle around the edges of the clipped path below.
1883     CGContextBeginPath(ctx);
1884     CGRect slightlySmallerAbsoluteBadgeRect = CGRectMake(absoluteBadgeRect.origin.x + 0.5, absoluteBadgeRect.origin.y + 0.5, badgeDimension - 1, badgeDimension - 1);
1885     RetainPtr<CGPathRef> slightlySmallerCircle = adoptCF(CGPathCreateWithRoundedRect(slightlySmallerAbsoluteBadgeRect, slightlySmallerAbsoluteBadgeRect.size.width / 2, slightlySmallerAbsoluteBadgeRect.size.height / 2, nullptr));
1886     CGContextAddPath(ctx, slightlySmallerCircle.get());
1887     CGContextClosePath(ctx);
1888     CGContextFillPath(ctx);
1889
1890     CGContextRestoreGState(ctx);
1891
1892     // Draw the blurred backdrop. Scale from intrinsic size to render size.
1893     CGAffineTransform transform = CGAffineTransformIdentity;
1894     transform = CGAffineTransformScale(transform, rect.width() / image.width(), rect.height() / image.height());
1895     CIImage *scaledImage = [inputImage imageByApplyingTransform:transform];
1896
1897     // CoreImage coordinates are y-up, so we need to flip the badge rectangle within the image frame.
1898     CGRect flippedInsetBadgeRect = CGRectMake(insetBadgeRect.origin.x, rect.height() - insetBadgeRect.origin.y - insetBadgeRect.size.height, badgeDimension, badgeDimension);
1899
1900     // Create a cropped region with pixel values extending outwards.
1901     CIImage *clampedImage = [scaledImage imageByClampingToRect:flippedInsetBadgeRect];
1902
1903     // Blur.
1904     CIImage *blurredImage = [clampedImage imageByApplyingGaussianBlurWithSigma:10];
1905
1906     // Saturate.
1907     CIFilter *saturationFilter = [CIFilter filterWithName:@"CIColorControls"];
1908     [saturationFilter setValue:blurredImage forKey:kCIInputImageKey];
1909     [saturationFilter setValue:@1.8 forKey:kCIInputSaturationKey];
1910
1911     // Tint.
1912     CIFilter *tintFilter1 = [CIFilter filterWithName:@"CIConstantColorGenerator"];
1913     CIColor *tintColor1 = [CIColor colorWithRed:1 green:1 blue:1 alpha:0.18];
1914     [tintFilter1 setValue:tintColor1 forKey:kCIInputColorKey];
1915
1916     // Blend the tint with the saturated output.
1917     CIFilter *sourceOverFilter = [CIFilter filterWithName:@"CISourceOverCompositing"];
1918     [sourceOverFilter setValue:tintFilter1.outputImage forKey:kCIInputImageKey];
1919     [sourceOverFilter setValue:saturationFilter.outputImage forKey:kCIInputBackgroundImageKey];
1920
1921     if (!m_ciContext)
1922         m_ciContext = [CIContext context];
1923
1924     RetainPtr<CGImageRef> cgImage;
1925 #if HAVE(IOSURFACE)
1926     // Crop the result to the badge location.
1927     CIImage *croppedImage = [sourceOverFilter.outputImage imageByCroppingToRect:flippedInsetBadgeRect];
1928     CIImage *translatedImage = [croppedImage imageByApplyingTransform:CGAffineTransformMakeTranslation(-flippedInsetBadgeRect.origin.x, -flippedInsetBadgeRect.origin.y)];
1929     IOSurfaceRef surface;
1930     if (useSmallBadge) {
1931         if (!m_smallBadgeSurface)
1932             m_smallBadgeSurface = IOSurface::create({ smallBadgeDimension, smallBadgeDimension }, sRGBColorSpaceRef());
1933         surface = m_smallBadgeSurface->surface();
1934     } else {
1935         if (!m_largeBadgeSurface)
1936             m_largeBadgeSurface = IOSurface::create({ largeBadgeDimension, largeBadgeDimension }, sRGBColorSpaceRef());
1937         surface = m_largeBadgeSurface->surface();
1938     }
1939     [m_ciContext.get() render:translatedImage toIOSurface:surface bounds:badgeRect colorSpace:sRGBColorSpaceRef()];
1940     cgImage = useSmallBadge ? m_smallBadgeSurface->createImage() : m_largeBadgeSurface->createImage();
1941 #else
1942     cgImage = adoptCF([m_ciContext.get() createCGImage:sourceOverFilter.outputImage fromRect:flippedInsetBadgeRect]);
1943 #endif
1944
1945     // Before we render the result, we should clip to a circle around the badge rectangle.
1946     CGContextSaveGState(ctx);
1947     CGContextBeginPath(ctx);
1948     CGContextAddPath(ctx, circle.get());
1949     CGContextClosePath(ctx);
1950     CGContextClip(ctx);
1951
1952     CGContextTranslateCTM(ctx, absoluteBadgeRect.origin.x, absoluteBadgeRect.origin.y);
1953     CGContextTranslateCTM(ctx, 0, badgeDimension);
1954     CGContextScaleCTM(ctx, 1, -1);
1955     CGContextDrawImage(ctx, badgeRect, cgImage.get());
1956
1957 #if USE(APPLE_INTERNAL_SDK)
1958     if (auto logo = systemPreviewLogo()) {
1959         CGSize pdfSize = CGPDFPageGetBoxRect(logo, kCGPDFMediaBox).size;
1960         CGFloat scaleX = badgeDimension / pdfSize.width;
1961         CGFloat scaleY = badgeDimension / pdfSize.height;
1962         CGContextScaleCTM(ctx, scaleX, scaleY);
1963         CGContextDrawPDFPage(ctx, logo);
1964     }
1965 #endif
1966
1967     CGContextFlush(ctx);
1968     CGContextRestoreGState(ctx);
1969 }
1970 #endif
1971
1972 } // namespace WebCore
1973
1974 #endif //PLATFORM(IOS)