Rename SimpleFontData to Font
[WebKit-https.git] / Source / WebCore / rendering / RenderThemeIOS.mm
1 /*
2  * Copyright (C) 2005, 2006, 2007, 2008 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
28 #if PLATFORM(IOS)
29
30 #import "CSSPrimitiveValue.h"
31 #import "CSSToLengthConversionData.h"
32 #import "CSSValueKeywords.h"
33 #import "CoreTextSPI.h"
34 #import "DateComponents.h"
35 #import "Document.h"
36 #import "FloatRoundedRect.h"
37 #import "FontCache.h"
38 #import "FontCascade.h"
39 #import "Frame.h"
40 #import "FrameView.h"
41 #import "Gradient.h"
42 #import "GraphicsContext.h"
43 #import "GraphicsContextCG.h"
44 #import "HTMLInputElement.h"
45 #import "HTMLNames.h"
46 #import "HTMLSelectElement.h"
47 #import "Icon.h"
48 #import "LocalizedDateCache.h"
49 #import "NodeRenderStyle.h"
50 #import "Page.h"
51 #import "PaintInfo.h"
52 #import "PlatformLocale.h"
53 #import "RenderObject.h"
54 #import "RenderProgress.h"
55 #import "RenderStyle.h"
56 #import "RenderThemeIOS.h"
57 #import "RenderView.h"
58 #import "SoftLinking.h"
59 #import "UserAgentScripts.h"
60 #import "UserAgentStyleSheets.h"
61 #import "WebCoreThreadRun.h"
62 #import <CoreGraphics/CoreGraphics.h>
63 #import <objc/runtime.h>
64 #import <wtf/NeverDestroyed.h>
65 #import <wtf/RefPtr.h>
66 #import <wtf/StdLibExtras.h>
67
68 @interface UIApplication
69 + (UIApplication *)sharedApplication;
70 @property(nonatomic,copy) NSString *preferredContentSizeCategory;
71 @end
72
73 SOFT_LINK_FRAMEWORK(UIKit)
74 SOFT_LINK_CLASS(UIKit, UIApplication)
75 SOFT_LINK_CONSTANT(UIKit, UIContentSizeCategoryDidChangeNotification, CFStringRef)
76 #define UIContentSizeCategoryDidChangeNotification getUIContentSizeCategoryDidChangeNotification()
77
78 @interface WebCoreRenderThemeBundle : NSObject
79 @end
80
81 @implementation WebCoreRenderThemeBundle
82 @end
83
84 namespace WebCore {
85
86 const float ControlBaseHeight = 20;
87 const float ControlBaseFontSize = 11;
88
89 struct IOSGradient {
90     float* start; // points to static float[4]
91     float* end; // points to static float[4]
92     IOSGradient(float start[4], float end[4])
93         : start(start)
94         , end(end)
95     {
96     }
97 };
98
99 typedef IOSGradient* IOSGradientRef;
100
101 enum Interpolation
102 {
103     LinearInterpolation,
104     ExponentialInterpolation
105 };
106
107 static void interpolateLinearGradient(void *info, const CGFloat *inData, CGFloat *outData)
108 {
109     IOSGradientRef gradient = static_cast<IOSGradientRef>(info);
110     float alpha = inData[0];
111     float inverse = 1.0f - alpha;
112
113     outData[0] = inverse * gradient->start[0] + alpha * gradient->end[0];
114     outData[1] = inverse * gradient->start[1] + alpha * gradient->end[1];
115     outData[2] = inverse * gradient->start[2] + alpha * gradient->end[2];
116     outData[3] = inverse * gradient->start[3] + alpha * gradient->end[3];
117 }
118
119 static void interpolateExponentialGradient(void *info, const CGFloat *inData, CGFloat *outData)
120 {
121     IOSGradientRef gradient = static_cast<IOSGradientRef>(info);
122     float a = inData[0];
123     for (int paintInfo = 0; paintInfo < 4; ++paintInfo) {
124         float end = logf(std::max(gradient->end[paintInfo], 0.01f));
125         float start = logf(std::max(gradient->start[paintInfo], 0.01f));
126         outData[paintInfo] = expf(start - (end + start) * a);
127     }
128 }
129
130 static CGFunctionRef getSharedFunctionRef(IOSGradientRef gradient, Interpolation interpolation)
131 {
132     CGFunctionRef function = nullptr;
133
134     static HashMap<IOSGradientRef, CGFunctionRef>* linearFunctionRefs;
135     static HashMap<IOSGradientRef, CGFunctionRef>* exponentialFunctionRefs;;
136
137     if (interpolation == LinearInterpolation) {
138         if (!linearFunctionRefs)
139             linearFunctionRefs = new HashMap<IOSGradientRef, CGFunctionRef>;
140         else
141             function = linearFunctionRefs->get(gradient);
142     
143         if (!function) {
144             static struct CGFunctionCallbacks linearFunctionCallbacks =  { 0, interpolateLinearGradient, 0 };
145             linearFunctionRefs->set(gradient, function = CGFunctionCreate(gradient, 1, nullptr, 4, nullptr, &linearFunctionCallbacks));
146         }
147
148         return function;
149     }
150
151     if (!exponentialFunctionRefs)
152         exponentialFunctionRefs = new HashMap<IOSGradientRef, CGFunctionRef>;
153     else
154         function = exponentialFunctionRefs->get(gradient);
155
156     if (!function) {
157         static struct CGFunctionCallbacks exponentialFunctionCallbacks =  { 0, interpolateExponentialGradient, 0 };
158         exponentialFunctionRefs->set(gradient, function = CGFunctionCreate(gradient, 1, 0, 4, 0, &exponentialFunctionCallbacks));
159     }
160
161     return function;
162 }
163
164 static void drawAxialGradient(CGContextRef context, IOSGradientRef gradient, const FloatPoint& startPoint, const FloatPoint& stopPoint, Interpolation interpolation)
165 {
166     RetainPtr<CGShadingRef> shading = adoptCF(CGShadingCreateAxial(deviceRGBColorSpaceRef(), startPoint, stopPoint, getSharedFunctionRef(gradient, interpolation), false, false));
167     CGContextDrawShading(context, shading.get());
168 }
169
170 static void drawRadialGradient(CGContextRef context, IOSGradientRef gradient, const FloatPoint& startPoint, float startRadius, const FloatPoint& stopPoint, float stopRadius, Interpolation interpolation)
171 {
172     RetainPtr<CGShadingRef> shading = adoptCF(CGShadingCreateRadial(deviceRGBColorSpaceRef(), startPoint, startRadius, stopPoint, stopRadius, getSharedFunctionRef(gradient, interpolation), false, false));
173     CGContextDrawShading(context, shading.get());
174 }
175
176 enum IOSGradientType {
177     InsetGradient,
178     ShineGradient,
179     ShadeGradient,
180     ConvexGradient,
181     ConcaveGradient,
182     SliderTrackGradient,
183     ReadonlySliderTrackGradient,
184     SliderThumbOpaquePressedGradient,
185 };
186
187 static IOSGradientRef getInsetGradient()
188 {
189     static float end[4] = { 0 / 255.0, 0 / 255.0, 0 / 255.0, 0 };
190     static float start[4] = { 0 / 255.0, 0 / 255.0, 0 / 255.0, 0.2 };
191     static NeverDestroyed<IOSGradient> gradient(start, end);
192     return &gradient.get();
193 }
194
195 static IOSGradientRef getShineGradient()
196 {
197     static float end[4] = { 1, 1, 1, 0.8 };
198     static float start[4] = { 1, 1, 1, 0 };
199     static NeverDestroyed<IOSGradient> gradient(start, end);
200     return &gradient.get();
201 }
202
203 static IOSGradientRef getShadeGradient()
204 {
205     static float end[4] = { 178 / 255.0, 178 / 255.0, 178 / 255.0, 0.65 };
206     static float start[4] = { 252 / 255.0, 252 / 255.0, 252 / 255.0, 0.65 };
207     static NeverDestroyed<IOSGradient> gradient(start, end);
208     return &gradient.get();
209 }
210
211 static IOSGradientRef getConvexGradient()
212 {
213     static float end[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.05 };
214     static float start[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.43 };
215     static NeverDestroyed<IOSGradient> gradient(start, end);
216     return &gradient.get();
217 }
218
219 static IOSGradientRef getConcaveGradient()
220 {
221     static float end[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.46 };
222     static float start[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0 };
223     static NeverDestroyed<IOSGradient> gradient(start, end);
224     return &gradient.get();
225 }
226
227 static IOSGradientRef getSliderTrackGradient()
228 {
229     static float end[4] = { 132 / 255.0, 132 / 255.0, 132 / 255.0, 1 };
230     static float start[4] = { 74 / 255.0, 77 / 255.0, 80 / 255.0, 1 };
231     static NeverDestroyed<IOSGradient> gradient(start, end);
232     return &gradient.get();
233 }
234
235 static IOSGradientRef getReadonlySliderTrackGradient()
236 {
237     static float end[4] = { 132 / 255.0, 132 / 255.0, 132 / 255.0, 0.4 };
238     static float start[4] = { 74 / 255.0, 77 / 255.0, 80 /255.0, 0.4 };
239     static NeverDestroyed<IOSGradient> gradient(start, end);
240     return &gradient.get();
241 }
242
243 static IOSGradientRef getSliderThumbOpaquePressedGradient()
244 {
245     static float end[4] = { 144 / 255.0, 144 / 255.0, 144 / 255.0, 1};
246     static float start[4] = { 55 / 255.0, 55 / 255.0, 55 / 255.0, 1 };
247     static NeverDestroyed<IOSGradient> gradient(start, end);
248     return &gradient.get();
249 }
250
251 static IOSGradientRef gradientWithName(IOSGradientType gradientType)
252 {
253     switch (gradientType) {
254     case InsetGradient:
255         return getInsetGradient();
256     case ShineGradient:
257         return getShineGradient();
258     case ShadeGradient:
259         return getShadeGradient();
260     case ConvexGradient:
261         return getConvexGradient();
262     case ConcaveGradient:
263         return getConcaveGradient();
264     case SliderTrackGradient:
265         return getSliderTrackGradient();
266     case ReadonlySliderTrackGradient:
267         return getReadonlySliderTrackGradient();
268     case SliderThumbOpaquePressedGradient:
269         return getSliderThumbOpaquePressedGradient();
270     }
271     ASSERT_NOT_REACHED();
272     return nullptr;
273 }
274
275 static void contentSizeCategoryDidChange(CFNotificationCenterRef, void*, CFStringRef name, const void*, CFDictionaryRef)
276 {
277     ASSERT_UNUSED(name, CFEqual(name, UIContentSizeCategoryDidChangeNotification));
278     WebThreadRun(^{
279         Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment();
280     });
281 }
282
283 RenderThemeIOS::RenderThemeIOS()
284 {
285     CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), this, contentSizeCategoryDidChange, UIContentSizeCategoryDidChangeNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
286 }
287
288 PassRefPtr<RenderTheme> RenderTheme::themeForPage(Page*)
289 {
290     static RenderTheme* renderTheme = RenderThemeIOS::create().leakRef();
291     return renderTheme;
292 }
293
294 PassRefPtr<RenderTheme> RenderThemeIOS::create()
295 {
296     return adoptRef(new RenderThemeIOS);
297 }
298
299 static String& _contentSizeCategory()
300 {
301     static NeverDestroyed<String> _contentSizeCategory;
302     return _contentSizeCategory.get();
303 }
304
305 CFStringRef RenderThemeIOS::contentSizeCategory()
306 {
307     if (!_contentSizeCategory().isNull())
308         return (__bridge CFStringRef)static_cast<NSString*>(_contentSizeCategory());
309     return (CFStringRef)[[getUIApplicationClass() sharedApplication] preferredContentSizeCategory];
310 }
311
312 void RenderThemeIOS::setContentSizeCategory(const String& contentSizeCategory)
313 {
314     _contentSizeCategory() = contentSizeCategory;
315 }
316
317 const Color& RenderThemeIOS::shadowColor() const
318 {
319     static Color color(0.0f, 0.0f, 0.0f, 0.7f);
320     return color;
321 }
322
323 FloatRect RenderThemeIOS::addRoundedBorderClip(const RenderObject& box, GraphicsContext* context, const IntRect& rect)
324 {
325     // To fix inner border bleeding issues <rdar://problem/9812507>, we clip to the outer border and assert that
326     // the border is opaque or transparent, unless we're checked because checked radio/checkboxes show no bleeding.
327     RenderStyle& style = box.style();
328     RoundedRect border = isChecked(box) ? style.getRoundedInnerBorderFor(rect) : style.getRoundedBorderFor(rect);
329
330     if (border.isRounded())
331         context->clipRoundedRect(FloatRoundedRect(border));
332     else
333         context->clip(border.rect());
334
335     if (isChecked(box)) {
336         ASSERT(style.visitedDependentColor(CSSPropertyBorderTopColor).alpha() % 255 == 0);
337         ASSERT(style.visitedDependentColor(CSSPropertyBorderRightColor).alpha() % 255 == 0);
338         ASSERT(style.visitedDependentColor(CSSPropertyBorderBottomColor).alpha() % 255 == 0);
339         ASSERT(style.visitedDependentColor(CSSPropertyBorderLeftColor).alpha() % 255 == 0);
340     }
341
342     return border.rect();
343 }
344
345 void RenderThemeIOS::adjustCheckboxStyle(StyleResolver&, RenderStyle& style, Element*) const
346 {
347     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
348         return;
349
350     Length length = Length(static_cast<int>(ceilf(std::max(style.fontSize(), 10))), Fixed);
351     
352     style.setWidth(length);
353     style.setHeight(length);
354 }
355
356 static CGPoint shortened(CGPoint start, CGPoint end, float width)
357 {
358     float x = end.x - start.x;
359     float y = end.y - start.y;
360     float ratio = (!x && !y) ? 0 : width / sqrtf(x * x + y * y);
361     return CGPointMake(start.x + x * ratio, start.y + y * ratio);
362 }
363
364 bool RenderThemeIOS::paintCheckboxDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
365 {
366     GraphicsContextStateSaver stateSaver(*paintInfo.context);
367     FloatRect clip = addRoundedBorderClip(box, paintInfo.context, rect);
368
369     float width = clip.width();
370     float height = clip.height();
371
372     CGContextRef cgContext = paintInfo.context->platformContext();
373     if (isChecked(box)) {
374         drawAxialGradient(cgContext, gradientWithName(ConcaveGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
375
376         static float thicknessRatio = 2 / 14.0;
377         static CGSize size = { 14.0f, 14.0f };
378         static CGPoint pathRatios[3] = {
379             { 2.5f / size.width, 7.5f / size.height },
380             { 5.5f / size.width, 10.5f / size.height },
381             { 11.5f / size.width, 2.5f / size.height }
382         };
383
384         float lineWidth = std::min(width, height) * 2.0f * thicknessRatio;
385
386         CGPoint line[3] = {
387             CGPointMake(clip.x() + width * pathRatios[0].x, clip.y() + height * pathRatios[0].y),
388             CGPointMake(clip.x() + width * pathRatios[1].x, clip.y() + height * pathRatios[1].y),
389             CGPointMake(clip.x() + width * pathRatios[2].x, clip.y() + height * pathRatios[2].y)
390         };
391         CGPoint shadow[3] = {
392             shortened(line[0], line[1], lineWidth / 4.0f),
393             line[1],
394             shortened(line[2], line[1], lineWidth / 4.0f)
395         };
396
397         paintInfo.context->setStrokeThickness(lineWidth);
398         paintInfo.context->setStrokeColor(Color(0.0f, 0.0f, 0.0f, 0.7f), ColorSpaceDeviceRGB);
399
400         paintInfo.context->drawJoinedLines(shadow, 3, true, kCGLineCapSquare);
401
402         paintInfo.context->setStrokeThickness(std::min(clip.width(), clip.height()) * thicknessRatio);
403         paintInfo.context->setStrokeColor(Color(1.0f, 1.0f, 1.0f, 240 / 255.0f), ColorSpaceDeviceRGB);
404
405         paintInfo.context->drawJoinedLines(line, 3, true);
406     } else {
407         FloatPoint bottomCenter(clip.x() + clip.width() / 2.0f, clip.maxY());
408         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
409         drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0, bottomCenter, sqrtf((width * width) / 4.0f + height * height), ExponentialInterpolation);
410     }
411
412     return false;
413 }
414
415 int RenderThemeIOS::baselinePosition(const RenderObject& renderer) const
416 {
417     if (!is<RenderBox>(renderer))
418         return 0;
419
420     const auto& box = downcast<RenderBox>(renderer);
421
422     if (box.style().appearance() == CheckboxPart || box.style().appearance() == RadioPart)
423         return box.marginTop() + box.height() - 2; // The baseline is 2px up from the bottom of the checkbox/radio in AppKit.
424     if (box.style().appearance() == MenulistPart)
425         return box.marginTop() + box.height() - 5; // This is to match AppKit. There might be a better way to calculate this though.
426     return RenderTheme::baselinePosition(box);
427 }
428
429 bool RenderThemeIOS::isControlStyled(const RenderStyle& style, const BorderData& border, const FillLayer& background, const Color& backgroundColor) const
430 {
431     // Buttons and MenulistButtons are styled if they contain a background image.
432     if (style.appearance() == PushButtonPart || style.appearance() == MenulistButtonPart)
433         return !style.visitedDependentColor(CSSPropertyBackgroundColor).alpha() || style.backgroundLayers()->hasImage();
434
435     if (style.appearance() == TextFieldPart || style.appearance() == TextAreaPart)
436         return *style.backgroundLayers() != background;
437
438     return RenderTheme::isControlStyled(style, border, background, backgroundColor);
439 }
440
441 void RenderThemeIOS::adjustRadioStyle(StyleResolver&, RenderStyle& style, Element*) const
442 {
443     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
444         return;
445
446     Length length = Length(static_cast<int>(ceilf(std::max(style.fontSize(), 10))), Fixed);
447     style.setWidth(length);
448     style.setHeight(length);
449     style.setBorderRadius(IntSize(length.value() / 2.0f, length.value() / 2.0f));
450 }
451
452 bool RenderThemeIOS::paintRadioDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
453 {
454     GraphicsContextStateSaver stateSaver(*paintInfo.context);
455     FloatRect clip = addRoundedBorderClip(box, paintInfo.context, rect);
456
457     CGContextRef cgContext = paintInfo.context->platformContext();
458     if (isChecked(box)) {
459         drawAxialGradient(cgContext, gradientWithName(ConcaveGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
460
461         // The inner circle is 6 / 14 the size of the surrounding circle, 
462         // leaving 8 / 14 around it. (8 / 14) / 2 = 2 / 7.
463
464         static float InnerInverseRatio = 2 / 7.0;
465
466         clip.inflateX(-clip.width() * InnerInverseRatio);
467         clip.inflateY(-clip.height() * InnerInverseRatio);
468
469         paintInfo.context->drawRaisedEllipse(clip, Color::white, ColorSpaceDeviceRGB, shadowColor(), ColorSpaceDeviceRGB);
470
471         FloatSize radius(clip.width() / 2.0f, clip.height() / 2.0f);
472         paintInfo.context->clipRoundedRect(FloatRoundedRect(clip, radius, radius, radius, radius));
473     }
474     FloatPoint bottomCenter(clip.x() + clip.width() / 2.0, clip.maxY());
475     drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
476     drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0, bottomCenter, std::max(clip.width(), clip.height()), ExponentialInterpolation);
477     return false;
478 }
479
480 bool RenderThemeIOS::paintTextFieldDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
481 {
482     RenderStyle& style = box.style();
483     FloatPoint point(rect.x() + style.borderLeftWidth(), rect.y() + style.borderTopWidth());
484
485     GraphicsContextStateSaver stateSaver(*paintInfo.context);
486
487     paintInfo.context->clipRoundedRect(style.getRoundedBorderFor(LayoutRect(rect)).pixelSnappedRoundedRectForPainting(box.document().deviceScaleFactor()));
488
489     // This gradient gets drawn black when printing.
490     // Do not draw the gradient if there is no visible top border.
491     bool topBorderIsInvisible = !style.hasBorder() || !style.borderTopWidth() || style.borderTopIsTransparent();
492     if (!box.view().printing() && !topBorderIsInvisible)
493         drawAxialGradient(paintInfo.context->platformContext(), gradientWithName(InsetGradient), point, FloatPoint(CGPointMake(point.x(), point.y() + 3.0f)), LinearInterpolation);
494     return false;
495 }
496
497 bool RenderThemeIOS::paintTextAreaDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
498 {
499     return paintTextFieldDecorations(box, paintInfo, rect);
500 }
501
502 const int MenuListMinHeight = 15;
503
504 const float MenuListBaseHeight = 20;
505 const float MenuListBaseFontSize = 11;
506
507 const float MenuListArrowWidth = 7;
508 const float MenuListArrowHeight = 6;
509 const float MenuListButtonPaddingRight = 19;
510
511 int RenderThemeIOS::popupInternalPaddingRight(RenderStyle& style) const
512 {
513     if (style.appearance() == MenulistButtonPart)
514         return MenuListButtonPaddingRight + style.borderTopWidth();
515     return 0;
516 }
517
518 void RenderThemeIOS::adjustRoundBorderRadius(RenderStyle& style, RenderBox& box)
519 {
520     if (style.appearance() == NoControlPart || style.backgroundLayers()->hasImage())
521         return;
522
523     // FIXME: We should not be relying on border radius for the appearance of our controls <rdar://problem/7675493>
524     Length radiusWidth(static_cast<int>(std::min(box.width(), box.height()) / 2.0), Fixed);
525     Length radiusHeight(static_cast<int>(box.height() / 2.0), Fixed);
526     style.setBorderRadius(LengthSize(radiusWidth, radiusHeight));
527 }
528
529 static void applyCommonButtonPaddingToStyle(RenderStyle& style, Element& element)
530 {
531     Document& document = element.document();
532     RefPtr<CSSPrimitiveValue> emSize = CSSPrimitiveValue::create(0.5, CSSPrimitiveValue::CSS_EMS);
533     int pixels = emSize->computeLength<int>(CSSToLengthConversionData(&style, document.renderStyle(), document.renderView(), document.frame()->pageZoomFactor()));
534     style.setPaddingBox(LengthBox(0, pixels, 0, pixels));
535 }
536
537 static void adjustSelectListButtonStyle(RenderStyle& style, Element& element)
538 {
539     // Enforce "padding: 0 0.5em".
540     applyCommonButtonPaddingToStyle(style, element);
541
542     // Enforce "line-height: normal".
543     style.setLineHeight(Length(-100.0, Percent));
544 }
545     
546 class RenderThemeMeasureTextClient : public MeasureTextClient {
547 public:
548     RenderThemeMeasureTextClient(const FontCascade& font, RenderObject& renderObject, const RenderStyle& style)
549         : m_font(font)
550         , m_renderObject(renderObject)
551         , m_style(style)
552     {
553     }
554     virtual float measureText(const String& string) const override
555     {
556         TextRun run = RenderBlock::constructTextRun(&m_renderObject, m_font, string, m_style, TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, DefaultTextRunFlags);
557         return m_font.width(run);
558     }
559 private:
560     const FontCascade& m_font;
561     RenderObject& m_renderObject;
562     const RenderStyle& m_style;
563 };
564
565 static void adjustInputElementButtonStyle(RenderStyle& style, HTMLInputElement& inputElement)
566 {
567     // Always Enforce "padding: 0 0.5em".
568     applyCommonButtonPaddingToStyle(style, inputElement);
569
570     // Don't adjust the style if the width is specified.
571     if (style.width().isFixed() && style.width().value() > 0)
572         return;
573
574     // Don't adjust for unsupported date input types.
575     DateComponents::Type dateType = inputElement.dateType();
576     if (dateType == DateComponents::Invalid || dateType == DateComponents::Week)
577         return;
578
579     // Enforce the width and set the box-sizing to content-box to not conflict with the padding.
580     FontCascade font = style.fontCascade();
581     
582     RenderObject* renderer = inputElement.renderer();
583     if (font.primaryFont().isSVGFont() && !renderer)
584         return;
585     
586     float maximumWidth = localizedDateCache().maximumWidthForDateType(dateType, font, RenderThemeMeasureTextClient(font, *renderer, style));
587
588     ASSERT(maximumWidth >= 0);
589
590     if (maximumWidth > 0) {    
591         int width = static_cast<int>(maximumWidth + MenuListButtonPaddingRight);
592         style.setWidth(Length(width, Fixed));
593         style.setBoxSizing(CONTENT_BOX);
594     }
595 }
596
597 void RenderThemeIOS::adjustMenuListButtonStyle(StyleResolver&, RenderStyle& style, Element* element) const
598 {
599     // Set the min-height to be at least MenuListMinHeight.
600     if (style.height().isAuto())
601         style.setMinHeight(Length(std::max(MenuListMinHeight, static_cast<int>(MenuListBaseHeight / MenuListBaseFontSize * style.fontDescription().computedSize())), Fixed));
602     else
603         style.setMinHeight(Length(MenuListMinHeight, Fixed));
604
605     if (!element)
606         return;
607
608     // Enforce some default styles in the case that this is a non-multiple <select> element,
609     // or a date input. We don't force these if this is just an element with
610     // "-webkit-appearance: menulist-button".
611     if (element->hasTagName(HTMLNames::selectTag) && !element->hasAttribute(HTMLNames::multipleAttr))
612         adjustSelectListButtonStyle(style, *element);
613     else if (element->hasTagName(HTMLNames::inputTag))
614         adjustInputElementButtonStyle(style, static_cast<HTMLInputElement&>(*element));
615 }
616
617 bool RenderThemeIOS::paintMenuListButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
618 {
619     RenderStyle& style = box.style();
620     float borderTopWidth = style.borderTopWidth();
621     FloatRect clip(rect.x() + style.borderLeftWidth(), rect.y() + style.borderTopWidth(), rect.width() - style.borderLeftWidth() - style.borderRightWidth(), rect.height() - style.borderTopWidth() - style.borderBottomWidth());
622     CGContextRef cgContext = paintInfo.context->platformContext();
623
624     float adjustLeft = 0.5;
625     float adjustRight = 0.5;
626     float adjustTop = 0.5;
627     float adjustBottom = 0.5;
628
629     // Paint left-hand title portion.
630     {
631         FloatRect titleClip(clip.x() - adjustLeft, clip.y() - adjustTop, clip.width() - MenuListButtonPaddingRight + adjustLeft, clip.height() + adjustTop + adjustBottom);
632
633         GraphicsContextStateSaver stateSaver(*paintInfo.context);
634
635         paintInfo.context->clipRoundedRect(FloatRoundedRect(titleClip,
636             FloatSize(valueForLength(style.borderTopLeftRadius().width(), rect.width()) - style.borderLeftWidth(), valueForLength(style.borderTopLeftRadius().height(), rect.height()) - style.borderTopWidth()), FloatSize(0, 0),
637             FloatSize(valueForLength(style.borderBottomLeftRadius().width(), rect.width()) - style.borderLeftWidth(), valueForLength(style.borderBottomLeftRadius().height(), rect.height()) - style.borderBottomWidth()), FloatSize(0, 0)));
638
639         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), titleClip.location(), FloatPoint(titleClip.x(), titleClip.maxY()), LinearInterpolation);
640         drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(titleClip.x(), titleClip.maxY()), titleClip.location(), ExponentialInterpolation);
641     }
642
643     // Draw the separator after the initial padding.
644
645     float separator = clip.maxX() - MenuListButtonPaddingRight;
646
647     box.drawLineForBoxSide(paintInfo.context, separator - borderTopWidth, clip.y(), separator, clip.maxY(), BSRight, style.visitedDependentColor(CSSPropertyBorderTopColor), style.borderTopStyle(), 0, 0);
648
649     FloatRect buttonClip(separator - adjustTop, clip.y() - adjustTop, MenuListButtonPaddingRight + adjustTop + adjustRight, clip.height() + adjustTop + adjustBottom);
650
651     // Now paint the button portion.
652     {
653         GraphicsContextStateSaver stateSaver(*paintInfo.context);
654
655         paintInfo.context->clipRoundedRect(FloatRoundedRect(buttonClip,
656             FloatSize(0, 0), FloatSize(valueForLength(style.borderTopRightRadius().width(), rect.width()) - style.borderRightWidth(), valueForLength(style.borderTopRightRadius().height(), rect.height()) - style.borderTopWidth()),
657             FloatSize(0, 0), FloatSize(valueForLength(style.borderBottomRightRadius().width(), rect.width()) - style.borderRightWidth(), valueForLength(style.borderBottomRightRadius().height(), rect.height()) - style.borderBottomWidth())));
658
659         paintInfo.context->fillRect(buttonClip, style.visitedDependentColor(CSSPropertyBorderTopColor), style.colorSpace());
660
661         drawAxialGradient(cgContext, gradientWithName(isFocused(box) && !isReadOnlyControl(box) ? ConcaveGradient : ConvexGradient), buttonClip.location(), FloatPoint(buttonClip.x(), buttonClip.maxY()), LinearInterpolation);
662     }
663
664     // Paint Indicators.
665
666     if (box.isMenuList() && downcast<HTMLSelectElement>(box.node())->multiple()) {
667         int size = 2;
668         int count = 3;
669         int padding = 3;
670
671         FloatRect ellipse(buttonClip.x() + (buttonClip.width() - count * (size + padding) + padding) / 2.0, buttonClip.maxY() - 10.0, size, size);
672
673         for (int i = 0; i < count; ++i) {
674             paintInfo.context->drawRaisedEllipse(ellipse, Color::white, ColorSpaceDeviceRGB, Color(0.0f, 0.0f, 0.0f, 0.5f), ColorSpaceDeviceRGB);
675             ellipse.move(size + padding, 0);
676         }
677     }  else {
678         float centerX = floorf(buttonClip.x() + buttonClip.width() / 2.0) - 0.5;
679         float centerY = floorf(buttonClip.y() + buttonClip.height() * 3.0 / 8.0);
680
681         FloatPoint arrow[3];
682         FloatPoint shadow[3];
683
684         arrow[0] = FloatPoint(centerX - MenuListArrowWidth / 2.0, centerY);
685         arrow[1] = FloatPoint(centerX + MenuListArrowWidth / 2.0, centerY);
686         arrow[2] = FloatPoint(centerX, centerY + MenuListArrowHeight);
687
688         shadow[0] = FloatPoint(arrow[0].x(), arrow[0].y() + 1.0f);
689         shadow[1] = FloatPoint(arrow[1].x(), arrow[1].y() + 1.0f);
690         shadow[2] = FloatPoint(arrow[2].x(), arrow[2].y() + 1.0f);
691
692         float opacity = isReadOnlyControl(box) ? 0.2 : 0.5;
693         paintInfo.context->setStrokeColor(Color(0.0f, 0.0f, 0.0f, opacity), ColorSpaceDeviceRGB);
694         paintInfo.context->setFillColor(Color(0.0f, 0.0f, 0.0f, opacity), ColorSpaceDeviceRGB);
695         paintInfo.context->drawConvexPolygon(3, shadow, true);
696
697         paintInfo.context->setStrokeColor(Color::white, ColorSpaceDeviceRGB);
698         paintInfo.context->setFillColor(Color::white, ColorSpaceDeviceRGB);
699         paintInfo.context->drawConvexPolygon(3, arrow, true);
700     }
701
702     return false;
703 }
704
705 const CGFloat kTrackThickness = 4.0;
706 const CGFloat kTrackRadius = kTrackThickness / 2.0;
707 const int kDefaultSliderThumbSize = 16;
708
709 void RenderThemeIOS::adjustSliderTrackStyle(StyleResolver& selector, RenderStyle& style, Element* element) const
710 {
711     RenderTheme::adjustSliderTrackStyle(selector, style, element);
712
713     // FIXME: We should not be relying on border radius for the appearance of our controls <rdar://problem/7675493>
714     Length radiusWidth(static_cast<int>(kTrackRadius), Fixed);
715     Length radiusHeight(static_cast<int>(kTrackRadius), Fixed);
716     style.setBorderRadius(LengthSize(radiusWidth, radiusHeight));
717 }
718
719 bool RenderThemeIOS::paintSliderTrack(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
720 {
721     IntRect trackClip = rect;
722     RenderStyle& style = box.style();
723
724     bool isHorizontal = true;
725     switch (style.appearance()) {
726     case SliderHorizontalPart:
727         isHorizontal = true;
728         // Inset slightly so the thumb covers the edge.
729         if (trackClip.width() > 2) {
730             trackClip.setWidth(trackClip.width() - 2);
731             trackClip.setX(trackClip.x() + 1);
732         }
733         trackClip.setHeight(static_cast<int>(kTrackThickness));
734         trackClip.setY(rect.y() + rect.height() / 2 - kTrackThickness / 2);
735         break;
736     case SliderVerticalPart:
737         isHorizontal = false;
738         // Inset slightly so the thumb covers the edge.
739         if (trackClip.height() > 2) {
740             trackClip.setHeight(trackClip.height() - 2);
741             trackClip.setY(trackClip.y() + 1);
742         }
743         trackClip.setWidth(kTrackThickness);
744         trackClip.setX(rect.x() + rect.width() / 2 - kTrackThickness / 2);
745         break;
746     default:
747         ASSERT_NOT_REACHED();
748     }
749
750     ASSERT(trackClip.width() >= 0);
751     ASSERT(trackClip.height() >= 0);
752     CGFloat cornerWidth = trackClip.width() < kTrackThickness ? trackClip.width() / 2.0f : kTrackRadius;
753     CGFloat cornerHeight = trackClip.height() < kTrackThickness ? trackClip.height() / 2.0f : kTrackRadius;
754
755     bool readonly = isReadOnlyControl(box);
756
757 #if ENABLE(DATALIST_ELEMENT)
758     paintSliderTicks(box, paintInfo, trackClip);
759 #endif
760
761     // Draw the track gradient.
762     {
763         GraphicsContextStateSaver stateSaver(*paintInfo.context);
764
765         IntSize cornerSize(cornerWidth, cornerHeight);
766         FloatRoundedRect innerBorder(trackClip, cornerSize, cornerSize, cornerSize, cornerSize);
767         paintInfo.context->clipRoundedRect(innerBorder);
768
769         CGContextRef cgContext = paintInfo.context->platformContext();
770         IOSGradientRef gradient = readonly ? gradientWithName(ReadonlySliderTrackGradient) : gradientWithName(SliderTrackGradient);
771         if (isHorizontal)
772             drawAxialGradient(cgContext, gradient, trackClip.location(), FloatPoint(trackClip.x(), trackClip.maxY()), LinearInterpolation);
773         else
774             drawAxialGradient(cgContext, gradient, trackClip.location(), FloatPoint(trackClip.maxX(), trackClip.y()), LinearInterpolation);
775     }
776
777     // Draw the track border.
778     {
779         GraphicsContextStateSaver stateSaver(*paintInfo.context);
780
781         CGContextRef cgContext = paintInfo.context->platformContext();
782         if (readonly)
783             paintInfo.context->setStrokeColor(Color(178, 178, 178), ColorSpaceDeviceRGB);
784         else
785             paintInfo.context->setStrokeColor(Color(76, 76, 76), ColorSpaceDeviceRGB);
786
787         RetainPtr<CGMutablePathRef> roundedRectPath = adoptCF(CGPathCreateMutable());
788         CGPathAddRoundedRect(roundedRectPath.get(), 0, trackClip, cornerWidth, cornerHeight);
789         CGContextAddPath(cgContext, roundedRectPath.get());
790         CGContextSetLineWidth(cgContext, 1);
791         CGContextStrokePath(cgContext);
792     }
793
794     return false;
795 }
796
797 void RenderThemeIOS::adjustSliderThumbSize(RenderStyle& style, Element*) const
798 {
799     if (style.appearance() != SliderThumbHorizontalPart && style.appearance() != SliderThumbVerticalPart)
800         return;
801
802     // Enforce "border-radius: 50%".
803     Length length(50.0f, Percent);
804     style.setBorderRadius(LengthSize(length, length));
805
806     // Enforce a 16x16 size if no size is provided.
807     if (style.width().isIntrinsicOrAuto() || style.height().isAuto()) {
808         Length length = Length(kDefaultSliderThumbSize, Fixed);
809         style.setWidth(length);
810         style.setHeight(length);
811     }
812 }
813
814 bool RenderThemeIOS::paintSliderThumbDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
815 {
816     GraphicsContextStateSaver stateSaver(*paintInfo.context);
817     FloatRect clip = addRoundedBorderClip(box, paintInfo.context, rect);
818
819     CGContextRef cgContext = paintInfo.context->platformContext();
820     FloatPoint bottomCenter(clip.x() + clip.width() / 2.0f, clip.maxY());
821     if (isPressed(box))
822         drawAxialGradient(cgContext, gradientWithName(SliderThumbOpaquePressedGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
823     else {
824         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
825         drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0.0f, bottomCenter, std::max(clip.width(), clip.height()), ExponentialInterpolation);
826     }
827
828     return false;
829 }
830
831 double RenderThemeIOS::animationRepeatIntervalForProgressBar(RenderProgress&) const
832 {
833     return 0;
834 }
835
836 double RenderThemeIOS::animationDurationForProgressBar(RenderProgress&) const
837 {
838     return 0;
839 }
840
841 bool RenderThemeIOS::paintProgressBar(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& rect)
842 {
843     if (!is<RenderProgress>(renderer))
844         return true;
845
846     const int progressBarHeight = 9;
847     const float verticalOffset = (rect.height() - progressBarHeight) / 2.0;
848
849     GraphicsContextStateSaver stateSaver(*paintInfo.context);
850     if (rect.width() < 10 || rect.height() < 9) {
851         // The rect is smaller than the standard progress bar. We clip to the element's rect to avoid
852         // leaking pixels outside the repaint rect.
853         paintInfo.context->clip(rect);
854     }
855
856     // 1) Draw the progress bar track.
857     // 1.1) Draw the white background with grey gradient border.
858     GraphicsContext* context = paintInfo.context;
859     context->setStrokeThickness(0.68);
860     context->setStrokeStyle(SolidStroke);
861
862     const float verticalRenderingPosition = rect.y() + verticalOffset;
863     RefPtr<Gradient> strokeGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1));
864     strokeGradient->addColorStop(0.0, Color(0x8d, 0x8d, 0x8d));
865     strokeGradient->addColorStop(0.45, Color(0xee, 0xee, 0xee));
866     strokeGradient->addColorStop(0.55, Color(0xee, 0xee, 0xee));
867     strokeGradient->addColorStop(1.0, Color(0x8d, 0x8d, 0x8d));
868     context->setStrokeGradient(strokeGradient.releaseNonNull());
869
870     ColorSpace colorSpace = renderer.style().colorSpace();
871     context->setFillColor(Color(255, 255, 255), colorSpace);
872
873     Path trackPath;
874     FloatRect trackRect(rect.x() + 0.25, verticalRenderingPosition + 0.25, rect.width() - 0.5, progressBarHeight - 0.5);
875     FloatSize roundedCornerRadius(5, 4);
876     trackPath.addRoundedRect(trackRect, roundedCornerRadius);
877     context->drawPath(trackPath);
878
879     // 1.2) Draw top gradient on the upper half. It is supposed to overlay the fill from the background and darker the stroked path.
880     FloatRect border(rect.x(), rect.y() + verticalOffset, rect.width(), progressBarHeight);
881     paintInfo.context->clipRoundedRect(FloatRoundedRect(border, roundedCornerRadius, roundedCornerRadius, roundedCornerRadius, roundedCornerRadius));
882
883     float upperGradientHeight = progressBarHeight / 2.;
884     RefPtr<Gradient> upperGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition + 0.5), FloatPoint(rect.x(), verticalRenderingPosition + upperGradientHeight - 1.5));
885     upperGradient->addColorStop(0.0, Color(133, 133, 133, 188));
886     upperGradient->addColorStop(1.0, Color(18, 18, 18, 51));
887     context->setFillGradient(upperGradient.releaseNonNull());
888
889     context->fillRect(FloatRect(rect.x(), verticalRenderingPosition, rect.width(), upperGradientHeight));
890
891     const auto& renderProgress = downcast<RenderProgress>(renderer);
892     if (renderProgress.isDeterminate()) {
893         // 2) Draw the progress bar.
894         double position = clampTo(renderProgress.position(), 0.0, 1.0);
895         double barWidth = position * rect.width();
896         RefPtr<Gradient> barGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition + 0.5), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1));
897         barGradient->addColorStop(0.0, Color(195, 217, 247));
898         barGradient->addColorStop(0.45, Color(118, 164, 228));
899         barGradient->addColorStop(0.49, Color(118, 164, 228));
900         barGradient->addColorStop(0.51, Color(36, 114, 210));
901         barGradient->addColorStop(0.55, Color(36, 114, 210));
902         barGradient->addColorStop(1.0, Color(57, 142, 244));
903         context->setFillGradient(barGradient.releaseNonNull());
904
905         RefPtr<Gradient> barStrokeGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1));
906         barStrokeGradient->addColorStop(0.0, Color(95, 107, 183));
907         barStrokeGradient->addColorStop(0.5, Color(66, 106, 174, 240));
908         barStrokeGradient->addColorStop(1.0, Color(38, 104, 166));
909         context->setStrokeGradient(barStrokeGradient.releaseNonNull());
910
911         Path barPath;
912         int left = rect.x();
913         if (!renderProgress.style().isLeftToRightDirection())
914             left = rect.maxX() - barWidth;
915         FloatRect barRect(left + 0.25, verticalRenderingPosition + 0.25, std::max(barWidth - 0.5, 0.0), progressBarHeight - 0.5);
916         barPath.addRoundedRect(barRect, roundedCornerRadius);
917         context->drawPath(barPath);
918     }
919
920     return false;
921 }
922
923 #if ENABLE(DATALIST_ELEMENT)
924 IntSize RenderThemeIOS::sliderTickSize() const
925 {
926     // FIXME: <rdar://problem/12271791> MERGEBOT: Correct values for slider tick of <input type="range"> elements (requires ENABLE_DATALIST_ELEMENT)
927     return IntSize(1, 3);
928 }
929
930 int RenderThemeIOS::sliderTickOffsetFromTrackCenter() const
931 {
932     // FIXME: <rdar://problem/12271791> MERGEBOT: Correct values for slider tick of <input type="range"> elements (requires ENABLE_DATALIST_ELEMENT)
933     return -9;
934 }
935 #endif
936
937 void RenderThemeIOS::adjustSearchFieldStyle(StyleResolver& selector, RenderStyle& style, Element* element) const
938 {
939     RenderTheme::adjustSearchFieldStyle(selector, style, element);
940
941     if (!element)
942         return;
943
944     if (!style.hasBorder())
945         return;
946
947     RenderBox* box = element->renderBox();
948     if (!box)
949         return;
950
951     adjustRoundBorderRadius(style, *box);
952 }
953
954 bool RenderThemeIOS::paintSearchFieldDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
955 {
956     return paintTextFieldDecorations(box, paintInfo, rect);
957 }
958
959 void RenderThemeIOS::adjustButtonStyle(StyleResolver& selector, RenderStyle& style, Element* element) const
960 {
961     RenderTheme::adjustButtonStyle(selector, style, element);
962
963     // Set padding: 0 1.0em; on buttons.
964     // CSSPrimitiveValue::computeLengthInt only needs the element's style to calculate em lengths.
965     // Since the element might not be in a document, just pass nullptr for the root element style
966     // and the render view.
967     RefPtr<CSSPrimitiveValue> emSize = CSSPrimitiveValue::create(1.0, CSSPrimitiveValue::CSS_EMS);
968     int pixels = emSize->computeLength<int>(CSSToLengthConversionData(&style, nullptr, nullptr, 1.0, false));
969     style.setPaddingBox(LengthBox(0, pixels, 0, pixels));
970
971     if (!element)
972         return;
973
974     RenderBox* box = element->renderBox();
975     if (!box)
976         return;
977
978     adjustRoundBorderRadius(style, *box);
979 }
980
981 bool RenderThemeIOS::paintButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
982 {
983     return paintPushButtonDecorations(box, paintInfo, rect);
984 }
985
986 bool RenderThemeIOS::paintPushButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
987 {
988     GraphicsContextStateSaver stateSaver(*paintInfo.context);
989     FloatRect clip = addRoundedBorderClip(box, paintInfo.context, rect);
990
991     CGContextRef cgContext = paintInfo.context->platformContext();
992     if (box.style().visitedDependentColor(CSSPropertyBackgroundColor).isDark())
993         drawAxialGradient(cgContext, gradientWithName(ConvexGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
994     else {
995         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
996         drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(clip.x(), clip.maxY()), clip.location(), ExponentialInterpolation);
997     }
998     return false;
999 }
1000
1001 void RenderThemeIOS::setButtonSize(RenderStyle& style) const
1002 {
1003     // If the width and height are both specified, then we have nothing to do.
1004     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
1005         return;
1006
1007     // Use the font size to determine the intrinsic width of the control.
1008     style.setHeight(Length(static_cast<int>(ControlBaseHeight / ControlBaseFontSize * style.fontDescription().computedSize()), Fixed));
1009 }
1010
1011 const int kThumbnailBorderStrokeWidth = 1;
1012 const int kThumbnailBorderCornerRadius = 1;
1013 const int kVisibleBackgroundImageWidth = 1;
1014 const int kMultipleThumbnailShrinkSize = 2;
1015
1016 bool RenderThemeIOS::paintFileUploadIconDecorations(const RenderObject&, const RenderObject& buttonRenderer, const PaintInfo& paintInfo, const IntRect& rect, Icon* icon, FileUploadDecorations fileUploadDecorations)
1017 {
1018     GraphicsContextStateSaver stateSaver(*paintInfo.context);
1019
1020     IntSize cornerSize(kThumbnailBorderCornerRadius, kThumbnailBorderCornerRadius);
1021     Color pictureFrameColor = buttonRenderer.style().visitedDependentColor(CSSPropertyBorderTopColor);
1022
1023     IntRect thumbnailPictureFrameRect = rect;
1024     IntRect thumbnailRect = rect;
1025     thumbnailRect.contract(2 * kThumbnailBorderStrokeWidth, 2 * kThumbnailBorderStrokeWidth);
1026     thumbnailRect.move(kThumbnailBorderStrokeWidth, kThumbnailBorderStrokeWidth);
1027
1028     if (fileUploadDecorations == MultipleFiles) {
1029         // Smaller thumbnails for multiple selection appearance.
1030         thumbnailPictureFrameRect.contract(kMultipleThumbnailShrinkSize, kMultipleThumbnailShrinkSize);
1031         thumbnailRect.contract(kMultipleThumbnailShrinkSize, kMultipleThumbnailShrinkSize);
1032
1033         // Background picture frame and simple background icon with a gradient matching the button.
1034         Color backgroundImageColor = Color(buttonRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor).rgb());
1035         paintInfo.context->fillRoundedRect(FloatRoundedRect(thumbnailPictureFrameRect, cornerSize, cornerSize, cornerSize, cornerSize), pictureFrameColor, ColorSpaceDeviceRGB);
1036         paintInfo.context->fillRect(thumbnailRect, backgroundImageColor, ColorSpaceDeviceRGB);
1037         {
1038             GraphicsContextStateSaver stateSaver2(*paintInfo.context);
1039             CGContextRef cgContext = paintInfo.context->platformContext();
1040             paintInfo.context->clip(thumbnailRect);
1041             if (backgroundImageColor.isDark())
1042                 drawAxialGradient(cgContext, gradientWithName(ConvexGradient), thumbnailRect.location(), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), LinearInterpolation);
1043             else {
1044                 drawAxialGradient(cgContext, gradientWithName(ShadeGradient), thumbnailRect.location(), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), LinearInterpolation);
1045                 drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), thumbnailRect.location(), ExponentialInterpolation);
1046             }
1047         }
1048
1049         // Move the rects for the Foreground picture frame and icon.
1050         int inset = kVisibleBackgroundImageWidth + kThumbnailBorderStrokeWidth;
1051         thumbnailPictureFrameRect.move(inset, inset);
1052         thumbnailRect.move(inset, inset);
1053     }
1054
1055     // Foreground picture frame and icon.
1056     paintInfo.context->fillRoundedRect(FloatRoundedRect(thumbnailPictureFrameRect, cornerSize, cornerSize, cornerSize, cornerSize), pictureFrameColor, ColorSpaceDeviceRGB);
1057     icon->paint(paintInfo.context, thumbnailRect);
1058
1059     return false;
1060 }
1061
1062 Color RenderThemeIOS::platformActiveSelectionBackgroundColor() const
1063 {
1064     return Color::transparent;
1065 }
1066
1067 Color RenderThemeIOS::platformInactiveSelectionBackgroundColor() const
1068 {
1069     return Color::transparent;
1070 }
1071
1072 bool RenderThemeIOS::shouldShowPlaceholderWhenFocused() const
1073 {
1074     return true;
1075 }
1076
1077 bool RenderThemeIOS::shouldHaveSpinButton(HTMLInputElement&) const
1078 {
1079     return false;
1080 }
1081
1082 static FontWeight fromCTFontWeight(float fontWeight)
1083 {
1084     if (fontWeight <= -0.8)
1085         return FontWeight100;
1086     else if (fontWeight <= -0.4)
1087         return FontWeight200;
1088     else if (fontWeight <= -0.2)
1089         return FontWeight300;
1090     else if (fontWeight <= 0.0)
1091         return FontWeight400;
1092     else if (fontWeight <= 0.2)
1093         return FontWeight500;
1094     else if (fontWeight <= 0.3)
1095         return FontWeight600;
1096     else if (fontWeight <= 0.4)
1097         return FontWeight700;
1098     else if (fontWeight <= 0.6)
1099         return FontWeight800;
1100     else if (fontWeight <= 0.8)
1101         return FontWeight900;
1102
1103     return FontWeightNormal;
1104 }
1105
1106 void RenderThemeIOS::systemFont(CSSValueID valueID, FontDescription& fontDescription) const
1107 {
1108     static NeverDestroyed<FontDescription> systemFont;
1109     static NeverDestroyed<FontDescription> headlineFont;
1110     static NeverDestroyed<FontDescription> bodyFont;
1111     static NeverDestroyed<FontDescription> subheadlineFont;
1112     static NeverDestroyed<FontDescription> footnoteFont;
1113     static NeverDestroyed<FontDescription> caption1Font;
1114     static NeverDestroyed<FontDescription> caption2Font;
1115     static NeverDestroyed<FontDescription> shortHeadlineFont;
1116     static NeverDestroyed<FontDescription> shortBodyFont;
1117     static NeverDestroyed<FontDescription> shortSubheadlineFont;
1118     static NeverDestroyed<FontDescription> shortFootnoteFont;
1119     static NeverDestroyed<FontDescription> shortCaption1Font;
1120     static NeverDestroyed<FontDescription> tallBodyFont;
1121 #if __IPHONE_OS_VERSION_MIN_REQUIRED > 80200
1122     static NeverDestroyed<FontDescription> title1Font;
1123     static NeverDestroyed<FontDescription> title2Font;
1124     static NeverDestroyed<FontDescription> title3Font;
1125 #endif
1126
1127     static CFStringRef userTextSize = contentSizeCategory();
1128
1129     if (userTextSize != contentSizeCategory()) {
1130         userTextSize = contentSizeCategory();
1131
1132         headlineFont.get().setIsAbsoluteSize(false);
1133         bodyFont.get().setIsAbsoluteSize(false);
1134         subheadlineFont.get().setIsAbsoluteSize(false);
1135         footnoteFont.get().setIsAbsoluteSize(false);
1136         caption1Font.get().setIsAbsoluteSize(false);
1137         caption2Font.get().setIsAbsoluteSize(false);
1138         shortHeadlineFont.get().setIsAbsoluteSize(false);
1139         shortBodyFont.get().setIsAbsoluteSize(false);
1140         shortSubheadlineFont.get().setIsAbsoluteSize(false);
1141         shortFootnoteFont.get().setIsAbsoluteSize(false);
1142         shortCaption1Font.get().setIsAbsoluteSize(false);
1143         tallBodyFont.get().setIsAbsoluteSize(false);
1144     }
1145
1146     FontDescription* cachedDesc;
1147     RetainPtr<CTFontDescriptorRef> fontDescriptor;
1148     CFStringRef textStyle;
1149     switch (valueID) {
1150     case CSSValueAppleSystemHeadline:
1151         cachedDesc = &headlineFont.get();
1152         textStyle = kCTUIFontTextStyleHeadline;
1153         if (!headlineFont.get().isAbsoluteSize())
1154             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1155         break;
1156     case CSSValueAppleSystemBody:
1157         cachedDesc = &bodyFont.get();
1158         textStyle = kCTUIFontTextStyleBody;
1159         if (!bodyFont.get().isAbsoluteSize())
1160             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1161         break;
1162 #if __IPHONE_OS_VERSION_MIN_REQUIRED > 80200
1163     case CSSValueAppleSystemTitle1:
1164         cachedDesc = &title1Font.get();
1165         textStyle = kCTUIFontTextStyleTitle1;
1166         if (!title1Font.get().isAbsoluteSize())
1167             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1168         break;
1169     case CSSValueAppleSystemTitle2:
1170         cachedDesc = &title2Font.get();
1171         textStyle = kCTUIFontTextStyleTitle2;
1172         if (!title2Font.get().isAbsoluteSize())
1173             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1174         break;
1175     case CSSValueAppleSystemTitle3:
1176         cachedDesc = &title3Font.get();
1177         textStyle = kCTUIFontTextStyleTitle3;
1178         if (!title3Font.get().isAbsoluteSize())
1179             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1180         break;
1181 #endif
1182     case CSSValueAppleSystemSubheadline:
1183         cachedDesc = &subheadlineFont.get();
1184         textStyle = kCTUIFontTextStyleSubhead;
1185         if (!subheadlineFont.get().isAbsoluteSize())
1186             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1187         break;
1188     case CSSValueAppleSystemFootnote:
1189         cachedDesc = &footnoteFont.get();
1190         textStyle = kCTUIFontTextStyleFootnote;
1191         if (!footnoteFont.get().isAbsoluteSize())
1192             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1193         break;
1194     case CSSValueAppleSystemCaption1:
1195         cachedDesc = &caption1Font.get();
1196         textStyle = kCTUIFontTextStyleCaption1;
1197         if (!caption1Font.get().isAbsoluteSize())
1198             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1199         break;
1200     case CSSValueAppleSystemCaption2:
1201         cachedDesc = &caption2Font.get();
1202         textStyle = kCTUIFontTextStyleCaption2;
1203         if (!caption2Font.get().isAbsoluteSize())
1204             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1205         break;
1206
1207     // Short version.
1208     case CSSValueAppleSystemShortHeadline:
1209         cachedDesc = &shortHeadlineFont.get();
1210         textStyle = kCTUIFontTextStyleShortHeadline;
1211         if (!shortHeadlineFont.get().isAbsoluteSize())
1212             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1213         break;
1214     case CSSValueAppleSystemShortBody:
1215         cachedDesc = &shortBodyFont.get();
1216         textStyle = kCTUIFontTextStyleShortBody;
1217         if (!shortBodyFont.get().isAbsoluteSize())
1218             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1219         break;
1220     case CSSValueAppleSystemShortSubheadline:
1221         cachedDesc = &shortSubheadlineFont.get();
1222         textStyle = kCTUIFontTextStyleShortSubhead;
1223         if (!shortSubheadlineFont.get().isAbsoluteSize())
1224             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1225         break;
1226     case CSSValueAppleSystemShortFootnote:
1227         cachedDesc = &shortFootnoteFont.get();
1228         textStyle = kCTUIFontTextStyleShortFootnote;
1229         if (!shortFootnoteFont.get().isAbsoluteSize())
1230             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1231         break;
1232     case CSSValueAppleSystemShortCaption1:
1233         cachedDesc = &shortCaption1Font.get();
1234         textStyle = kCTUIFontTextStyleShortCaption1;
1235         if (!shortCaption1Font.get().isAbsoluteSize())
1236             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1237         break;
1238
1239     // Tall version.
1240     case CSSValueAppleSystemTallBody:
1241         cachedDesc = &tallBodyFont.get();
1242         textStyle = kCTUIFontTextStyleTallBody;
1243         if (!tallBodyFont.get().isAbsoluteSize())
1244             fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, userTextSize, 0));
1245         break;
1246
1247     default:
1248         textStyle = kCTFontDescriptorTextStyleEmphasized;
1249         cachedDesc = &systemFont.get();
1250         if (!systemFont.get().isAbsoluteSize())
1251             fontDescriptor = adoptCF(CTFontDescriptorCreateForUIType(kCTFontSystemFontType, 0, nullptr));
1252     }
1253
1254     if (fontDescriptor) {
1255         RetainPtr<CTFontRef> font = adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 0, nullptr));
1256         cachedDesc->setIsAbsoluteSize(true);
1257         cachedDesc->setOneFamily(textStyle);
1258         cachedDesc->setSpecifiedSize(CTFontGetSize(font.get()));
1259         cachedDesc->setWeight(fromCTFontWeight(FontCache::weightOfCTFont(font.get())));
1260         cachedDesc->setItalic(FontItalicOff);
1261     }
1262     fontDescription = *cachedDesc;
1263 }
1264
1265 #if ENABLE(VIDEO)
1266 String RenderThemeIOS::mediaControlsStyleSheet()
1267 {
1268 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1269     if (m_mediaControlsStyleSheet.isEmpty()) {
1270         StringBuilder builder;
1271         builder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsiOS" ofType:@"css"] encoding:NSUTF8StringEncoding error:nil]);
1272         builder.append(wkGetMediaUIImageData(wkMediaUIPartOptimizedFullscreenButton));
1273         m_mediaControlsStyleSheet = builder.toString();
1274     }
1275     return m_mediaControlsStyleSheet;
1276 #else
1277     return emptyString();
1278 #endif
1279 }
1280
1281 String RenderThemeIOS::mediaControlsScript()
1282 {
1283 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1284     if (m_mediaControlsScript.isEmpty()) {
1285         StringBuilder scriptBuilder;
1286         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsLocalizedStrings" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1287         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsApple" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1288         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsiOS" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1289         m_mediaControlsScript = scriptBuilder.toString();
1290     }
1291     return m_mediaControlsScript;
1292 #else
1293     return emptyString();
1294 #endif
1295 }
1296 #endif // ENABLE(VIDEO)
1297
1298 }
1299
1300 #endif //PLATFORM(IOS)