Replace all RenderTheme::popupInternalPadding methods with a single one returning...
[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 "BitmapImage.h"
31 #import "CSSPrimitiveValue.h"
32 #import "CSSToLengthConversionData.h"
33 #import "CSSValueKeywords.h"
34 #import "CoreTextSPI.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 "Icon.h"
53 #import "LocalizedDateCache.h"
54 #import "NodeRenderStyle.h"
55 #import "Page.h"
56 #import "PaintInfo.h"
57 #import "PathUtilities.h"
58 #import "PlatformLocale.h"
59 #import "RenderAttachment.h"
60 #import "RenderObject.h"
61 #import "RenderProgress.h"
62 #import "RenderStyle.h"
63 #import "RenderThemeIOS.h"
64 #import "RenderView.h"
65 #import "SoftLinking.h"
66 #import "UIKitSPI.h"
67 #import "UTIUtilities.h"
68 #import "UserAgentScripts.h"
69 #import "UserAgentStyleSheets.h"
70 #import "WebCoreThreadRun.h"
71 #import <CoreGraphics/CoreGraphics.h>
72 #import <objc/runtime.h>
73 #import <wtf/NeverDestroyed.h>
74 #import <wtf/RefPtr.h>
75 #import <wtf/StdLibExtras.h>
76
77 SOFT_LINK_FRAMEWORK(MobileCoreServices)
78 SOFT_LINK_CLASS(MobileCoreServices, LSDocumentProxy)
79
80 SOFT_LINK_FRAMEWORK(UIKit)
81 SOFT_LINK_CLASS(UIKit, UIApplication)
82 SOFT_LINK_CLASS(UIKit, UIColor)
83 SOFT_LINK_CLASS(UIKit, UIDocumentInteractionController)
84 SOFT_LINK_CLASS(UIKit, UIImage)
85 SOFT_LINK_CONSTANT(UIKit, UIContentSizeCategoryDidChangeNotification, CFStringRef)
86 #define UIContentSizeCategoryDidChangeNotification getUIContentSizeCategoryDidChangeNotification()
87
88 @interface WebCoreRenderThemeBundle : NSObject
89 @end
90
91 @implementation WebCoreRenderThemeBundle
92 @end
93
94 namespace WebCore {
95
96 using namespace HTMLNames;
97
98 const float ControlBaseHeight = 20;
99 const float ControlBaseFontSize = 11;
100
101 struct IOSGradient {
102     float* start; // points to static float[4]
103     float* end; // points to static float[4]
104     IOSGradient(float start[4], float end[4])
105         : start(start)
106         , end(end)
107     {
108     }
109 };
110
111 typedef IOSGradient* IOSGradientRef;
112
113 enum Interpolation
114 {
115     LinearInterpolation,
116     ExponentialInterpolation
117 };
118
119 static void interpolateLinearGradient(void *info, const CGFloat *inData, CGFloat *outData)
120 {
121     IOSGradientRef gradient = static_cast<IOSGradientRef>(info);
122     float alpha = inData[0];
123     float inverse = 1.0f - alpha;
124
125     outData[0] = inverse * gradient->start[0] + alpha * gradient->end[0];
126     outData[1] = inverse * gradient->start[1] + alpha * gradient->end[1];
127     outData[2] = inverse * gradient->start[2] + alpha * gradient->end[2];
128     outData[3] = inverse * gradient->start[3] + alpha * gradient->end[3];
129 }
130
131 static void interpolateExponentialGradient(void *info, const CGFloat *inData, CGFloat *outData)
132 {
133     IOSGradientRef gradient = static_cast<IOSGradientRef>(info);
134     float a = inData[0];
135     for (int paintInfo = 0; paintInfo < 4; ++paintInfo) {
136         float end = logf(std::max(gradient->end[paintInfo], 0.01f));
137         float start = logf(std::max(gradient->start[paintInfo], 0.01f));
138         outData[paintInfo] = expf(start - (end + start) * a);
139     }
140 }
141
142 static CGFunctionRef getSharedFunctionRef(IOSGradientRef gradient, Interpolation interpolation)
143 {
144     CGFunctionRef function = nullptr;
145
146     static HashMap<IOSGradientRef, CGFunctionRef>* linearFunctionRefs;
147     static HashMap<IOSGradientRef, CGFunctionRef>* exponentialFunctionRefs;
148
149     if (interpolation == LinearInterpolation) {
150         if (!linearFunctionRefs)
151             linearFunctionRefs = new HashMap<IOSGradientRef, CGFunctionRef>;
152         else
153             function = linearFunctionRefs->get(gradient);
154     
155         if (!function) {
156             static struct CGFunctionCallbacks linearFunctionCallbacks =  { 0, interpolateLinearGradient, 0 };
157             linearFunctionRefs->set(gradient, function = CGFunctionCreate(gradient, 1, nullptr, 4, nullptr, &linearFunctionCallbacks));
158         }
159
160         return function;
161     }
162
163     if (!exponentialFunctionRefs)
164         exponentialFunctionRefs = new HashMap<IOSGradientRef, CGFunctionRef>;
165     else
166         function = exponentialFunctionRefs->get(gradient);
167
168     if (!function) {
169         static struct CGFunctionCallbacks exponentialFunctionCallbacks =  { 0, interpolateExponentialGradient, 0 };
170         exponentialFunctionRefs->set(gradient, function = CGFunctionCreate(gradient, 1, 0, 4, 0, &exponentialFunctionCallbacks));
171     }
172
173     return function;
174 }
175
176 static void drawAxialGradient(CGContextRef context, IOSGradientRef gradient, const FloatPoint& startPoint, const FloatPoint& stopPoint, Interpolation interpolation)
177 {
178     RetainPtr<CGShadingRef> shading = adoptCF(CGShadingCreateAxial(sRGBColorSpaceRef(), startPoint, stopPoint, getSharedFunctionRef(gradient, interpolation), false, false));
179     CGContextDrawShading(context, shading.get());
180 }
181
182 static void drawRadialGradient(CGContextRef context, IOSGradientRef gradient, const FloatPoint& startPoint, float startRadius, const FloatPoint& stopPoint, float stopRadius, Interpolation interpolation)
183 {
184     RetainPtr<CGShadingRef> shading = adoptCF(CGShadingCreateRadial(sRGBColorSpaceRef(), startPoint, startRadius, stopPoint, stopRadius, getSharedFunctionRef(gradient, interpolation), false, false));
185     CGContextDrawShading(context, shading.get());
186 }
187
188 enum IOSGradientType {
189     InsetGradient,
190     ShineGradient,
191     ShadeGradient,
192     ConvexGradient,
193     ConcaveGradient,
194     SliderTrackGradient,
195     ReadonlySliderTrackGradient,
196     SliderThumbOpaquePressedGradient,
197 };
198
199 static IOSGradientRef getInsetGradient()
200 {
201     static float end[4] = { 0 / 255.0, 0 / 255.0, 0 / 255.0, 0 };
202     static float start[4] = { 0 / 255.0, 0 / 255.0, 0 / 255.0, 0.2 };
203     static NeverDestroyed<IOSGradient> gradient(start, end);
204     return &gradient.get();
205 }
206
207 static IOSGradientRef getShineGradient()
208 {
209     static float end[4] = { 1, 1, 1, 0.8 };
210     static float start[4] = { 1, 1, 1, 0 };
211     static NeverDestroyed<IOSGradient> gradient(start, end);
212     return &gradient.get();
213 }
214
215 static IOSGradientRef getShadeGradient()
216 {
217     static float end[4] = { 178 / 255.0, 178 / 255.0, 178 / 255.0, 0.65 };
218     static float start[4] = { 252 / 255.0, 252 / 255.0, 252 / 255.0, 0.65 };
219     static NeverDestroyed<IOSGradient> gradient(start, end);
220     return &gradient.get();
221 }
222
223 static IOSGradientRef getConvexGradient()
224 {
225     static float end[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.05 };
226     static float start[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.43 };
227     static NeverDestroyed<IOSGradient> gradient(start, end);
228     return &gradient.get();
229 }
230
231 static IOSGradientRef getConcaveGradient()
232 {
233     static float end[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0.46 };
234     static float start[4] = { 255 / 255.0, 255 / 255.0, 255 / 255.0, 0 };
235     static NeverDestroyed<IOSGradient> gradient(start, end);
236     return &gradient.get();
237 }
238
239 static IOSGradientRef getSliderTrackGradient()
240 {
241     static float end[4] = { 132 / 255.0, 132 / 255.0, 132 / 255.0, 1 };
242     static float start[4] = { 74 / 255.0, 77 / 255.0, 80 / 255.0, 1 };
243     static NeverDestroyed<IOSGradient> gradient(start, end);
244     return &gradient.get();
245 }
246
247 static IOSGradientRef getReadonlySliderTrackGradient()
248 {
249     static float end[4] = { 132 / 255.0, 132 / 255.0, 132 / 255.0, 0.4 };
250     static float start[4] = { 74 / 255.0, 77 / 255.0, 80 /255.0, 0.4 };
251     static NeverDestroyed<IOSGradient> gradient(start, end);
252     return &gradient.get();
253 }
254
255 static IOSGradientRef getSliderThumbOpaquePressedGradient()
256 {
257     static float end[4] = { 144 / 255.0, 144 / 255.0, 144 / 255.0, 1};
258     static float start[4] = { 55 / 255.0, 55 / 255.0, 55 / 255.0, 1 };
259     static NeverDestroyed<IOSGradient> gradient(start, end);
260     return &gradient.get();
261 }
262
263 static IOSGradientRef gradientWithName(IOSGradientType gradientType)
264 {
265     switch (gradientType) {
266     case InsetGradient:
267         return getInsetGradient();
268     case ShineGradient:
269         return getShineGradient();
270     case ShadeGradient:
271         return getShadeGradient();
272     case ConvexGradient:
273         return getConvexGradient();
274     case ConcaveGradient:
275         return getConcaveGradient();
276     case SliderTrackGradient:
277         return getSliderTrackGradient();
278     case ReadonlySliderTrackGradient:
279         return getReadonlySliderTrackGradient();
280     case SliderThumbOpaquePressedGradient:
281         return getSliderThumbOpaquePressedGradient();
282     }
283     ASSERT_NOT_REACHED();
284     return nullptr;
285 }
286
287 static void contentSizeCategoryDidChange(CFNotificationCenterRef, void*, CFStringRef name, const void*, CFDictionaryRef)
288 {
289     ASSERT_UNUSED(name, CFEqual(name, UIContentSizeCategoryDidChangeNotification));
290     WebThreadRun(^{
291         Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment();
292     });
293 }
294
295 RenderThemeIOS::RenderThemeIOS()
296 {
297     CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), this, contentSizeCategoryDidChange, UIContentSizeCategoryDidChangeNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
298 }
299
300 PassRefPtr<RenderTheme> RenderTheme::themeForPage(Page*)
301 {
302     static RenderTheme& renderTheme = RenderThemeIOS::create().leakRef();
303     return &renderTheme;
304 }
305
306 Ref<RenderTheme> RenderThemeIOS::create()
307 {
308     return adoptRef(*new RenderThemeIOS);
309 }
310
311 static String& _contentSizeCategory()
312 {
313     static NeverDestroyed<String> _contentSizeCategory;
314     return _contentSizeCategory.get();
315 }
316
317 CFStringRef RenderThemeIOS::contentSizeCategory()
318 {
319     if (!_contentSizeCategory().isNull())
320         return (__bridge CFStringRef)static_cast<NSString*>(_contentSizeCategory());
321     return (CFStringRef)[[getUIApplicationClass() sharedApplication] preferredContentSizeCategory];
322 }
323
324 void RenderThemeIOS::setContentSizeCategory(const String& contentSizeCategory)
325 {
326     _contentSizeCategory() = contentSizeCategory;
327 }
328
329 const Color& RenderThemeIOS::shadowColor() const
330 {
331     static Color color(0.0f, 0.0f, 0.0f, 0.7f);
332     return color;
333 }
334
335 FloatRect RenderThemeIOS::addRoundedBorderClip(const RenderObject& box, GraphicsContext& context, const IntRect& rect)
336 {
337     // To fix inner border bleeding issues <rdar://problem/9812507>, we clip to the outer border and assert that
338     // the border is opaque or transparent, unless we're checked because checked radio/checkboxes show no bleeding.
339     RenderStyle& style = box.style();
340     RoundedRect border = isChecked(box) ? style.getRoundedInnerBorderFor(rect) : style.getRoundedBorderFor(rect);
341
342     if (border.isRounded())
343         context.clipRoundedRect(FloatRoundedRect(border));
344     else
345         context.clip(border.rect());
346
347     if (isChecked(box)) {
348         ASSERT(style.visitedDependentColor(CSSPropertyBorderTopColor).alpha() % 255 == 0);
349         ASSERT(style.visitedDependentColor(CSSPropertyBorderRightColor).alpha() % 255 == 0);
350         ASSERT(style.visitedDependentColor(CSSPropertyBorderBottomColor).alpha() % 255 == 0);
351         ASSERT(style.visitedDependentColor(CSSPropertyBorderLeftColor).alpha() % 255 == 0);
352     }
353
354     return border.rect();
355 }
356
357 void RenderThemeIOS::adjustCheckboxStyle(StyleResolver&, RenderStyle& style, Element*) const
358 {
359     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
360         return;
361
362     Length length = Length(static_cast<int>(ceilf(std::max(style.fontSize(), 10))), Fixed);
363     
364     style.setWidth(length);
365     style.setHeight(length);
366 }
367
368 static CGPoint shortened(CGPoint start, CGPoint end, float width)
369 {
370     float x = end.x - start.x;
371     float y = end.y - start.y;
372     float ratio = (!x && !y) ? 0 : width / sqrtf(x * x + y * y);
373     return CGPointMake(start.x + x * ratio, start.y + y * ratio);
374 }
375
376 static void drawJoinedLines(CGContextRef context, CGPoint points[], unsigned count, bool antialias, CGLineCap lineCap)
377 {
378     CGContextSetShouldAntialias(context, antialias);
379     CGContextBeginPath(context);
380     CGContextSetLineCap(context, lineCap);
381     CGContextMoveToPoint(context, points[0].x, points[0].y);
382     
383     for (unsigned i = 1; i < count; ++i)
384         CGContextAddLineToPoint(context, points[i].x, points[i].y);
385
386     CGContextStrokePath(context);
387 }
388
389 bool RenderThemeIOS::paintCheckboxDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
390 {
391     GraphicsContextStateSaver stateSaver(paintInfo.context());
392     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
393
394     float width = clip.width();
395     float height = clip.height();
396
397     CGContextRef cgContext = paintInfo.context().platformContext();
398     if (isChecked(box)) {
399         drawAxialGradient(cgContext, gradientWithName(ConcaveGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
400
401         static const float thicknessRatio = 2 / 14.0;
402         static const CGSize size = { 14.0f, 14.0f };
403         static const CGPoint pathRatios[3] = {
404             { 2.5f / size.width, 7.5f / size.height },
405             { 5.5f / size.width, 10.5f / size.height },
406             { 11.5f / size.width, 2.5f / size.height }
407         };
408
409         float lineWidth = std::min(width, height) * 2.0f * thicknessRatio;
410
411         CGPoint line[3] = {
412             CGPointMake(clip.x() + width * pathRatios[0].x, clip.y() + height * pathRatios[0].y),
413             CGPointMake(clip.x() + width * pathRatios[1].x, clip.y() + height * pathRatios[1].y),
414             CGPointMake(clip.x() + width * pathRatios[2].x, clip.y() + height * pathRatios[2].y)
415         };
416         CGPoint shadow[3] = {
417             shortened(line[0], line[1], lineWidth / 4.0f),
418             line[1],
419             shortened(line[2], line[1], lineWidth / 4.0f)
420         };
421
422         lineWidth = std::max<float>(lineWidth, 1);
423         CGContextSetLineWidth(cgContext, lineWidth);
424         CGContextSetStrokeColorWithColor(cgContext, cachedCGColor(Color(0.0f, 0.0f, 0.0f, 0.7f)));
425         drawJoinedLines(cgContext, shadow, 3, true, kCGLineCapSquare);
426
427         lineWidth = std::max<float>(std::min(clip.width(), clip.height()) * thicknessRatio, 1);
428         CGContextSetLineWidth(cgContext, lineWidth);
429         CGContextSetStrokeColorWithColor(cgContext, cachedCGColor(Color(1.0f, 1.0f, 1.0f, 240 / 255.0f)));
430         drawJoinedLines(cgContext, line, 3, true, kCGLineCapButt);
431     } else {
432         FloatPoint bottomCenter(clip.x() + clip.width() / 2.0f, clip.maxY());
433         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
434         drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0, bottomCenter, sqrtf((width * width) / 4.0f + height * height), ExponentialInterpolation);
435     }
436
437     return false;
438 }
439
440 int RenderThemeIOS::baselinePosition(const RenderBox& box) const
441 {
442     if (box.style().appearance() == CheckboxPart || box.style().appearance() == RadioPart)
443         return box.marginTop() + box.height() - 2; // The baseline is 2px up from the bottom of the checkbox/radio in AppKit.
444     if (box.style().appearance() == MenulistPart)
445         return box.marginTop() + box.height() - 5; // This is to match AppKit. There might be a better way to calculate this though.
446     return RenderTheme::baselinePosition(box);
447 }
448
449 bool RenderThemeIOS::isControlStyled(const RenderStyle& style, const BorderData& border, const FillLayer& background, const Color& backgroundColor) const
450 {
451     // Buttons and MenulistButtons are styled if they contain a background image.
452     if (style.appearance() == PushButtonPart || style.appearance() == MenulistButtonPart)
453         return !style.visitedDependentColor(CSSPropertyBackgroundColor).alpha() || style.backgroundLayers()->hasImage();
454
455     if (style.appearance() == TextFieldPart || style.appearance() == TextAreaPart)
456         return *style.backgroundLayers() != background;
457
458     return RenderTheme::isControlStyled(style, border, background, backgroundColor);
459 }
460
461 void RenderThemeIOS::adjustRadioStyle(StyleResolver&, RenderStyle& style, Element*) const
462 {
463     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
464         return;
465
466     Length length = Length(static_cast<int>(ceilf(std::max(style.fontSize(), 10))), Fixed);
467     style.setWidth(length);
468     style.setHeight(length);
469     style.setBorderRadius(IntSize(length.value() / 2.0f, length.value() / 2.0f));
470 }
471
472 bool RenderThemeIOS::paintRadioDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
473 {
474     GraphicsContextStateSaver stateSaver(paintInfo.context());
475     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
476
477     CGContextRef cgContext = paintInfo.context().platformContext();
478     if (isChecked(box)) {
479         drawAxialGradient(cgContext, gradientWithName(ConcaveGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
480
481         // The inner circle is 6 / 14 the size of the surrounding circle, 
482         // leaving 8 / 14 around it. (8 / 14) / 2 = 2 / 7.
483
484         static const float InnerInverseRatio = 2 / 7.0;
485
486         clip.inflateX(-clip.width() * InnerInverseRatio);
487         clip.inflateY(-clip.height() * InnerInverseRatio);
488
489         paintInfo.context().drawRaisedEllipse(clip, Color::white, shadowColor());
490
491         FloatSize radius(clip.width() / 2.0f, clip.height() / 2.0f);
492         paintInfo.context().clipRoundedRect(FloatRoundedRect(clip, radius, radius, radius, radius));
493     }
494     FloatPoint bottomCenter(clip.x() + clip.width() / 2.0, clip.maxY());
495     drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
496     drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0, bottomCenter, std::max(clip.width(), clip.height()), ExponentialInterpolation);
497     return false;
498 }
499
500 bool RenderThemeIOS::paintTextFieldDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
501 {
502     RenderStyle& style = box.style();
503     FloatPoint point(rect.x() + style.borderLeftWidth(), rect.y() + style.borderTopWidth());
504
505     GraphicsContextStateSaver stateSaver(paintInfo.context());
506
507     paintInfo.context().clipRoundedRect(style.getRoundedBorderFor(LayoutRect(rect)).pixelSnappedRoundedRectForPainting(box.document().deviceScaleFactor()));
508
509     // This gradient gets drawn black when printing.
510     // Do not draw the gradient if there is no visible top border.
511     bool topBorderIsInvisible = !style.hasBorder() || !style.borderTopWidth() || style.borderTopIsTransparent();
512     if (!box.view().printing() && !topBorderIsInvisible)
513         drawAxialGradient(paintInfo.context().platformContext(), gradientWithName(InsetGradient), point, FloatPoint(CGPointMake(point.x(), point.y() + 3.0f)), LinearInterpolation);
514     return false;
515 }
516
517 bool RenderThemeIOS::paintTextAreaDecorations(const RenderObject& box, const PaintInfo& paintInfo, const FloatRect& rect)
518 {
519     return paintTextFieldDecorations(box, paintInfo, rect);
520 }
521
522 const int MenuListMinHeight = 15;
523
524 const float MenuListBaseHeight = 20;
525 const float MenuListBaseFontSize = 11;
526
527 const float MenuListArrowWidth = 7;
528 const float MenuListArrowHeight = 6;
529 const float MenuListButtonPaddingRight = 19;
530
531 LengthBox RenderThemeIOS::popupInternalPaddingBox(const RenderStyle& style) const
532 {
533     if (style.appearance() == MenulistButtonPart)
534         return { 0, static_cast<int>(MenuListButtonPaddingRight + style.borderTopWidth()), 0, 0 };
535     return { 0, 0, 0, 0 };
536 }
537
538 void RenderThemeIOS::adjustRoundBorderRadius(RenderStyle& style, RenderBox& box)
539 {
540     if (style.appearance() == NoControlPart || style.backgroundLayers()->hasImage())
541         return;
542
543     // FIXME: We should not be relying on border radius for the appearance of our controls <rdar://problem/7675493>
544     Length radiusWidth(static_cast<int>(std::min(box.width(), box.height()) / 2.0), Fixed);
545     Length radiusHeight(static_cast<int>(box.height() / 2.0), Fixed);
546     style.setBorderRadius(LengthSize(radiusWidth, radiusHeight));
547 }
548
549 static void applyCommonButtonPaddingToStyle(RenderStyle& style, Element& element)
550 {
551     Document& document = element.document();
552     RefPtr<CSSPrimitiveValue> emSize = CSSPrimitiveValue::create(0.5, CSSPrimitiveValue::CSS_EMS);
553     int pixels = emSize->computeLength<int>(CSSToLengthConversionData(&style, document.renderStyle(), document.renderView(), document.frame()->pageZoomFactor()));
554     style.setPaddingBox(LengthBox(0, pixels, 0, pixels));
555 }
556
557 static void adjustSelectListButtonStyle(RenderStyle& style, Element& element)
558 {
559     // Enforce "padding: 0 0.5em".
560     applyCommonButtonPaddingToStyle(style, element);
561
562     // Enforce "line-height: normal".
563     style.setLineHeight(Length(-100.0, Percent));
564 }
565     
566 class RenderThemeMeasureTextClient : public MeasureTextClient {
567 public:
568     RenderThemeMeasureTextClient(const FontCascade& font, const RenderStyle& style)
569         : m_font(font)
570         , m_style(style)
571     {
572     }
573     float measureText(const String& string) const override
574     {
575         TextRun run = RenderBlock::constructTextRun(string, m_style, AllowTrailingExpansion | ForbidLeadingExpansion, DefaultTextRunFlags);
576         return m_font.width(run);
577     }
578 private:
579     const FontCascade& m_font;
580     const RenderStyle& m_style;
581 };
582
583 static void adjustInputElementButtonStyle(RenderStyle& style, HTMLInputElement& inputElement)
584 {
585     // Always Enforce "padding: 0 0.5em".
586     applyCommonButtonPaddingToStyle(style, inputElement);
587
588     // Don't adjust the style if the width is specified.
589     if (style.width().isFixed() && style.width().value() > 0)
590         return;
591
592     // Don't adjust for unsupported date input types.
593     DateComponents::Type dateType = inputElement.dateType();
594     if (dateType == DateComponents::Invalid || dateType == DateComponents::Week)
595         return;
596
597     // Enforce the width and set the box-sizing to content-box to not conflict with the padding.
598     FontCascade font = style.fontCascade();
599     
600     float maximumWidth = localizedDateCache().maximumWidthForDateType(dateType, font, RenderThemeMeasureTextClient(font, style));
601
602     ASSERT(maximumWidth >= 0);
603
604     if (maximumWidth > 0) {    
605         int width = static_cast<int>(maximumWidth + MenuListButtonPaddingRight);
606         style.setWidth(Length(width, Fixed));
607         style.setBoxSizing(CONTENT_BOX);
608     }
609 }
610
611 void RenderThemeIOS::adjustMenuListButtonStyle(StyleResolver&, RenderStyle& style, Element* element) const
612 {
613     // Set the min-height to be at least MenuListMinHeight.
614     if (style.height().isAuto())
615         style.setMinHeight(Length(std::max(MenuListMinHeight, static_cast<int>(MenuListBaseHeight / MenuListBaseFontSize * style.fontDescription().computedSize())), Fixed));
616     else
617         style.setMinHeight(Length(MenuListMinHeight, Fixed));
618
619     if (!element)
620         return;
621
622     // Enforce some default styles in the case that this is a non-multiple <select> element,
623     // or a date input. We don't force these if this is just an element with
624     // "-webkit-appearance: menulist-button".
625     if (element->hasTagName(HTMLNames::selectTag) && !element->hasAttribute(HTMLNames::multipleAttr))
626         adjustSelectListButtonStyle(style, *element);
627     else if (element->hasTagName(HTMLNames::inputTag))
628         adjustInputElementButtonStyle(style, static_cast<HTMLInputElement&>(*element));
629 }
630
631 bool RenderThemeIOS::paintMenuListButtonDecorations(const RenderBox& box, const PaintInfo& paintInfo, const FloatRect& rect)
632 {
633     RenderStyle& style = box.style();
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 left-hand title portion.
644     {
645         FloatRect titleClip(clip.x() - adjustLeft, clip.y() - adjustTop, clip.width() - MenuListButtonPaddingRight + adjustLeft, clip.height() + adjustTop + adjustBottom);
646
647         GraphicsContextStateSaver stateSaver(paintInfo.context());
648
649         paintInfo.context().clipRoundedRect(FloatRoundedRect(titleClip,
650             FloatSize(valueForLength(style.borderTopLeftRadius().width(), rect.width()) - style.borderLeftWidth(), valueForLength(style.borderTopLeftRadius().height(), rect.height()) - style.borderTopWidth()), FloatSize(0, 0),
651             FloatSize(valueForLength(style.borderBottomLeftRadius().width(), rect.width()) - style.borderLeftWidth(), valueForLength(style.borderBottomLeftRadius().height(), rect.height()) - style.borderBottomWidth()), FloatSize(0, 0)));
652
653         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), titleClip.location(), FloatPoint(titleClip.x(), titleClip.maxY()), LinearInterpolation);
654         drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(titleClip.x(), titleClip.maxY()), titleClip.location(), ExponentialInterpolation);
655     }
656
657     // Draw the separator after the initial padding.
658
659     float separator = clip.maxX() - MenuListButtonPaddingRight;
660
661     box.drawLineForBoxSide(paintInfo.context(), FloatRect(FloatPoint(separator - borderTopWidth, clip.y()), FloatPoint(separator, clip.maxY())), BSRight, style.visitedDependentColor(CSSPropertyBorderTopColor), style.borderTopStyle(), 0, 0);
662
663     FloatRect buttonClip(separator - adjustTop, clip.y() - adjustTop, MenuListButtonPaddingRight + adjustTop + adjustRight, clip.height() + adjustTop + adjustBottom);
664
665     // Now paint the button portion.
666     {
667         GraphicsContextStateSaver stateSaver(paintInfo.context());
668
669         paintInfo.context().clipRoundedRect(FloatRoundedRect(buttonClip,
670             FloatSize(0, 0), FloatSize(valueForLength(style.borderTopRightRadius().width(), rect.width()) - style.borderRightWidth(), valueForLength(style.borderTopRightRadius().height(), rect.height()) - style.borderTopWidth()),
671             FloatSize(0, 0), FloatSize(valueForLength(style.borderBottomRightRadius().width(), rect.width()) - style.borderRightWidth(), valueForLength(style.borderBottomRightRadius().height(), rect.height()) - style.borderBottomWidth())));
672
673         paintInfo.context().fillRect(buttonClip, style.visitedDependentColor(CSSPropertyBorderTopColor));
674
675         drawAxialGradient(cgContext, gradientWithName(isFocused(box) && !isReadOnlyControl(box) ? ConcaveGradient : ConvexGradient), buttonClip.location(), FloatPoint(buttonClip.x(), buttonClip.maxY()), LinearInterpolation);
676     }
677
678     // Paint Indicators.
679
680     if (box.isMenuList() && downcast<HTMLSelectElement>(box.element())->multiple()) {
681         int size = 2;
682         int count = 3;
683         int padding = 3;
684
685         FloatRect ellipse(buttonClip.x() + (buttonClip.width() - count * (size + padding) + padding) / 2.0, buttonClip.maxY() - 10.0, size, size);
686
687         for (int i = 0; i < count; ++i) {
688             paintInfo.context().drawRaisedEllipse(ellipse, Color::white, Color(0.0f, 0.0f, 0.0f, 0.5f));
689             ellipse.move(size + padding, 0);
690         }
691     }  else {
692         float centerX = floorf(buttonClip.x() + buttonClip.width() / 2.0) - 0.5;
693         float centerY = floorf(buttonClip.y() + buttonClip.height() * 3.0 / 8.0);
694
695         Vector<FloatPoint> arrow = {
696             { centerX - MenuListArrowWidth / 2, centerY },
697             { centerX + MenuListArrowWidth / 2, centerY },
698             { centerX, centerY + MenuListArrowHeight }
699         };
700
701         Vector<FloatPoint> shadow = {
702             { arrow[0].x(), arrow[0].y() + 1 },
703             { arrow[1].x(), arrow[1].y() + 1 },
704             { arrow[2].x(), arrow[2].y() + 1 }
705         };
706
707         float opacity = isReadOnlyControl(box) ? 0.2 : 0.5;
708         paintInfo.context().setStrokeColor(Color(0.0f, 0.0f, 0.0f, opacity));
709         paintInfo.context().setFillColor(Color(0.0f, 0.0f, 0.0f, opacity));
710         paintInfo.context().drawPath(Path::polygonPathFromPoints(shadow));
711
712         paintInfo.context().setStrokeColor(Color::white);
713         paintInfo.context().setFillColor(Color::white);
714         paintInfo.context().drawPath(Path::polygonPathFromPoints(arrow));
715     }
716
717     return false;
718 }
719
720 const CGFloat kTrackThickness = 4.0;
721 const CGFloat kTrackRadius = kTrackThickness / 2.0;
722 const int kDefaultSliderThumbSize = 16;
723
724 void RenderThemeIOS::adjustSliderTrackStyle(StyleResolver& selector, RenderStyle& style, Element* element) const
725 {
726     RenderTheme::adjustSliderTrackStyle(selector, style, element);
727
728     // FIXME: We should not be relying on border radius for the appearance of our controls <rdar://problem/7675493>
729     Length radiusWidth(static_cast<int>(kTrackRadius), Fixed);
730     Length radiusHeight(static_cast<int>(kTrackRadius), Fixed);
731     style.setBorderRadius(LengthSize(radiusWidth, radiusHeight));
732 }
733
734 bool RenderThemeIOS::paintSliderTrack(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
735 {
736     IntRect trackClip = rect;
737     RenderStyle& style = box.style();
738
739     bool isHorizontal = true;
740     switch (style.appearance()) {
741     case SliderHorizontalPart:
742         isHorizontal = true;
743         // Inset slightly so the thumb covers the edge.
744         if (trackClip.width() > 2) {
745             trackClip.setWidth(trackClip.width() - 2);
746             trackClip.setX(trackClip.x() + 1);
747         }
748         trackClip.setHeight(static_cast<int>(kTrackThickness));
749         trackClip.setY(rect.y() + rect.height() / 2 - kTrackThickness / 2);
750         break;
751     case SliderVerticalPart:
752         isHorizontal = false;
753         // Inset slightly so the thumb covers the edge.
754         if (trackClip.height() > 2) {
755             trackClip.setHeight(trackClip.height() - 2);
756             trackClip.setY(trackClip.y() + 1);
757         }
758         trackClip.setWidth(kTrackThickness);
759         trackClip.setX(rect.x() + rect.width() / 2 - kTrackThickness / 2);
760         break;
761     default:
762         ASSERT_NOT_REACHED();
763     }
764
765     ASSERT(trackClip.width() >= 0);
766     ASSERT(trackClip.height() >= 0);
767     CGFloat cornerWidth = trackClip.width() < kTrackThickness ? trackClip.width() / 2.0f : kTrackRadius;
768     CGFloat cornerHeight = trackClip.height() < kTrackThickness ? trackClip.height() / 2.0f : kTrackRadius;
769
770     bool readonly = isReadOnlyControl(box);
771
772 #if ENABLE(DATALIST_ELEMENT)
773     paintSliderTicks(box, paintInfo, trackClip);
774 #endif
775
776     // Draw the track gradient.
777     {
778         GraphicsContextStateSaver stateSaver(paintInfo.context());
779
780         IntSize cornerSize(cornerWidth, cornerHeight);
781         FloatRoundedRect innerBorder(trackClip, cornerSize, cornerSize, cornerSize, cornerSize);
782         paintInfo.context().clipRoundedRect(innerBorder);
783
784         CGContextRef cgContext = paintInfo.context().platformContext();
785         IOSGradientRef gradient = readonly ? gradientWithName(ReadonlySliderTrackGradient) : gradientWithName(SliderTrackGradient);
786         if (isHorizontal)
787             drawAxialGradient(cgContext, gradient, trackClip.location(), FloatPoint(trackClip.x(), trackClip.maxY()), LinearInterpolation);
788         else
789             drawAxialGradient(cgContext, gradient, trackClip.location(), FloatPoint(trackClip.maxX(), trackClip.y()), LinearInterpolation);
790     }
791
792     // Draw the track border.
793     {
794         GraphicsContextStateSaver stateSaver(paintInfo.context());
795
796         CGContextRef cgContext = paintInfo.context().platformContext();
797         if (readonly)
798             paintInfo.context().setStrokeColor(Color(178, 178, 178));
799         else
800             paintInfo.context().setStrokeColor(Color(76, 76, 76));
801
802         RetainPtr<CGMutablePathRef> roundedRectPath = adoptCF(CGPathCreateMutable());
803         CGPathAddRoundedRect(roundedRectPath.get(), 0, trackClip, cornerWidth, cornerHeight);
804         CGContextAddPath(cgContext, roundedRectPath.get());
805         CGContextSetLineWidth(cgContext, 1);
806         CGContextStrokePath(cgContext);
807     }
808
809     return false;
810 }
811
812 void RenderThemeIOS::adjustSliderThumbSize(RenderStyle& style, Element*) const
813 {
814     if (style.appearance() != SliderThumbHorizontalPart && style.appearance() != SliderThumbVerticalPart)
815         return;
816
817     // Enforce "border-radius: 50%".
818     Length length(50.0f, Percent);
819     style.setBorderRadius(LengthSize(length, length));
820
821     // Enforce a 16x16 size if no size is provided.
822     if (style.width().isIntrinsicOrAuto() || style.height().isAuto()) {
823         Length length = Length(kDefaultSliderThumbSize, Fixed);
824         style.setWidth(length);
825         style.setHeight(length);
826     }
827 }
828
829 bool RenderThemeIOS::paintSliderThumbDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
830 {
831     GraphicsContextStateSaver stateSaver(paintInfo.context());
832     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
833
834     CGContextRef cgContext = paintInfo.context().platformContext();
835     FloatPoint bottomCenter(clip.x() + clip.width() / 2.0f, clip.maxY());
836     if (isPressed(box))
837         drawAxialGradient(cgContext, gradientWithName(SliderThumbOpaquePressedGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
838     else {
839         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
840         drawRadialGradient(cgContext, gradientWithName(ShineGradient), bottomCenter, 0.0f, bottomCenter, std::max(clip.width(), clip.height()), ExponentialInterpolation);
841     }
842
843     return false;
844 }
845
846 double RenderThemeIOS::animationRepeatIntervalForProgressBar(RenderProgress&) const
847 {
848     return 0;
849 }
850
851 double RenderThemeIOS::animationDurationForProgressBar(RenderProgress&) const
852 {
853     return 0;
854 }
855
856 bool RenderThemeIOS::paintProgressBar(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& rect)
857 {
858     if (!is<RenderProgress>(renderer))
859         return true;
860
861     const int progressBarHeight = 9;
862     const float verticalOffset = (rect.height() - progressBarHeight) / 2.0;
863
864     GraphicsContextStateSaver stateSaver(paintInfo.context());
865     if (rect.width() < 10 || rect.height() < 9) {
866         // The rect is smaller than the standard progress bar. We clip to the element's rect to avoid
867         // leaking pixels outside the repaint rect.
868         paintInfo.context().clip(rect);
869     }
870
871     // 1) Draw the progress bar track.
872     // 1.1) Draw the white background with grey gradient border.
873     GraphicsContext& context = paintInfo.context();
874     context.setStrokeThickness(0.68);
875     context.setStrokeStyle(SolidStroke);
876
877     const float verticalRenderingPosition = rect.y() + verticalOffset;
878     RefPtr<Gradient> strokeGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1));
879     strokeGradient->addColorStop(0.0, Color(0x8d, 0x8d, 0x8d));
880     strokeGradient->addColorStop(0.45, Color(0xee, 0xee, 0xee));
881     strokeGradient->addColorStop(0.55, Color(0xee, 0xee, 0xee));
882     strokeGradient->addColorStop(1.0, Color(0x8d, 0x8d, 0x8d));
883     context.setStrokeGradient(strokeGradient.releaseNonNull());
884
885     context.setFillColor(Color(255, 255, 255));
886
887     Path trackPath;
888     FloatRect trackRect(rect.x() + 0.25, verticalRenderingPosition + 0.25, rect.width() - 0.5, progressBarHeight - 0.5);
889     FloatSize roundedCornerRadius(5, 4);
890     trackPath.addRoundedRect(trackRect, roundedCornerRadius);
891     context.drawPath(trackPath);
892
893     // 1.2) Draw top gradient on the upper half. It is supposed to overlay the fill from the background and darker the stroked path.
894     FloatRect border(rect.x(), rect.y() + verticalOffset, rect.width(), progressBarHeight);
895     paintInfo.context().clipRoundedRect(FloatRoundedRect(border, roundedCornerRadius, roundedCornerRadius, roundedCornerRadius, roundedCornerRadius));
896
897     float upperGradientHeight = progressBarHeight / 2.;
898     RefPtr<Gradient> upperGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition + 0.5), FloatPoint(rect.x(), verticalRenderingPosition + upperGradientHeight - 1.5));
899     upperGradient->addColorStop(0.0, Color(133, 133, 133, 188));
900     upperGradient->addColorStop(1.0, Color(18, 18, 18, 51));
901     context.setFillGradient(upperGradient.releaseNonNull());
902
903     context.fillRect(FloatRect(rect.x(), verticalRenderingPosition, rect.width(), upperGradientHeight));
904
905     const auto& renderProgress = downcast<RenderProgress>(renderer);
906     if (renderProgress.isDeterminate()) {
907         // 2) Draw the progress bar.
908         double position = clampTo(renderProgress.position(), 0.0, 1.0);
909         double barWidth = position * rect.width();
910         RefPtr<Gradient> barGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition + 0.5), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1));
911         barGradient->addColorStop(0.0, Color(195, 217, 247));
912         barGradient->addColorStop(0.45, Color(118, 164, 228));
913         barGradient->addColorStop(0.49, Color(118, 164, 228));
914         barGradient->addColorStop(0.51, Color(36, 114, 210));
915         barGradient->addColorStop(0.55, Color(36, 114, 210));
916         barGradient->addColorStop(1.0, Color(57, 142, 244));
917         context.setFillGradient(barGradient.releaseNonNull());
918
919         RefPtr<Gradient> barStrokeGradient = Gradient::create(FloatPoint(rect.x(), verticalRenderingPosition), FloatPoint(rect.x(), verticalRenderingPosition + progressBarHeight - 1));
920         barStrokeGradient->addColorStop(0.0, Color(95, 107, 183));
921         barStrokeGradient->addColorStop(0.5, Color(66, 106, 174, 240));
922         barStrokeGradient->addColorStop(1.0, Color(38, 104, 166));
923         context.setStrokeGradient(barStrokeGradient.releaseNonNull());
924
925         Path barPath;
926         int left = rect.x();
927         if (!renderProgress.style().isLeftToRightDirection())
928             left = rect.maxX() - barWidth;
929         FloatRect barRect(left + 0.25, verticalRenderingPosition + 0.25, std::max(barWidth - 0.5, 0.0), progressBarHeight - 0.5);
930         barPath.addRoundedRect(barRect, roundedCornerRadius);
931         context.drawPath(barPath);
932     }
933
934     return false;
935 }
936
937 #if ENABLE(DATALIST_ELEMENT)
938 IntSize RenderThemeIOS::sliderTickSize() const
939 {
940     // FIXME: <rdar://problem/12271791> MERGEBOT: Correct values for slider tick of <input type="range"> elements (requires ENABLE_DATALIST_ELEMENT)
941     return IntSize(1, 3);
942 }
943
944 int RenderThemeIOS::sliderTickOffsetFromTrackCenter() const
945 {
946     // FIXME: <rdar://problem/12271791> MERGEBOT: Correct values for slider tick of <input type="range"> elements (requires ENABLE_DATALIST_ELEMENT)
947     return -9;
948 }
949 #endif
950
951 void RenderThemeIOS::adjustSearchFieldStyle(StyleResolver& selector, RenderStyle& style, Element* element) const
952 {
953     RenderTheme::adjustSearchFieldStyle(selector, style, element);
954
955     if (!element)
956         return;
957
958     if (!style.hasBorder())
959         return;
960
961     RenderBox* box = element->renderBox();
962     if (!box)
963         return;
964
965     adjustRoundBorderRadius(style, *box);
966 }
967
968 bool RenderThemeIOS::paintSearchFieldDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
969 {
970     return paintTextFieldDecorations(box, paintInfo, rect);
971 }
972
973 void RenderThemeIOS::adjustButtonStyle(StyleResolver& selector, RenderStyle& style, Element* element) const
974 {
975     RenderTheme::adjustButtonStyle(selector, style, element);
976
977     // Set padding: 0 1.0em; on buttons.
978     // CSSPrimitiveValue::computeLengthInt only needs the element's style to calculate em lengths.
979     // Since the element might not be in a document, just pass nullptr for the root element style
980     // and the render view.
981     RefPtr<CSSPrimitiveValue> emSize = CSSPrimitiveValue::create(1.0, CSSPrimitiveValue::CSS_EMS);
982     int pixels = emSize->computeLength<int>(CSSToLengthConversionData(&style, nullptr, nullptr, 1.0, false));
983     style.setPaddingBox(LengthBox(0, pixels, 0, pixels));
984
985     if (!element)
986         return;
987
988     RenderBox* box = element->renderBox();
989     if (!box)
990         return;
991
992     adjustRoundBorderRadius(style, *box);
993 }
994
995 bool RenderThemeIOS::paintButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
996 {
997     return paintPushButtonDecorations(box, paintInfo, rect);
998 }
999
1000 bool RenderThemeIOS::paintPushButtonDecorations(const RenderObject& box, const PaintInfo& paintInfo, const IntRect& rect)
1001 {
1002     GraphicsContextStateSaver stateSaver(paintInfo.context());
1003     FloatRect clip = addRoundedBorderClip(box, paintInfo.context(), rect);
1004
1005     CGContextRef cgContext = paintInfo.context().platformContext();
1006     if (box.style().visitedDependentColor(CSSPropertyBackgroundColor).isDark())
1007         drawAxialGradient(cgContext, gradientWithName(ConvexGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
1008     else {
1009         drawAxialGradient(cgContext, gradientWithName(ShadeGradient), clip.location(), FloatPoint(clip.x(), clip.maxY()), LinearInterpolation);
1010         drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(clip.x(), clip.maxY()), clip.location(), ExponentialInterpolation);
1011     }
1012     return false;
1013 }
1014
1015 void RenderThemeIOS::setButtonSize(RenderStyle& style) const
1016 {
1017     // If the width and height are both specified, then we have nothing to do.
1018     if (!style.width().isIntrinsicOrAuto() && !style.height().isAuto())
1019         return;
1020
1021     // Use the font size to determine the intrinsic width of the control.
1022     style.setHeight(Length(static_cast<int>(ControlBaseHeight / ControlBaseFontSize * style.fontDescription().computedSize()), Fixed));
1023 }
1024
1025 const int kThumbnailBorderStrokeWidth = 1;
1026 const int kThumbnailBorderCornerRadius = 1;
1027 const int kVisibleBackgroundImageWidth = 1;
1028 const int kMultipleThumbnailShrinkSize = 2;
1029
1030 bool RenderThemeIOS::paintFileUploadIconDecorations(const RenderObject&, const RenderObject& buttonRenderer, const PaintInfo& paintInfo, const IntRect& rect, Icon* icon, FileUploadDecorations fileUploadDecorations)
1031 {
1032     GraphicsContextStateSaver stateSaver(paintInfo.context());
1033
1034     IntSize cornerSize(kThumbnailBorderCornerRadius, kThumbnailBorderCornerRadius);
1035     Color pictureFrameColor = buttonRenderer.style().visitedDependentColor(CSSPropertyBorderTopColor);
1036
1037     IntRect thumbnailPictureFrameRect = rect;
1038     IntRect thumbnailRect = rect;
1039     thumbnailRect.contract(2 * kThumbnailBorderStrokeWidth, 2 * kThumbnailBorderStrokeWidth);
1040     thumbnailRect.move(kThumbnailBorderStrokeWidth, kThumbnailBorderStrokeWidth);
1041
1042     if (fileUploadDecorations == MultipleFiles) {
1043         // Smaller thumbnails for multiple selection appearance.
1044         thumbnailPictureFrameRect.contract(kMultipleThumbnailShrinkSize, kMultipleThumbnailShrinkSize);
1045         thumbnailRect.contract(kMultipleThumbnailShrinkSize, kMultipleThumbnailShrinkSize);
1046
1047         // Background picture frame and simple background icon with a gradient matching the button.
1048         Color backgroundImageColor = Color(buttonRenderer.style().visitedDependentColor(CSSPropertyBackgroundColor).rgb());
1049         paintInfo.context().fillRoundedRect(FloatRoundedRect(thumbnailPictureFrameRect, cornerSize, cornerSize, cornerSize, cornerSize), pictureFrameColor);
1050         paintInfo.context().fillRect(thumbnailRect, backgroundImageColor);
1051         {
1052             GraphicsContextStateSaver stateSaver2(paintInfo.context());
1053             CGContextRef cgContext = paintInfo.context().platformContext();
1054             paintInfo.context().clip(thumbnailRect);
1055             if (backgroundImageColor.isDark())
1056                 drawAxialGradient(cgContext, gradientWithName(ConvexGradient), thumbnailRect.location(), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), LinearInterpolation);
1057             else {
1058                 drawAxialGradient(cgContext, gradientWithName(ShadeGradient), thumbnailRect.location(), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), LinearInterpolation);
1059                 drawAxialGradient(cgContext, gradientWithName(ShineGradient), FloatPoint(thumbnailRect.x(), thumbnailRect.maxY()), thumbnailRect.location(), ExponentialInterpolation);
1060             }
1061         }
1062
1063         // Move the rects for the Foreground picture frame and icon.
1064         int inset = kVisibleBackgroundImageWidth + kThumbnailBorderStrokeWidth;
1065         thumbnailPictureFrameRect.move(inset, inset);
1066         thumbnailRect.move(inset, inset);
1067     }
1068
1069     // Foreground picture frame and icon.
1070     paintInfo.context().fillRoundedRect(FloatRoundedRect(thumbnailPictureFrameRect, cornerSize, cornerSize, cornerSize, cornerSize), pictureFrameColor);
1071     icon->paint(paintInfo.context(), thumbnailRect);
1072
1073     return false;
1074 }
1075
1076 Color RenderThemeIOS::platformActiveSelectionBackgroundColor() const
1077 {
1078     return Color::transparent;
1079 }
1080
1081 Color RenderThemeIOS::platformInactiveSelectionBackgroundColor() const
1082 {
1083     return Color::transparent;
1084 }
1085
1086 bool RenderThemeIOS::shouldHaveSpinButton(HTMLInputElement&) const
1087 {
1088     return false;
1089 }
1090
1091 bool RenderThemeIOS::shouldHaveCapsLockIndicator(HTMLInputElement&) const
1092 {
1093     return false;
1094 }
1095
1096 FontCascadeDescription& RenderThemeIOS::cachedSystemFontDescription(CSSValueID valueID) const
1097 {
1098     static NeverDestroyed<FontCascadeDescription> systemFont;
1099     static NeverDestroyed<FontCascadeDescription> headlineFont;
1100     static NeverDestroyed<FontCascadeDescription> bodyFont;
1101     static NeverDestroyed<FontCascadeDescription> subheadlineFont;
1102     static NeverDestroyed<FontCascadeDescription> footnoteFont;
1103     static NeverDestroyed<FontCascadeDescription> caption1Font;
1104     static NeverDestroyed<FontCascadeDescription> caption2Font;
1105     static NeverDestroyed<FontCascadeDescription> shortHeadlineFont;
1106     static NeverDestroyed<FontCascadeDescription> shortBodyFont;
1107     static NeverDestroyed<FontCascadeDescription> shortSubheadlineFont;
1108     static NeverDestroyed<FontCascadeDescription> shortFootnoteFont;
1109     static NeverDestroyed<FontCascadeDescription> shortCaption1Font;
1110     static NeverDestroyed<FontCascadeDescription> tallBodyFont;
1111     static NeverDestroyed<FontCascadeDescription> title1Font;
1112     static NeverDestroyed<FontCascadeDescription> title2Font;
1113     static NeverDestroyed<FontCascadeDescription> title3Font;
1114
1115     static CFStringRef userTextSize = contentSizeCategory();
1116
1117     if (userTextSize != contentSizeCategory()) {
1118         userTextSize = contentSizeCategory();
1119
1120         headlineFont.get().setIsAbsoluteSize(false);
1121         bodyFont.get().setIsAbsoluteSize(false);
1122         subheadlineFont.get().setIsAbsoluteSize(false);
1123         footnoteFont.get().setIsAbsoluteSize(false);
1124         caption1Font.get().setIsAbsoluteSize(false);
1125         caption2Font.get().setIsAbsoluteSize(false);
1126         shortHeadlineFont.get().setIsAbsoluteSize(false);
1127         shortBodyFont.get().setIsAbsoluteSize(false);
1128         shortSubheadlineFont.get().setIsAbsoluteSize(false);
1129         shortFootnoteFont.get().setIsAbsoluteSize(false);
1130         shortCaption1Font.get().setIsAbsoluteSize(false);
1131         tallBodyFont.get().setIsAbsoluteSize(false);
1132     }
1133
1134     switch (valueID) {
1135     case CSSValueAppleSystemHeadline:
1136         return headlineFont;
1137     case CSSValueAppleSystemBody:
1138         return bodyFont;
1139     case CSSValueAppleSystemTitle1:
1140         return title1Font;
1141     case CSSValueAppleSystemTitle2:
1142         return title2Font;
1143     case CSSValueAppleSystemTitle3:
1144         return title3Font;
1145     case CSSValueAppleSystemSubheadline:
1146         return subheadlineFont;
1147     case CSSValueAppleSystemFootnote:
1148         return footnoteFont;
1149     case CSSValueAppleSystemCaption1:
1150         return caption1Font;
1151     case CSSValueAppleSystemCaption2:
1152         return caption2Font;
1153         // Short version.
1154     case CSSValueAppleSystemShortHeadline:
1155         return shortHeadlineFont;
1156     case CSSValueAppleSystemShortBody:
1157         return shortBodyFont;
1158     case CSSValueAppleSystemShortSubheadline:
1159         return shortSubheadlineFont;
1160     case CSSValueAppleSystemShortFootnote:
1161         return shortFootnoteFont;
1162     case CSSValueAppleSystemShortCaption1:
1163         return shortCaption1Font;
1164         // Tall version.
1165     case CSSValueAppleSystemTallBody:
1166         return tallBodyFont;
1167     default:
1168         return systemFont;
1169     }
1170 }
1171
1172 void RenderThemeIOS::updateCachedSystemFontDescription(CSSValueID valueID, FontCascadeDescription& fontDescription) const
1173 {
1174     RetainPtr<CTFontDescriptorRef> fontDescriptor;
1175     CFStringRef textStyle;
1176     switch (valueID) {
1177     case CSSValueAppleSystemHeadline:
1178         textStyle = kCTUIFontTextStyleHeadline;
1179         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1180         break;
1181     case CSSValueAppleSystemBody:
1182         textStyle = kCTUIFontTextStyleBody;
1183         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1184         break;
1185     case CSSValueAppleSystemTitle1:
1186         textStyle = kCTUIFontTextStyleTitle1;
1187         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1188         break;
1189     case CSSValueAppleSystemTitle2:
1190         textStyle = kCTUIFontTextStyleTitle2;
1191         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1192         break;
1193     case CSSValueAppleSystemTitle3:
1194         textStyle = kCTUIFontTextStyleTitle3;
1195         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1196         break;
1197     case CSSValueAppleSystemSubheadline:
1198         textStyle = kCTUIFontTextStyleSubhead;
1199         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1200         break;
1201     case CSSValueAppleSystemFootnote:
1202         textStyle = kCTUIFontTextStyleFootnote;
1203         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1204         break;
1205     case CSSValueAppleSystemCaption1:
1206         textStyle = kCTUIFontTextStyleCaption1;
1207         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1208         break;
1209     case CSSValueAppleSystemCaption2:
1210         textStyle = kCTUIFontTextStyleCaption2;
1211         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1212         break;
1213
1214     // Short version.
1215     case CSSValueAppleSystemShortHeadline:
1216         textStyle = kCTUIFontTextStyleShortHeadline;
1217         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1218         break;
1219     case CSSValueAppleSystemShortBody:
1220         textStyle = kCTUIFontTextStyleShortBody;
1221         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1222         break;
1223     case CSSValueAppleSystemShortSubheadline:
1224         textStyle = kCTUIFontTextStyleShortSubhead;
1225         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1226         break;
1227     case CSSValueAppleSystemShortFootnote:
1228         textStyle = kCTUIFontTextStyleShortFootnote;
1229         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1230         break;
1231     case CSSValueAppleSystemShortCaption1:
1232         textStyle = kCTUIFontTextStyleShortCaption1;
1233         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1234         break;
1235
1236     // Tall version.
1237     case CSSValueAppleSystemTallBody:
1238         textStyle = kCTUIFontTextStyleTallBody;
1239         fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(textStyle, contentSizeCategory(), 0));
1240         break;
1241
1242     default:
1243         textStyle = kCTFontDescriptorTextStyleEmphasized;
1244         fontDescriptor = adoptCF(CTFontDescriptorCreateForUIType(kCTFontUIFontSystem, 0, nullptr));
1245     }
1246
1247     ASSERT(fontDescriptor);
1248     RetainPtr<CTFontRef> font = adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 0, nullptr));
1249     font = preparePlatformFont(font.get(), fontDescription.textRenderingMode(), nullptr, nullptr, fontDescription.featureSettings(), fontDescription.variantSettings());
1250     fontDescription.setIsAbsoluteSize(true);
1251     fontDescription.setOneFamily(textStyle);
1252     fontDescription.setSpecifiedSize(CTFontGetSize(font.get()));
1253     fontDescription.setWeight(fontWeightFromCoreText(FontCache::weightOfCTFont(font.get())));
1254     fontDescription.setItalic(FontItalicOff);
1255 }
1256
1257 #if ENABLE(VIDEO)
1258 String RenderThemeIOS::mediaControlsStyleSheet()
1259 {
1260 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1261     if (m_mediaControlsStyleSheet.isEmpty()) {
1262         StringBuilder builder;
1263         builder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsiOS" ofType:@"css"] encoding:NSUTF8StringEncoding error:nil]);
1264         m_mediaControlsStyleSheet = builder.toString();
1265     }
1266     return m_mediaControlsStyleSheet;
1267 #else
1268     return emptyString();
1269 #endif
1270 }
1271
1272 String RenderThemeIOS::mediaControlsScript()
1273 {
1274 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1275     if (m_mediaControlsScript.isEmpty()) {
1276         StringBuilder scriptBuilder;
1277         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsLocalizedStrings" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1278         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsApple" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1279         scriptBuilder.append([NSString stringWithContentsOfFile:[[NSBundle bundleForClass:[WebCoreRenderThemeBundle class]] pathForResource:@"mediaControlsiOS" ofType:@"js"] encoding:NSUTF8StringEncoding error:nil]);
1280         m_mediaControlsScript = scriptBuilder.toString();
1281     }
1282     return m_mediaControlsScript;
1283 #else
1284     return emptyString();
1285 #endif
1286 }
1287 #endif // ENABLE(VIDEO)
1288
1289 Color RenderThemeIOS::systemColor(CSSValueID cssValueID) const
1290 {
1291     auto addResult = m_systemColorCache.add(cssValueID, Color());
1292     if (!addResult.isNewEntry)
1293         return addResult.iterator->value;
1294
1295     Color color;
1296     switch (cssValueID) {
1297     case CSSValueAppleWirelessPlaybackTargetActive:
1298         color = [getUIColorClass() systemBlueColor].CGColor;
1299         break;
1300     case CSSValueAppleSystemBlue:
1301         color = [getUIColorClass() systemBlueColor].CGColor;
1302         break;
1303     case CSSValueAppleSystemGray:
1304         color = [getUIColorClass() systemGrayColor].CGColor;
1305         break;
1306     case CSSValueAppleSystemGreen:
1307         color = [getUIColorClass() systemGreenColor].CGColor;
1308         break;
1309     case CSSValueAppleSystemOrange:
1310         color = [getUIColorClass() systemOrangeColor].CGColor;
1311         break;
1312     case CSSValueAppleSystemPink:
1313         color = [getUIColorClass() systemPinkColor].CGColor;
1314         break;
1315     case CSSValueAppleSystemRed:
1316         color = [getUIColorClass() systemRedColor].CGColor;
1317         break;
1318     case CSSValueAppleSystemYellow:
1319         color = [getUIColorClass() systemYellowColor].CGColor;
1320         break;
1321     default:
1322         break;
1323     }
1324
1325     if (!color.isValid())
1326         color = RenderTheme::systemColor(cssValueID);
1327
1328     addResult.iterator->value = color;
1329
1330     return addResult.iterator->value;
1331 }
1332
1333 #if ENABLE(ATTACHMENT_ELEMENT)
1334
1335 const CGSize attachmentSize = { 160, 119 };
1336
1337 const CGFloat attachmentBorderRadius = 16;
1338 static Color attachmentBorderColor() { return Color(204, 204, 204); }
1339
1340 static Color attachmentProgressColor() { return Color(222, 222, 222); }
1341 const CGFloat attachmentProgressBorderThickness = 3;
1342
1343 const CGFloat attachmentProgressSize = 36;
1344 const CGFloat attachmentIconSize = 48;
1345
1346 const CGFloat attachmentItemMargin = 8;
1347
1348 const CGFloat attachmentTitleMaximumWidth = 140;
1349 const CFIndex attachmentTitleMaximumLineCount = 2;
1350
1351 static RetainPtr<CTFontRef> attachmentActionFont()
1352 {
1353     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(kCTUIFontTextStyleShortFootnote, RenderThemeIOS::contentSizeCategory(), 0));
1354     RetainPtr<CTFontDescriptorRef> emphasizedFontDescriptor = adoptCF(CTFontDescriptorCreateCopyWithAttributes(fontDescriptor.get(),
1355         (CFDictionaryRef)@{
1356             (id)kCTFontDescriptorTextStyleAttribute: (id)kCTFontDescriptorTextStyleEmphasized
1357     }));
1358     return adoptCF(CTFontCreateWithFontDescriptor(emphasizedFontDescriptor.get(), 0, nullptr));
1359 }
1360
1361 static UIColor *attachmentActionColor(const RenderAttachment& attachment)
1362 {
1363     return [getUIColorClass() colorWithCGColor:cachedCGColor(attachment.style().visitedDependentColor(CSSPropertyColor))];
1364 }
1365
1366 static RetainPtr<CTFontRef> attachmentTitleFont()
1367 {
1368     RetainPtr<CTFontDescriptorRef> fontDescriptor = adoptCF(CTFontDescriptorCreateWithTextStyle(kCTUIFontTextStyleShortCaption1, RenderThemeIOS::contentSizeCategory(), 0));
1369     return adoptCF(CTFontCreateWithFontDescriptor(fontDescriptor.get(), 0, nullptr));
1370 }
1371
1372 static UIColor *attachmentTitleColor() { return [getUIColorClass() systemGrayColor]; }
1373
1374 static RetainPtr<CTFontRef> attachmentSubtitleFont() { return attachmentTitleFont(); }
1375 static UIColor *attachmentSubtitleColor() { return [getUIColorClass() systemGrayColor]; }
1376
1377 struct AttachmentInfo {
1378     explicit AttachmentInfo(const RenderAttachment&);
1379
1380     FloatRect iconRect;
1381     FloatRect attachmentRect;
1382     FloatRect progressRect;
1383
1384     BOOL hasProgress { NO };
1385     float progress;
1386
1387     RetainPtr<UIImage> icon;
1388
1389     int baseline { 0 };
1390
1391     struct LabelLine {
1392         FloatRect rect;
1393         RetainPtr<CTLineRef> line;
1394     };
1395     Vector<LabelLine> lines;
1396
1397     CGFloat contentYOrigin { 0 };
1398
1399 private:
1400     void buildTitleLines(const RenderAttachment&);
1401     void buildSingleLine(const String&, CTFontRef, UIColor *);
1402
1403     void addLine(CTLineRef);
1404 };
1405
1406 void AttachmentInfo::addLine(CTLineRef line)
1407 {
1408     CGRect lineBounds = CTLineGetBoundsWithOptions(line, kCTLineBoundsExcludeTypographicLeading);
1409     CGFloat trailingWhitespaceWidth = CTLineGetTrailingWhitespaceWidth(line);
1410     CGFloat lineWidthIgnoringTrailingWhitespace = lineBounds.size.width - trailingWhitespaceWidth;
1411     CGFloat lineHeight = CGCeiling(lineBounds.size.height + lineBounds.origin.y);
1412
1413     CGFloat xOffset = (attachmentRect.width() / 2) - (lineWidthIgnoringTrailingWhitespace / 2);
1414     LabelLine labelLine;
1415     labelLine.line = line;
1416     labelLine.rect = FloatRect(xOffset, 0, lineWidthIgnoringTrailingWhitespace, lineHeight);
1417
1418     lines.append(labelLine);
1419 }
1420
1421 void AttachmentInfo::buildTitleLines(const RenderAttachment& attachment)
1422 {
1423     RetainPtr<CTFontRef> font = attachmentTitleFont();
1424
1425     String title = attachment.attachmentElement().attachmentTitle();
1426     if (title.isEmpty())
1427         return;
1428
1429     NSDictionary *textAttributes = @{
1430         (id)kCTFontAttributeName: (id)font.get(),
1431         (id)kCTForegroundColorAttributeName: attachmentTitleColor()
1432     };
1433     RetainPtr<NSAttributedString> attributedTitle = adoptNS([[NSAttributedString alloc] initWithString:title attributes:textAttributes]);
1434     RetainPtr<CTFramesetterRef> titleFramesetter = adoptCF(CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributedTitle.get()));
1435
1436     CFRange fitRange;
1437     CGSize titleTextSize = CTFramesetterSuggestFrameSizeWithConstraints(titleFramesetter.get(), CFRangeMake(0, 0), nullptr, CGSizeMake(attachmentTitleMaximumWidth, CGFLOAT_MAX), &fitRange);
1438
1439     RetainPtr<CGPathRef> titlePath = adoptCF(CGPathCreateWithRect(CGRectMake(0, 0, titleTextSize.width, titleTextSize.height), nullptr));
1440     RetainPtr<CTFrameRef> titleFrame = adoptCF(CTFramesetterCreateFrame(titleFramesetter.get(), fitRange, titlePath.get(), nullptr));
1441
1442     CFArrayRef ctLines = CTFrameGetLines(titleFrame.get());
1443     CFIndex lineCount = CFArrayGetCount(ctLines);
1444     if (!lineCount)
1445         return;
1446
1447     // Lay out and record the first (attachmentTitleMaximumLineCount - 1) lines.
1448     CFIndex lineIndex = 0;
1449     for (; lineIndex < std::min(attachmentTitleMaximumLineCount - 1, lineCount); ++lineIndex) {
1450         CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
1451         addLine(line);
1452     }
1453
1454     if (lineIndex == lineCount)
1455         return;
1456
1457     // We had text that didn't fit in the first (attachmentTitleMaximumLineCount - 1) lines.
1458     // Combine it into one last line, and center-truncate it.
1459     CTLineRef firstRemainingLine = (CTLineRef)CFArrayGetValueAtIndex(ctLines, lineIndex);
1460     CFIndex remainingRangeStart = CTLineGetStringRange(firstRemainingLine).location;
1461     NSRange remainingRange = NSMakeRange(remainingRangeStart, [attributedTitle length] - remainingRangeStart);
1462     NSAttributedString *remainingString = [attributedTitle attributedSubstringFromRange:remainingRange];
1463     RetainPtr<CTLineRef> remainingLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)remainingString));
1464     RetainPtr<NSAttributedString> ellipsisString = adoptNS([[NSAttributedString alloc] initWithString:@"\u2026" attributes:textAttributes]);
1465     RetainPtr<CTLineRef> ellipsisLine = adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)ellipsisString.get()));
1466     RetainPtr<CTLineRef> truncatedLine = adoptCF(CTLineCreateTruncatedLine(remainingLine.get(), attachmentTitleMaximumWidth, kCTLineTruncationMiddle, ellipsisLine.get()));
1467
1468     if (!truncatedLine)
1469         truncatedLine = remainingLine;
1470
1471     addLine(truncatedLine.get());
1472 }
1473
1474 void AttachmentInfo::buildSingleLine(const String& text, CTFontRef font, UIColor *color)
1475 {
1476     if (text.isEmpty())
1477         return;
1478
1479     NSDictionary *textAttributes = @{
1480         (id)kCTFontAttributeName: (id)font,
1481         (id)kCTForegroundColorAttributeName: color
1482     };
1483     RetainPtr<NSAttributedString> attributedText = adoptNS([[NSAttributedString alloc] initWithString:text attributes:textAttributes]);
1484
1485     addLine(adoptCF(CTLineCreateWithAttributedString((CFAttributedStringRef)attributedText.get())).get());
1486 }
1487
1488 static BOOL getAttachmentProgress(const RenderAttachment& attachment, float& progress)
1489 {
1490     String progressString = attachment.attachmentElement().fastGetAttribute(progressAttr);
1491     if (progressString.isEmpty())
1492         return NO;
1493     bool validProgress;
1494     progress = std::max<float>(std::min<float>(progressString.toFloat(&validProgress), 1), 0);
1495     return validProgress;
1496 }
1497
1498 static RetainPtr<UIImage> iconForAttachment(const RenderAttachment& attachment, FloatSize& size)
1499 {
1500     String MIMEType = attachment.attachmentElement().attachmentType();
1501
1502     String fileName;
1503     if (File* file = attachment.attachmentElement().file())
1504         fileName = file->name();
1505
1506     if (fileName.isEmpty())
1507         fileName = attachment.attachmentElement().attachmentTitle();
1508
1509     RetainPtr<UIImage> result;
1510
1511     RetainPtr<UIDocumentInteractionController> documentInteractionController = adoptNS([[getUIDocumentInteractionControllerClass() alloc] init]);
1512     [documentInteractionController setName:fileName];
1513     [documentInteractionController setUTI:static_cast<NSString *>(mimeTypeFromUTITree(MIMEType.createCFString().get()).get())];
1514
1515     NSArray *icons = [documentInteractionController icons];
1516     if (!icons.count)
1517         return nil;
1518
1519     result = icons.lastObject;
1520
1521     BOOL useHeightForClosestMatch = [result size].height > [result size].width;
1522     CGFloat bestMatchRatio = -1;
1523
1524     for (UIImage *icon in icons) {
1525         CGFloat iconSize = useHeightForClosestMatch ? icon.size.height : icon.size.width;
1526
1527         CGFloat matchRatio = (attachmentIconSize / iconSize) - 1.0f;
1528         if (matchRatio < 0.3f) {
1529             matchRatio = CGFAbs(matchRatio);
1530             if ((bestMatchRatio == -1) || (matchRatio < bestMatchRatio)) {
1531                 result = icon;
1532                 bestMatchRatio = matchRatio;
1533             }
1534         }
1535     }
1536
1537     CGFloat iconAspect = [result size].width / [result size].height;
1538     size = largestRectWithAspectRatioInsideRect(iconAspect, FloatRect(0, 0, attachmentIconSize, attachmentIconSize)).size();
1539
1540     return result;
1541 }
1542
1543 AttachmentInfo::AttachmentInfo(const RenderAttachment& attachment)
1544 {
1545     attachmentRect = FloatRect(0, 0, attachmentSize.width, attachmentSize.height);
1546
1547     hasProgress = getAttachmentProgress(attachment, progress);
1548
1549     String action = attachment.attachmentElement().fastGetAttribute(actionAttr);
1550     String subtitle = attachment.attachmentElement().fastGetAttribute(subtitleAttr);
1551
1552     CGFloat yOffset = 0;
1553
1554     if (hasProgress) {
1555         progressRect = FloatRect((attachmentRect.width() / 2) - (attachmentProgressSize / 2), 0, attachmentProgressSize, attachmentProgressSize);
1556         yOffset += attachmentProgressSize + attachmentItemMargin;
1557     }
1558
1559     if (action.isEmpty() && !hasProgress) {
1560         FloatSize iconSize;
1561         icon = iconForAttachment(attachment, iconSize);
1562         if (icon) {
1563             iconRect = FloatRect(FloatPoint((attachmentRect.width() / 2) - (iconSize.width() / 2), 0), iconSize);
1564             yOffset += iconRect.height() + attachmentItemMargin;
1565         }
1566     } else
1567         buildSingleLine(action, attachmentActionFont().get(), attachmentActionColor(attachment));
1568
1569     buildTitleLines(attachment);
1570     buildSingleLine(subtitle, attachmentSubtitleFont().get(), attachmentSubtitleColor());
1571
1572     if (!lines.isEmpty()) {
1573         for (auto& line : lines) {
1574             line.rect.setY(yOffset);
1575             yOffset += line.rect.height() + attachmentItemMargin;
1576         }
1577     }
1578
1579     yOffset -= attachmentItemMargin;
1580
1581     contentYOrigin = (attachmentRect.height() / 2) - (yOffset / 2);
1582 }
1583
1584 LayoutSize RenderThemeIOS::attachmentIntrinsicSize(const RenderAttachment&) const
1585 {
1586     return LayoutSize(FloatSize(attachmentSize));
1587 }
1588
1589 int RenderThemeIOS::attachmentBaseline(const RenderAttachment& attachment) const
1590 {
1591     AttachmentInfo info(attachment);
1592     return info.baseline;
1593 }
1594
1595 static void paintAttachmentIcon(GraphicsContext& context, AttachmentInfo& info)
1596 {
1597     if (!info.icon)
1598         return;
1599
1600     RefPtr<Image> iconImage = BitmapImage::create([info.icon CGImage]);
1601     if (!iconImage)
1602         return;
1603
1604     context.drawImage(*iconImage, info.iconRect);
1605 }
1606
1607 static void paintAttachmentText(GraphicsContext& context, AttachmentInfo& info)
1608 {
1609     for (const auto& line : info.lines) {
1610         GraphicsContextStateSaver saver(context);
1611
1612         context.translate(toFloatSize(line.rect.minXMaxYCorner()));
1613         context.scale(FloatSize(1, -1));
1614
1615         CGContextSetTextMatrix(context.platformContext(), CGAffineTransformIdentity);
1616         CTLineDraw(line.line.get(), context.platformContext());
1617     }
1618 }
1619
1620 static void paintAttachmentProgress(GraphicsContext& context, AttachmentInfo& info)
1621 {
1622     GraphicsContextStateSaver saver(context);
1623
1624     context.setStrokeThickness(attachmentProgressBorderThickness);
1625     context.setStrokeColor(attachmentProgressColor());
1626     context.setFillColor(attachmentProgressColor());
1627     context.strokeEllipse(info.progressRect);
1628
1629     FloatPoint center = info.progressRect.center();
1630
1631     Path progressPath;
1632     progressPath.moveTo(center);
1633     progressPath.addLineTo(FloatPoint(center.x(), info.progressRect.y()));
1634     progressPath.addArc(center, info.progressRect.width() / 2, -M_PI_2, info.progress * 2 * M_PI - M_PI_2, 0);
1635     progressPath.closeSubpath();
1636     context.fillPath(progressPath);
1637 }
1638
1639 static void paintAttachmentBorder(GraphicsContext& context, AttachmentInfo& info)
1640 {
1641     Path borderPath;
1642     borderPath.addRoundedRect(info.attachmentRect, FloatSize(attachmentBorderRadius, attachmentBorderRadius));
1643     context.setStrokeColor(attachmentBorderColor());
1644     context.setStrokeThickness(1);
1645     context.strokePath(borderPath);
1646 }
1647
1648 bool RenderThemeIOS::paintAttachment(const RenderObject& renderer, const PaintInfo& paintInfo, const IntRect& paintRect)
1649 {
1650     if (!is<RenderAttachment>(renderer))
1651         return false;
1652
1653     const RenderAttachment& attachment = downcast<RenderAttachment>(renderer);
1654
1655     AttachmentInfo info(attachment);
1656
1657     GraphicsContext& context = paintInfo.context();
1658     GraphicsContextStateSaver saver(context);
1659
1660     context.translate(toFloatSize(paintRect.location()));
1661
1662     paintAttachmentBorder(context, info);
1663
1664     context.translate(FloatSize(0, info.contentYOrigin));
1665
1666     if (info.hasProgress)
1667         paintAttachmentProgress(context, info);
1668     else if (info.icon)
1669         paintAttachmentIcon(context, info);
1670
1671     paintAttachmentText(context, info);
1672
1673     return true;
1674 }
1675
1676 #endif // ENABLE(ATTACHMENT_ELEMENT)
1677
1678 } // namespace WebCore
1679
1680 #endif //PLATFORM(IOS)