Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / canvas / CanvasRenderingContext2D.cpp
1 /*
2  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
3  * Copyright (C) 2008, 2010 Nokia Corporation and/or its subsidiary(-ies)
4  * Copyright (C) 2007 Alp Toker <alp@atoker.com>
5  * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
6  * Copyright (C) 2008 Dirk Schulze <krit@webkit.org>
7  * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
8  * Copyright (C) 2012, 2013 Intel Corporation. All rights reserved.
9  * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
21  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
28  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "config.h"
34 #include "core/html/canvas/CanvasRenderingContext2D.h"
35
36 #include "bindings/core/v8/ExceptionMessages.h"
37 #include "bindings/core/v8/ExceptionState.h"
38 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
39 #include "core/CSSPropertyNames.h"
40 #include "core/css/CSSFontSelector.h"
41 #include "core/css/parser/BisonCSSParser.h"
42 #include "core/css/StylePropertySet.h"
43 #include "core/css/resolver/StyleResolver.h"
44 #include "core/dom/ExceptionCode.h"
45 #include "core/dom/StyleEngine.h"
46 #include "core/events/Event.h"
47 #include "core/fetch/ImageResource.h"
48 #include "core/frame/ImageBitmap.h"
49 #include "core/html/HTMLCanvasElement.h"
50 #include "core/html/HTMLImageElement.h"
51 #include "core/html/HTMLMediaElement.h"
52 #include "core/html/HTMLVideoElement.h"
53 #include "core/html/ImageData.h"
54 #include "core/html/TextMetrics.h"
55 #include "core/html/canvas/CanvasGradient.h"
56 #include "core/html/canvas/CanvasPattern.h"
57 #include "core/html/canvas/CanvasStyle.h"
58 #include "core/html/canvas/Path2D.h"
59 #include "core/rendering/RenderImage.h"
60 #include "core/rendering/RenderLayer.h"
61 #include "core/rendering/RenderTheme.h"
62 #include "platform/fonts/FontCache.h"
63 #include "platform/geometry/FloatQuad.h"
64 #include "platform/graphics/DrawLooperBuilder.h"
65 #include "platform/graphics/GraphicsContextStateSaver.h"
66 #include "platform/text/TextRun.h"
67 #include "wtf/CheckedArithmetic.h"
68 #include "wtf/MathExtras.h"
69 #include "wtf/OwnPtr.h"
70 #include "wtf/Uint8ClampedArray.h"
71 #include "wtf/text/StringBuilder.h"
72
73 namespace blink {
74
75 static const int defaultFontSize = 10;
76 static const char defaultFontFamily[] = "sans-serif";
77 static const char defaultFont[] = "10px sans-serif";
78 static const double TryRestoreContextInterval = 0.5;
79 static const unsigned MaxTryRestoreContextAttempts = 4;
80
81 static bool contextLostRestoredEventsEnabled()
82 {
83     return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled();
84 }
85
86 CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement* canvas, const Canvas2DContextAttributes* attrs, bool usesCSSCompatibilityParseMode)
87     : CanvasRenderingContext(canvas)
88     , m_usesCSSCompatibilityParseMode(usesCSSCompatibilityParseMode)
89     , m_hasAlpha(!attrs || attrs->alpha())
90     , m_isContextLost(false)
91     , m_contextRestorable(true)
92     , m_storageMode(!attrs ? PersistentStorage : attrs->parsedStorage())
93     , m_tryRestoreContextAttemptCount(0)
94     , m_dispatchContextLostEventTimer(this, &CanvasRenderingContext2D::dispatchContextLostEvent)
95     , m_dispatchContextRestoredEventTimer(this, &CanvasRenderingContext2D::dispatchContextRestoredEvent)
96     , m_tryRestoreContextEventTimer(this, &CanvasRenderingContext2D::tryRestoreContextEvent)
97 {
98     m_stateStack.append(adoptPtrWillBeNoop(new State()));
99     ScriptWrappable::init(this);
100 }
101
102 void CanvasRenderingContext2D::unwindStateStack()
103 {
104     if (size_t stackSize = m_stateStack.size()) {
105         if (GraphicsContext* context = canvas()->existingDrawingContext()) {
106             while (--stackSize)
107                 context->restore();
108         }
109     }
110 }
111
112 CanvasRenderingContext2D::~CanvasRenderingContext2D()
113 {
114 }
115
116 void CanvasRenderingContext2D::validateStateStack()
117 {
118 #if ENABLE(ASSERT)
119     GraphicsContext* context = canvas()->existingDrawingContext();
120     if (context && !context->contextDisabled())
121         ASSERT(context->saveCount() == m_stateStack.size());
122 #endif
123 }
124
125 bool CanvasRenderingContext2D::isAccelerated() const
126 {
127     if (!canvas()->hasImageBuffer())
128         return false;
129     GraphicsContext* context = drawingContext();
130     return context && context->isAccelerated();
131 }
132
133 bool CanvasRenderingContext2D::isContextLost() const
134 {
135     return m_isContextLost;
136 }
137
138 void CanvasRenderingContext2D::loseContext()
139 {
140     if (m_isContextLost)
141         return;
142     m_isContextLost = true;
143     m_dispatchContextLostEventTimer.startOneShot(0, FROM_HERE);
144 }
145
146 void CanvasRenderingContext2D::restoreContext()
147 {
148     if (!m_contextRestorable)
149         return;
150     // This code path is for restoring from an eviction
151     // Restoring from surface failure is handled internally
152     ASSERT(m_isContextLost && !canvas()->hasImageBuffer());
153
154     if (canvas()->buffer()) {
155         if (contextLostRestoredEventsEnabled()) {
156             m_dispatchContextRestoredEventTimer.startOneShot(0, FROM_HERE);
157         } else {
158             // legacy synchronous context restoration.
159             reset();
160             m_isContextLost = false;
161         }
162     }
163 }
164
165 void CanvasRenderingContext2D::trace(Visitor* visitor)
166 {
167 #if ENABLE(OILPAN)
168     visitor->trace(m_stateStack);
169     visitor->trace(m_fetchedFonts);
170     visitor->trace(m_hitRegionManager);
171 #endif
172     CanvasRenderingContext::trace(visitor);
173 }
174
175 void CanvasRenderingContext2D::dispatchContextLostEvent(Timer<CanvasRenderingContext2D>*)
176 {
177     if (contextLostRestoredEventsEnabled()) {
178         RefPtrWillBeRawPtr<Event> event = Event::createCancelable(EventTypeNames::contextlost);
179         canvas()->dispatchEvent(event);
180         if (event->defaultPrevented()) {
181             m_contextRestorable = false;
182         }
183     }
184
185     // If an image buffer is present, it means the context was not lost due to
186     // an eviction, but rather due to a surface failure (gpu context lost?)
187     if (m_contextRestorable && canvas()->hasImageBuffer()) {
188         m_tryRestoreContextAttemptCount = 0;
189         m_tryRestoreContextEventTimer.startRepeating(TryRestoreContextInterval, FROM_HERE);
190     }
191 }
192
193 void CanvasRenderingContext2D::tryRestoreContextEvent(Timer<CanvasRenderingContext2D>* timer)
194 {
195     if (!m_isContextLost) {
196         // Canvas was already restored (possibly thanks to a resize), so stop trying.
197         m_tryRestoreContextEventTimer.stop();
198         return;
199     }
200     if (canvas()->hasImageBuffer() && canvas()->buffer()->restoreSurface()) {
201         m_tryRestoreContextEventTimer.stop();
202         dispatchContextRestoredEvent(0);
203     }
204
205     if (++m_tryRestoreContextAttemptCount > MaxTryRestoreContextAttempts)
206         canvas()->discardImageBuffer();
207
208     if (!canvas()->hasImageBuffer()) {
209         // final attempt: allocate a brand new image buffer instead of restoring
210         timer->stop();
211         if (canvas()->buffer())
212             dispatchContextRestoredEvent(0);
213     }
214 }
215
216 void CanvasRenderingContext2D::dispatchContextRestoredEvent(Timer<CanvasRenderingContext2D>*)
217 {
218     if (!m_isContextLost)
219         return;
220     reset();
221     m_isContextLost = false;
222     if (contextLostRestoredEventsEnabled()) {
223         RefPtrWillBeRawPtr<Event> event(Event::create(EventTypeNames::contextrestored));
224         canvas()->dispatchEvent(event);
225     }
226 }
227
228 void CanvasRenderingContext2D::reset()
229 {
230     validateStateStack();
231     unwindStateStack();
232     m_stateStack.resize(1);
233     m_stateStack.first() = adoptPtrWillBeNoop(new State());
234     m_path.clear();
235     validateStateStack();
236 }
237
238 // Important: Several of these properties are also stored in GraphicsContext's
239 // StrokeData. The default values that StrokeData uses may not the same values
240 // that the canvas 2d spec specifies. Make sure to sync the initial state of the
241 // GraphicsContext in HTMLCanvasElement::createImageBuffer()!
242 CanvasRenderingContext2D::State::State()
243     : m_unrealizedSaveCount(0)
244     , m_strokeStyle(CanvasStyle::createFromRGBA(Color::black))
245     , m_fillStyle(CanvasStyle::createFromRGBA(Color::black))
246     , m_lineWidth(1)
247     , m_lineCap(ButtCap)
248     , m_lineJoin(MiterJoin)
249     , m_miterLimit(10)
250     , m_shadowBlur(0)
251     , m_shadowColor(Color::transparent)
252     , m_globalAlpha(1)
253     , m_globalComposite(CompositeSourceOver)
254     , m_globalBlend(blink::WebBlendModeNormal)
255     , m_invertibleCTM(true)
256     , m_lineDashOffset(0)
257     , m_imageSmoothingEnabled(true)
258     , m_textAlign(StartTextAlign)
259     , m_textBaseline(AlphabeticTextBaseline)
260     , m_unparsedFont(defaultFont)
261     , m_realizedFont(false)
262     , m_hasClip(false)
263 {
264 }
265
266 CanvasRenderingContext2D::State::State(const State& other)
267     : CSSFontSelectorClient()
268     , m_unrealizedSaveCount(other.m_unrealizedSaveCount)
269     , m_unparsedStrokeColor(other.m_unparsedStrokeColor)
270     , m_unparsedFillColor(other.m_unparsedFillColor)
271     , m_strokeStyle(other.m_strokeStyle)
272     , m_fillStyle(other.m_fillStyle)
273     , m_lineWidth(other.m_lineWidth)
274     , m_lineCap(other.m_lineCap)
275     , m_lineJoin(other.m_lineJoin)
276     , m_miterLimit(other.m_miterLimit)
277     , m_shadowOffset(other.m_shadowOffset)
278     , m_shadowBlur(other.m_shadowBlur)
279     , m_shadowColor(other.m_shadowColor)
280     , m_globalAlpha(other.m_globalAlpha)
281     , m_globalComposite(other.m_globalComposite)
282     , m_globalBlend(other.m_globalBlend)
283     , m_transform(other.m_transform)
284     , m_invertibleCTM(other.m_invertibleCTM)
285     , m_lineDashOffset(other.m_lineDashOffset)
286     , m_imageSmoothingEnabled(other.m_imageSmoothingEnabled)
287     , m_textAlign(other.m_textAlign)
288     , m_textBaseline(other.m_textBaseline)
289     , m_unparsedFont(other.m_unparsedFont)
290     , m_font(other.m_font)
291     , m_realizedFont(other.m_realizedFont)
292     , m_hasClip(other.m_hasClip)
293 {
294     if (m_realizedFont)
295         static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this);
296 }
297
298 CanvasRenderingContext2D::State& CanvasRenderingContext2D::State::operator=(const State& other)
299 {
300     if (this == &other)
301         return *this;
302
303 #if !ENABLE(OILPAN)
304     if (m_realizedFont)
305         static_cast<CSSFontSelector*>(m_font.fontSelector())->unregisterForInvalidationCallbacks(this);
306 #endif
307
308     m_unrealizedSaveCount = other.m_unrealizedSaveCount;
309     m_unparsedStrokeColor = other.m_unparsedStrokeColor;
310     m_unparsedFillColor = other.m_unparsedFillColor;
311     m_strokeStyle = other.m_strokeStyle;
312     m_fillStyle = other.m_fillStyle;
313     m_lineWidth = other.m_lineWidth;
314     m_lineCap = other.m_lineCap;
315     m_lineJoin = other.m_lineJoin;
316     m_miterLimit = other.m_miterLimit;
317     m_shadowOffset = other.m_shadowOffset;
318     m_shadowBlur = other.m_shadowBlur;
319     m_shadowColor = other.m_shadowColor;
320     m_globalAlpha = other.m_globalAlpha;
321     m_globalComposite = other.m_globalComposite;
322     m_globalBlend = other.m_globalBlend;
323     m_transform = other.m_transform;
324     m_invertibleCTM = other.m_invertibleCTM;
325     m_imageSmoothingEnabled = other.m_imageSmoothingEnabled;
326     m_textAlign = other.m_textAlign;
327     m_textBaseline = other.m_textBaseline;
328     m_unparsedFont = other.m_unparsedFont;
329     m_font = other.m_font;
330     m_realizedFont = other.m_realizedFont;
331     m_hasClip = other.m_hasClip;
332
333     if (m_realizedFont)
334         static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this);
335
336     return *this;
337 }
338
339 CanvasRenderingContext2D::State::~State()
340 {
341 #if !ENABLE(OILPAN)
342     if (m_realizedFont)
343         static_cast<CSSFontSelector*>(m_font.fontSelector())->unregisterForInvalidationCallbacks(this);
344 #endif
345 }
346
347 void CanvasRenderingContext2D::State::fontsNeedUpdate(CSSFontSelector* fontSelector)
348 {
349     ASSERT_ARG(fontSelector, fontSelector == m_font.fontSelector());
350     ASSERT(m_realizedFont);
351
352     m_font.update(fontSelector);
353 }
354
355 void CanvasRenderingContext2D::State::trace(Visitor* visitor)
356 {
357     visitor->trace(m_strokeStyle);
358     visitor->trace(m_fillStyle);
359     CSSFontSelectorClient::trace(visitor);
360 }
361
362 void CanvasRenderingContext2D::realizeSaves()
363 {
364     validateStateStack();
365     if (state().m_unrealizedSaveCount) {
366         ASSERT(m_stateStack.size() >= 1);
367         // Reduce the current state's unrealized count by one now,
368         // to reflect the fact we are saving one state.
369         m_stateStack.last()->m_unrealizedSaveCount--;
370         m_stateStack.append(adoptPtrWillBeNoop(new State(state())));
371         // Set the new state's unrealized count to 0, because it has no outstanding saves.
372         // We need to do this explicitly because the copy constructor and operator= used
373         // by the Vector operations copy the unrealized count from the previous state (in
374         // turn necessary to support correct resizing and unwinding of the stack).
375         m_stateStack.last()->m_unrealizedSaveCount = 0;
376         GraphicsContext* context = drawingContext();
377         if (context)
378             context->save();
379         validateStateStack();
380     }
381 }
382
383 void CanvasRenderingContext2D::restore()
384 {
385     validateStateStack();
386     if (state().m_unrealizedSaveCount) {
387         // We never realized the save, so just record that it was unnecessary.
388         --m_stateStack.last()->m_unrealizedSaveCount;
389         return;
390     }
391     ASSERT(m_stateStack.size() >= 1);
392     if (m_stateStack.size() <= 1)
393         return;
394     m_path.transform(state().m_transform);
395     m_stateStack.removeLast();
396     m_path.transform(state().m_transform.inverse());
397     GraphicsContext* c = drawingContext();
398     if (c)
399         c->restore();
400     validateStateStack();
401 }
402
403 CanvasStyle* CanvasRenderingContext2D::strokeStyle() const
404 {
405     return state().m_strokeStyle.get();
406 }
407
408 void CanvasRenderingContext2D::setStrokeStyle(PassRefPtrWillBeRawPtr<CanvasStyle> prpStyle)
409 {
410     RefPtrWillBeRawPtr<CanvasStyle> style = prpStyle;
411
412     if (!style)
413         return;
414
415     if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentColor(*style))
416         return;
417
418     if (style->isCurrentColor()) {
419         if (style->hasOverrideAlpha())
420             style = CanvasStyle::createFromRGBA(colorWithOverrideAlpha(currentColor(canvas()), style->overrideAlpha()));
421         else
422             style = CanvasStyle::createFromRGBA(currentColor(canvas()));
423     } else if (canvas()->originClean() && style->canvasPattern() && !style->canvasPattern()->originClean()) {
424         canvas()->setOriginTainted();
425     }
426
427     realizeSaves();
428     modifiableState().m_strokeStyle = style.release();
429     GraphicsContext* c = drawingContext();
430     if (!c)
431         return;
432     state().m_strokeStyle->applyStrokeColor(c);
433     modifiableState().m_unparsedStrokeColor = String();
434 }
435
436 CanvasStyle* CanvasRenderingContext2D::fillStyle() const
437 {
438     return state().m_fillStyle.get();
439 }
440
441 void CanvasRenderingContext2D::setFillStyle(PassRefPtrWillBeRawPtr<CanvasStyle> prpStyle)
442 {
443     RefPtrWillBeRawPtr<CanvasStyle> style = prpStyle;
444
445     if (!style)
446         return;
447
448     if (state().m_fillStyle && state().m_fillStyle->isEquivalentColor(*style))
449         return;
450
451     if (style->isCurrentColor()) {
452         if (style->hasOverrideAlpha())
453             style = CanvasStyle::createFromRGBA(colorWithOverrideAlpha(currentColor(canvas()), style->overrideAlpha()));
454         else
455             style = CanvasStyle::createFromRGBA(currentColor(canvas()));
456     } else if (canvas()->originClean() && style->canvasPattern() && !style->canvasPattern()->originClean()) {
457         canvas()->setOriginTainted();
458     }
459
460     realizeSaves();
461     modifiableState().m_fillStyle = style.release();
462     GraphicsContext* c = drawingContext();
463     if (!c)
464         return;
465     state().m_fillStyle->applyFillColor(c);
466     modifiableState().m_unparsedFillColor = String();
467 }
468
469 float CanvasRenderingContext2D::lineWidth() const
470 {
471     return state().m_lineWidth;
472 }
473
474 void CanvasRenderingContext2D::setLineWidth(float width)
475 {
476     if (!(std::isfinite(width) && width > 0))
477         return;
478     if (state().m_lineWidth == width)
479         return;
480     realizeSaves();
481     modifiableState().m_lineWidth = width;
482     GraphicsContext* c = drawingContext();
483     if (!c)
484         return;
485     c->setStrokeThickness(width);
486 }
487
488 String CanvasRenderingContext2D::lineCap() const
489 {
490     return lineCapName(state().m_lineCap);
491 }
492
493 void CanvasRenderingContext2D::setLineCap(const String& s)
494 {
495     LineCap cap;
496     if (!parseLineCap(s, cap))
497         return;
498     if (state().m_lineCap == cap)
499         return;
500     realizeSaves();
501     modifiableState().m_lineCap = cap;
502     GraphicsContext* c = drawingContext();
503     if (!c)
504         return;
505     c->setLineCap(cap);
506 }
507
508 String CanvasRenderingContext2D::lineJoin() const
509 {
510     return lineJoinName(state().m_lineJoin);
511 }
512
513 void CanvasRenderingContext2D::setLineJoin(const String& s)
514 {
515     LineJoin join;
516     if (!parseLineJoin(s, join))
517         return;
518     if (state().m_lineJoin == join)
519         return;
520     realizeSaves();
521     modifiableState().m_lineJoin = join;
522     GraphicsContext* c = drawingContext();
523     if (!c)
524         return;
525     c->setLineJoin(join);
526 }
527
528 float CanvasRenderingContext2D::miterLimit() const
529 {
530     return state().m_miterLimit;
531 }
532
533 void CanvasRenderingContext2D::setMiterLimit(float limit)
534 {
535     if (!(std::isfinite(limit) && limit > 0))
536         return;
537     if (state().m_miterLimit == limit)
538         return;
539     realizeSaves();
540     modifiableState().m_miterLimit = limit;
541     GraphicsContext* c = drawingContext();
542     if (!c)
543         return;
544     c->setMiterLimit(limit);
545 }
546
547 float CanvasRenderingContext2D::shadowOffsetX() const
548 {
549     return state().m_shadowOffset.width();
550 }
551
552 void CanvasRenderingContext2D::setShadowOffsetX(float x)
553 {
554     if (!std::isfinite(x))
555         return;
556     if (state().m_shadowOffset.width() == x)
557         return;
558     realizeSaves();
559     modifiableState().m_shadowOffset.setWidth(x);
560     applyShadow();
561 }
562
563 float CanvasRenderingContext2D::shadowOffsetY() const
564 {
565     return state().m_shadowOffset.height();
566 }
567
568 void CanvasRenderingContext2D::setShadowOffsetY(float y)
569 {
570     if (!std::isfinite(y))
571         return;
572     if (state().m_shadowOffset.height() == y)
573         return;
574     realizeSaves();
575     modifiableState().m_shadowOffset.setHeight(y);
576     applyShadow();
577 }
578
579 float CanvasRenderingContext2D::shadowBlur() const
580 {
581     return state().m_shadowBlur;
582 }
583
584 void CanvasRenderingContext2D::setShadowBlur(float blur)
585 {
586     if (!(std::isfinite(blur) && blur >= 0))
587         return;
588     if (state().m_shadowBlur == blur)
589         return;
590     realizeSaves();
591     modifiableState().m_shadowBlur = blur;
592     applyShadow();
593 }
594
595 String CanvasRenderingContext2D::shadowColor() const
596 {
597     return Color(state().m_shadowColor).serialized();
598 }
599
600 void CanvasRenderingContext2D::setShadowColor(const String& color)
601 {
602     RGBA32 rgba;
603     if (!parseColorOrCurrentColor(rgba, color, canvas()))
604         return;
605     if (state().m_shadowColor == rgba)
606         return;
607     realizeSaves();
608     modifiableState().m_shadowColor = rgba;
609     applyShadow();
610 }
611
612 const Vector<float>& CanvasRenderingContext2D::getLineDash() const
613 {
614     return state().m_lineDash;
615 }
616
617 static bool lineDashSequenceIsValid(const Vector<float>& dash)
618 {
619     for (size_t i = 0; i < dash.size(); i++) {
620         if (!std::isfinite(dash[i]) || dash[i] < 0)
621             return false;
622     }
623     return true;
624 }
625
626 void CanvasRenderingContext2D::setLineDash(const Vector<float>& dash)
627 {
628     if (!lineDashSequenceIsValid(dash))
629         return;
630
631     realizeSaves();
632     modifiableState().m_lineDash = dash;
633     // Spec requires the concatenation of two copies the dash list when the
634     // number of elements is odd
635     if (dash.size() % 2)
636         modifiableState().m_lineDash.appendVector(dash);
637
638     applyLineDash();
639 }
640
641 float CanvasRenderingContext2D::lineDashOffset() const
642 {
643     return state().m_lineDashOffset;
644 }
645
646 void CanvasRenderingContext2D::setLineDashOffset(float offset)
647 {
648     if (!std::isfinite(offset) || state().m_lineDashOffset == offset)
649         return;
650
651     realizeSaves();
652     modifiableState().m_lineDashOffset = offset;
653     applyLineDash();
654 }
655
656 void CanvasRenderingContext2D::applyLineDash() const
657 {
658     GraphicsContext* c = drawingContext();
659     if (!c)
660         return;
661     DashArray convertedLineDash(state().m_lineDash.size());
662     for (size_t i = 0; i < state().m_lineDash.size(); ++i)
663         convertedLineDash[i] = static_cast<DashArrayElement>(state().m_lineDash[i]);
664     c->setLineDash(convertedLineDash, state().m_lineDashOffset);
665 }
666
667 float CanvasRenderingContext2D::globalAlpha() const
668 {
669     return state().m_globalAlpha;
670 }
671
672 void CanvasRenderingContext2D::setGlobalAlpha(float alpha)
673 {
674     if (!(alpha >= 0 && alpha <= 1))
675         return;
676     if (state().m_globalAlpha == alpha)
677         return;
678     realizeSaves();
679     modifiableState().m_globalAlpha = alpha;
680     GraphicsContext* c = drawingContext();
681     if (!c)
682         return;
683     c->setAlphaAsFloat(alpha);
684 }
685
686 String CanvasRenderingContext2D::globalCompositeOperation() const
687 {
688     return compositeOperatorName(state().m_globalComposite, state().m_globalBlend);
689 }
690
691 void CanvasRenderingContext2D::setGlobalCompositeOperation(const String& operation)
692 {
693     CompositeOperator op = CompositeSourceOver;
694     blink::WebBlendMode blendMode = blink::WebBlendModeNormal;
695     if (!parseCompositeAndBlendOperator(operation, op, blendMode))
696         return;
697     if ((state().m_globalComposite == op) && (state().m_globalBlend == blendMode))
698         return;
699     realizeSaves();
700     modifiableState().m_globalComposite = op;
701     modifiableState().m_globalBlend = blendMode;
702     GraphicsContext* c = drawingContext();
703     if (!c)
704         return;
705     c->setCompositeOperation(op, blendMode);
706 }
707
708 void CanvasRenderingContext2D::setCurrentTransform(PassRefPtr<SVGMatrixTearOff> passMatrixTearOff)
709 {
710     RefPtr<SVGMatrixTearOff> matrixTearOff = passMatrixTearOff;
711     const AffineTransform& transform = matrixTearOff->value();
712     setTransform(transform.a(), transform.b(), transform.c(), transform.d(), transform.e(), transform.f());
713 }
714
715 void CanvasRenderingContext2D::scale(float sx, float sy)
716 {
717     GraphicsContext* c = drawingContext();
718     if (!c)
719         return;
720     if (!state().m_invertibleCTM)
721         return;
722
723     if (!std::isfinite(sx) | !std::isfinite(sy))
724         return;
725
726     AffineTransform newTransform = state().m_transform;
727     newTransform.scaleNonUniform(sx, sy);
728     if (state().m_transform == newTransform)
729         return;
730
731     realizeSaves();
732
733     if (!newTransform.isInvertible()) {
734         modifiableState().m_invertibleCTM = false;
735         return;
736     }
737
738     modifiableState().m_transform = newTransform;
739     c->scale(sx, sy);
740     m_path.transform(AffineTransform().scaleNonUniform(1.0 / sx, 1.0 / sy));
741 }
742
743 void CanvasRenderingContext2D::rotate(float angleInRadians)
744 {
745     GraphicsContext* c = drawingContext();
746     if (!c)
747         return;
748     if (!state().m_invertibleCTM)
749         return;
750
751     if (!std::isfinite(angleInRadians))
752         return;
753
754     AffineTransform newTransform = state().m_transform;
755     newTransform.rotateRadians(angleInRadians);
756     if (state().m_transform == newTransform)
757         return;
758
759     realizeSaves();
760
761     if (!newTransform.isInvertible()) {
762         modifiableState().m_invertibleCTM = false;
763         return;
764     }
765
766     modifiableState().m_transform = newTransform;
767     c->rotate(angleInRadians);
768     m_path.transform(AffineTransform().rotateRadians(-angleInRadians));
769 }
770
771 void CanvasRenderingContext2D::translate(float tx, float ty)
772 {
773     GraphicsContext* c = drawingContext();
774     if (!c)
775         return;
776     if (!state().m_invertibleCTM)
777         return;
778
779     if (!std::isfinite(tx) | !std::isfinite(ty))
780         return;
781
782     AffineTransform newTransform = state().m_transform;
783     newTransform.translate(tx, ty);
784     if (state().m_transform == newTransform)
785         return;
786
787     realizeSaves();
788
789     if (!newTransform.isInvertible()) {
790         modifiableState().m_invertibleCTM = false;
791         return;
792     }
793
794     modifiableState().m_transform = newTransform;
795     c->translate(tx, ty);
796     m_path.transform(AffineTransform().translate(-tx, -ty));
797 }
798
799 void CanvasRenderingContext2D::transform(float m11, float m12, float m21, float m22, float dx, float dy)
800 {
801     GraphicsContext* c = drawingContext();
802     if (!c)
803         return;
804     if (!state().m_invertibleCTM)
805         return;
806
807     if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
808         return;
809
810     AffineTransform transform(m11, m12, m21, m22, dx, dy);
811     AffineTransform newTransform = state().m_transform * transform;
812     if (state().m_transform == newTransform)
813         return;
814
815     realizeSaves();
816
817     modifiableState().m_transform = newTransform;
818     if (!newTransform.isInvertible()) {
819         modifiableState().m_invertibleCTM = false;
820         return;
821     }
822
823     c->concatCTM(transform);
824     m_path.transform(transform.inverse());
825 }
826
827 void CanvasRenderingContext2D::resetTransform()
828 {
829     GraphicsContext* c = drawingContext();
830     if (!c)
831         return;
832
833     AffineTransform ctm = state().m_transform;
834     bool invertibleCTM = state().m_invertibleCTM;
835     // It is possible that CTM is identity while CTM is not invertible.
836     // When CTM becomes non-invertible, realizeSaves() can make CTM identity.
837     if (ctm.isIdentity() && invertibleCTM)
838         return;
839
840     realizeSaves();
841     // resetTransform() resolves the non-invertible CTM state.
842     modifiableState().m_transform.makeIdentity();
843     modifiableState().m_invertibleCTM = true;
844     c->setCTM(canvas()->baseTransform());
845
846     if (invertibleCTM)
847         m_path.transform(ctm);
848     // When else, do nothing because all transform methods didn't update m_path when CTM became non-invertible.
849     // It means that resetTransform() restores m_path just before CTM became non-invertible.
850 }
851
852 void CanvasRenderingContext2D::setTransform(float m11, float m12, float m21, float m22, float dx, float dy)
853 {
854     GraphicsContext* c = drawingContext();
855     if (!c)
856         return;
857
858     if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
859         return;
860
861     resetTransform();
862     transform(m11, m12, m21, m22, dx, dy);
863 }
864
865 void CanvasRenderingContext2D::setStrokeColor(const String& color)
866 {
867     if (color == state().m_unparsedStrokeColor)
868         return;
869     realizeSaves();
870     setStrokeStyle(CanvasStyle::createFromString(color));
871     modifiableState().m_unparsedStrokeColor = color;
872 }
873
874 void CanvasRenderingContext2D::setStrokeColor(float grayLevel)
875 {
876     if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, 1.0f))
877         return;
878     setStrokeStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, 1.0f));
879 }
880
881 void CanvasRenderingContext2D::setStrokeColor(const String& color, float alpha)
882 {
883     setStrokeStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha));
884 }
885
886 void CanvasRenderingContext2D::setStrokeColor(float grayLevel, float alpha)
887 {
888     if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
889         return;
890     setStrokeStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, alpha));
891 }
892
893 void CanvasRenderingContext2D::setStrokeColor(float r, float g, float b, float a)
894 {
895     if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentRGBA(r, g, b, a))
896         return;
897     setStrokeStyle(CanvasStyle::createFromRGBAChannels(r, g, b, a));
898 }
899
900 void CanvasRenderingContext2D::setStrokeColor(float c, float m, float y, float k, float a)
901 {
902     if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentCMYKA(c, m, y, k, a))
903         return;
904     setStrokeStyle(CanvasStyle::createFromCMYKAChannels(c, m, y, k, a));
905 }
906
907 void CanvasRenderingContext2D::setFillColor(const String& color)
908 {
909     if (color == state().m_unparsedFillColor)
910         return;
911     realizeSaves();
912     setFillStyle(CanvasStyle::createFromString(color));
913     modifiableState().m_unparsedFillColor = color;
914 }
915
916 void CanvasRenderingContext2D::setFillColor(float grayLevel)
917 {
918     if (state().m_fillStyle && state().m_fillStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, 1.0f))
919         return;
920     setFillStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, 1.0f));
921 }
922
923 void CanvasRenderingContext2D::setFillColor(const String& color, float alpha)
924 {
925     setFillStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha));
926 }
927
928 void CanvasRenderingContext2D::setFillColor(float grayLevel, float alpha)
929 {
930     if (state().m_fillStyle && state().m_fillStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
931         return;
932     setFillStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, alpha));
933 }
934
935 void CanvasRenderingContext2D::setFillColor(float r, float g, float b, float a)
936 {
937     if (state().m_fillStyle && state().m_fillStyle->isEquivalentRGBA(r, g, b, a))
938         return;
939     setFillStyle(CanvasStyle::createFromRGBAChannels(r, g, b, a));
940 }
941
942 void CanvasRenderingContext2D::setFillColor(float c, float m, float y, float k, float a)
943 {
944     if (state().m_fillStyle && state().m_fillStyle->isEquivalentCMYKA(c, m, y, k, a))
945         return;
946     setFillStyle(CanvasStyle::createFromCMYKAChannels(c, m, y, k, a));
947 }
948
949 void CanvasRenderingContext2D::beginPath()
950 {
951     m_path.clear();
952 }
953
954 static bool validateRectForCanvas(float& x, float& y, float& width, float& height)
955 {
956     if (!std::isfinite(x) | !std::isfinite(y) | !std::isfinite(width) | !std::isfinite(height))
957         return false;
958
959     if (!width && !height)
960         return false;
961
962     if (width < 0) {
963         width = -width;
964         x -= width;
965     }
966
967     if (height < 0) {
968         height = -height;
969         y -= height;
970     }
971
972     return true;
973 }
974
975 static bool isFullCanvasCompositeMode(CompositeOperator op)
976 {
977     // See 4.8.11.1.3 Compositing
978     // CompositeSourceAtop and CompositeDestinationOut are not listed here as the platforms already
979     // implement the specification's behavior.
980     return op == CompositeSourceIn || op == CompositeSourceOut || op == CompositeDestinationIn || op == CompositeDestinationAtop;
981 }
982
983 static WindRule parseWinding(const String& windingRuleString)
984 {
985     if (windingRuleString == "nonzero")
986         return RULE_NONZERO;
987     if (windingRuleString == "evenodd")
988         return RULE_EVENODD;
989
990     ASSERT_NOT_REACHED();
991     return RULE_EVENODD;
992 }
993
994 void CanvasRenderingContext2D::fillInternal(const Path& path, const String& windingRuleString)
995 {
996     if (path.isEmpty()) {
997         return;
998     }
999     GraphicsContext* c = drawingContext();
1000     if (!c) {
1001         return;
1002     }
1003     if (!state().m_invertibleCTM) {
1004         return;
1005     }
1006     FloatRect clipBounds;
1007     if (!c->getTransformedClipBounds(&clipBounds)) {
1008         return;
1009     }
1010
1011     // If gradient size is zero, then paint nothing.
1012     Gradient* gradient = c->fillGradient();
1013     if (gradient && gradient->isZeroSize()) {
1014         return;
1015     }
1016
1017     WindRule windRule = c->fillRule();
1018     c->setFillRule(parseWinding(windingRuleString));
1019
1020     if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1021         fullCanvasCompositedFill(path);
1022         didDraw(clipBounds);
1023     } else if (state().m_globalComposite == CompositeCopy) {
1024         clearCanvas();
1025         c->fillPath(path);
1026         didDraw(clipBounds);
1027     } else {
1028         FloatRect dirtyRect;
1029         if (computeDirtyRect(path.boundingRect(), clipBounds, &dirtyRect)) {
1030             c->fillPath(path);
1031             didDraw(dirtyRect);
1032         }
1033     }
1034
1035     c->setFillRule(windRule);
1036 }
1037
1038 void CanvasRenderingContext2D::fill(const String& windingRuleString)
1039 {
1040     fillInternal(m_path, windingRuleString);
1041 }
1042
1043 void CanvasRenderingContext2D::fill(Path2D* domPath, const String& windingRuleString)
1044 {
1045     fillInternal(domPath->path(), windingRuleString);
1046 }
1047
1048 void CanvasRenderingContext2D::strokeInternal(const Path& path)
1049 {
1050     if (path.isEmpty()) {
1051         return;
1052     }
1053     GraphicsContext* c = drawingContext();
1054     if (!c) {
1055         return;
1056     }
1057     if (!state().m_invertibleCTM) {
1058         return;
1059     }
1060     FloatRect clipBounds;
1061     if (!c->getTransformedClipBounds(&clipBounds))
1062         return;
1063
1064     // If gradient size is zero, then paint nothing.
1065     Gradient* gradient = c->strokeGradient();
1066     if (gradient && gradient->isZeroSize()) {
1067         return;
1068     }
1069
1070     if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1071         fullCanvasCompositedStroke(path);
1072         didDraw(clipBounds);
1073     } else if (state().m_globalComposite == CompositeCopy) {
1074         clearCanvas();
1075         c->strokePath(path);
1076         didDraw(clipBounds);
1077     } else {
1078         FloatRect bounds = path.boundingRect();
1079         inflateStrokeRect(bounds);
1080         FloatRect dirtyRect;
1081         if (computeDirtyRect(bounds, clipBounds, &dirtyRect)) {
1082             c->strokePath(path);
1083             didDraw(dirtyRect);
1084         }
1085     }
1086 }
1087
1088 void CanvasRenderingContext2D::stroke()
1089 {
1090     strokeInternal(m_path);
1091 }
1092
1093 void CanvasRenderingContext2D::stroke(Path2D* domPath)
1094 {
1095     strokeInternal(domPath->path());
1096 }
1097
1098 void CanvasRenderingContext2D::clipInternal(const Path& path, const String& windingRuleString)
1099 {
1100     GraphicsContext* c = drawingContext();
1101     if (!c) {
1102         return;
1103     }
1104     if (!state().m_invertibleCTM) {
1105         return;
1106     }
1107
1108     realizeSaves();
1109     c->canvasClip(path, parseWinding(windingRuleString));
1110     modifiableState().m_hasClip = true;
1111 }
1112
1113 void CanvasRenderingContext2D::clip(const String& windingRuleString)
1114 {
1115     clipInternal(m_path, windingRuleString);
1116 }
1117
1118 void CanvasRenderingContext2D::clip(Path2D* domPath, const String& windingRuleString)
1119 {
1120     clipInternal(domPath->path(), windingRuleString);
1121 }
1122
1123 bool CanvasRenderingContext2D::isPointInPath(const float x, const float y, const String& windingRuleString)
1124 {
1125     return isPointInPathInternal(m_path, x, y, windingRuleString);
1126 }
1127
1128 bool CanvasRenderingContext2D::isPointInPath(Path2D* domPath, const float x, const float y, const String& windingRuleString)
1129 {
1130     return isPointInPathInternal(domPath->path(), x, y, windingRuleString);
1131 }
1132
1133 bool CanvasRenderingContext2D::isPointInPathInternal(const Path& path, const float x, const float y, const String& windingRuleString)
1134 {
1135     GraphicsContext* c = drawingContext();
1136     if (!c)
1137         return false;
1138     if (!state().m_invertibleCTM)
1139         return false;
1140
1141     FloatPoint point(x, y);
1142     AffineTransform ctm = state().m_transform;
1143     FloatPoint transformedPoint = ctm.inverse().mapPoint(point);
1144     if (!std::isfinite(transformedPoint.x()) || !std::isfinite(transformedPoint.y()))
1145         return false;
1146
1147     return path.contains(transformedPoint, parseWinding(windingRuleString));
1148 }
1149
1150 bool CanvasRenderingContext2D::isPointInStroke(const float x, const float y)
1151 {
1152     return isPointInStrokeInternal(m_path, x, y);
1153 }
1154
1155 bool CanvasRenderingContext2D::isPointInStroke(Path2D* domPath, const float x, const float y)
1156 {
1157     return isPointInStrokeInternal(domPath->path(), x, y);
1158 }
1159
1160 bool CanvasRenderingContext2D::isPointInStrokeInternal(const Path& path, const float x, const float y)
1161 {
1162     GraphicsContext* c = drawingContext();
1163     if (!c)
1164         return false;
1165     if (!state().m_invertibleCTM)
1166         return false;
1167
1168     FloatPoint point(x, y);
1169     AffineTransform ctm = state().m_transform;
1170     FloatPoint transformedPoint = ctm.inverse().mapPoint(point);
1171     if (!std::isfinite(transformedPoint.x()) || !std::isfinite(transformedPoint.y()))
1172         return false;
1173
1174     StrokeData strokeData;
1175     strokeData.setThickness(lineWidth());
1176     strokeData.setLineCap(getLineCap());
1177     strokeData.setLineJoin(getLineJoin());
1178     strokeData.setMiterLimit(miterLimit());
1179     strokeData.setLineDash(getLineDash(), lineDashOffset());
1180     return path.strokeContains(transformedPoint, strokeData);
1181 }
1182
1183 void CanvasRenderingContext2D::scrollPathIntoView()
1184 {
1185     scrollPathIntoViewInternal(m_path);
1186 }
1187
1188 void CanvasRenderingContext2D::scrollPathIntoView(Path2D* path2d)
1189 {
1190     scrollPathIntoViewInternal(path2d->path());
1191 }
1192
1193 void CanvasRenderingContext2D::scrollPathIntoViewInternal(const Path& path)
1194 {
1195     RenderObject* renderer = canvas()->renderer();
1196     RenderBox* renderBox = canvas()->renderBox();
1197     if (!renderer || !renderBox || !state().m_invertibleCTM || path.isEmpty())
1198         return;
1199
1200     canvas()->document().updateLayoutIgnorePendingStylesheets();
1201
1202     // Apply transformation and get the bounding rect
1203     Path transformedPath = path;
1204     transformedPath.transform(state().m_transform);
1205     FloatRect boundingRect = transformedPath.boundingRect();
1206
1207     // Offset by the canvas rect
1208     LayoutRect pathRect(boundingRect);
1209     IntRect canvasRect = renderBox->absoluteContentBox();
1210     pathRect.move(canvasRect.x(), canvasRect.y());
1211
1212     renderer->scrollRectToVisible(
1213         pathRect, ScrollAlignment::alignCenterAlways, ScrollAlignment::alignTopAlways);
1214
1215     // TODO: should implement "inform the user" that the caret and/or
1216     // selection the specified rectangle of the canvas. See http://crbug.com/357987
1217 }
1218
1219 void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height)
1220 {
1221     if (!validateRectForCanvas(x, y, width, height))
1222         return;
1223     GraphicsContext* context = drawingContext();
1224     if (!context)
1225         return;
1226     if (!state().m_invertibleCTM)
1227         return;
1228     FloatRect rect(x, y, width, height);
1229
1230     FloatRect dirtyRect;
1231     if (!computeDirtyRect(rect, &dirtyRect))
1232         return;
1233
1234     bool saved = false;
1235     if (shouldDrawShadows()) {
1236         context->save();
1237         saved = true;
1238         context->clearShadow();
1239     }
1240     if (state().m_globalAlpha != 1) {
1241         if (!saved) {
1242             context->save();
1243             saved = true;
1244         }
1245         context->setAlphaAsFloat(1);
1246     }
1247     if (state().m_globalComposite != CompositeSourceOver) {
1248         if (!saved) {
1249             context->save();
1250             saved = true;
1251         }
1252         context->setCompositeOperation(CompositeSourceOver);
1253     }
1254     context->clearRect(rect);
1255     if (m_hitRegionManager)
1256         m_hitRegionManager->removeHitRegionsInRect(rect, state().m_transform);
1257     if (saved)
1258         context->restore();
1259
1260     validateStateStack();
1261     didDraw(dirtyRect);
1262 }
1263
1264 void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height)
1265 {
1266     if (!validateRectForCanvas(x, y, width, height))
1267         return;
1268
1269     GraphicsContext* c = drawingContext();
1270     if (!c)
1271         return;
1272     if (!state().m_invertibleCTM)
1273         return;
1274     FloatRect clipBounds;
1275     if (!c->getTransformedClipBounds(&clipBounds))
1276         return;
1277
1278     // from the HTML5 Canvas spec:
1279     // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing
1280     // If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing
1281     Gradient* gradient = c->fillGradient();
1282     if (gradient && gradient->isZeroSize())
1283         return;
1284
1285     FloatRect rect(x, y, width, height);
1286     if (rectContainsTransformedRect(rect, clipBounds)) {
1287         c->fillRect(rect);
1288         didDraw(clipBounds);
1289     } else if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1290         fullCanvasCompositedFill(rect);
1291         didDraw(clipBounds);
1292     } else if (state().m_globalComposite == CompositeCopy) {
1293         clearCanvas();
1294         c->fillRect(rect);
1295         didDraw(clipBounds);
1296     } else {
1297         FloatRect dirtyRect;
1298         if (computeDirtyRect(rect, clipBounds, &dirtyRect)) {
1299             c->fillRect(rect);
1300             didDraw(dirtyRect);
1301         }
1302     }
1303 }
1304
1305 void CanvasRenderingContext2D::strokeRect(float x, float y, float width, float height)
1306 {
1307     if (!validateRectForCanvas(x, y, width, height))
1308         return;
1309
1310     if (!(state().m_lineWidth >= 0))
1311         return;
1312
1313     GraphicsContext* c = drawingContext();
1314     if (!c)
1315         return;
1316     if (!state().m_invertibleCTM)
1317         return;
1318     FloatRect clipBounds;
1319     if (!c->getTransformedClipBounds(&clipBounds))
1320         return;
1321
1322     // If gradient size is zero, then paint nothing.
1323     Gradient* gradient = c->strokeGradient();
1324     if (gradient && gradient->isZeroSize())
1325         return;
1326
1327     FloatRect rect(x, y, width, height);
1328
1329     if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1330         fullCanvasCompositedStroke(rect);
1331         didDraw(clipBounds);
1332     } else if (state().m_globalComposite == CompositeCopy) {
1333         clearCanvas();
1334         c->strokeRect(rect);
1335         didDraw(clipBounds);
1336     } else {
1337         FloatRect boundingRect = rect;
1338         boundingRect.inflate(state().m_lineWidth / 2);
1339         FloatRect dirtyRect;
1340         if (computeDirtyRect(boundingRect, clipBounds, &dirtyRect)) {
1341             c->strokeRect(rect);
1342             didDraw(dirtyRect);
1343         }
1344     }
1345 }
1346
1347 void CanvasRenderingContext2D::setShadow(float width, float height, float blur)
1348 {
1349     setShadow(FloatSize(width, height), blur, Color::transparent);
1350 }
1351
1352 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& color)
1353 {
1354     RGBA32 rgba;
1355     if (!parseColorOrCurrentColor(rgba, color, canvas()))
1356         return;
1357     setShadow(FloatSize(width, height), blur, rgba);
1358 }
1359
1360 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float grayLevel)
1361 {
1362     setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(grayLevel, grayLevel, grayLevel, 1));
1363 }
1364
1365 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& color, float alpha)
1366 {
1367     RGBA32 rgba;
1368     if (!parseColorOrCurrentColor(rgba, color, canvas()))
1369         return;
1370     setShadow(FloatSize(width, height), blur, colorWithOverrideAlpha(rgba, alpha));
1371 }
1372
1373 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float grayLevel, float alpha)
1374 {
1375     setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(grayLevel, grayLevel, grayLevel, alpha));
1376 }
1377
1378 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float r, float g, float b, float a)
1379 {
1380     setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(r, g, b, a));
1381 }
1382
1383 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float c, float m, float y, float k, float a)
1384 {
1385     setShadow(FloatSize(width, height), blur, makeRGBAFromCMYKA(c, m, y, k, a));
1386 }
1387
1388 void CanvasRenderingContext2D::clearShadow()
1389 {
1390     setShadow(FloatSize(), 0, Color::transparent);
1391 }
1392
1393 void CanvasRenderingContext2D::setShadow(const FloatSize& offset, float blur, RGBA32 color)
1394 {
1395     if (state().m_shadowOffset == offset && state().m_shadowBlur == blur && state().m_shadowColor == color)
1396         return;
1397     bool wasDrawingShadows = shouldDrawShadows();
1398     realizeSaves();
1399     modifiableState().m_shadowOffset = offset;
1400     modifiableState().m_shadowBlur = blur;
1401     modifiableState().m_shadowColor = color;
1402     if (!wasDrawingShadows && !shouldDrawShadows())
1403         return;
1404     applyShadow();
1405 }
1406
1407 void CanvasRenderingContext2D::applyShadow()
1408 {
1409     GraphicsContext* c = drawingContext();
1410     if (!c)
1411         return;
1412
1413     if (shouldDrawShadows()) {
1414         c->setShadow(state().m_shadowOffset, state().m_shadowBlur, state().m_shadowColor,
1415             DrawLooperBuilder::ShadowIgnoresTransforms);
1416     } else {
1417         c->clearShadow();
1418     }
1419 }
1420
1421 bool CanvasRenderingContext2D::shouldDrawShadows() const
1422 {
1423     return alphaChannel(state().m_shadowColor) && (state().m_shadowBlur || !state().m_shadowOffset.isZero());
1424 }
1425
1426 static inline FloatRect normalizeRect(const FloatRect& rect)
1427 {
1428     return FloatRect(std::min(rect.x(), rect.maxX()),
1429         std::min(rect.y(), rect.maxY()),
1430         std::max(rect.width(), -rect.width()),
1431         std::max(rect.height(), -rect.height()));
1432 }
1433
1434 static inline void clipRectsToImageRect(const FloatRect& imageRect, FloatRect* srcRect, FloatRect* dstRect)
1435 {
1436     if (imageRect.contains(*srcRect))
1437         return;
1438
1439     // Compute the src to dst transform
1440     FloatSize scale(dstRect->size().width() / srcRect->size().width(), dstRect->size().height() / srcRect->size().height());
1441     FloatPoint scaledSrcLocation = srcRect->location();
1442     scaledSrcLocation.scale(scale.width(), scale.height());
1443     FloatSize offset = dstRect->location() - scaledSrcLocation;
1444
1445     srcRect->intersect(imageRect);
1446
1447     // To clip the destination rectangle in the same proportion, transform the clipped src rect
1448     *dstRect = *srcRect;
1449     dstRect->scale(scale.width(), scale.height());
1450     dstRect->move(offset);
1451 }
1452
1453 void CanvasRenderingContext2D::drawImage(CanvasImageSource* imageSource, float x, float y, ExceptionState& exceptionState)
1454 {
1455     FloatSize destRectSize = imageSource->defaultDestinationSize();
1456     drawImage(imageSource, x, y, destRectSize.width(), destRectSize.height(), exceptionState);
1457 }
1458
1459 void CanvasRenderingContext2D::drawImage(CanvasImageSource* imageSource,
1460     float x, float y, float width, float height, ExceptionState& exceptionState)
1461 {
1462     FloatSize sourceRectSize = imageSource->sourceSize();
1463     drawImage(imageSource, 0, 0, sourceRectSize.width(), sourceRectSize.height(), x, y, width, height, exceptionState);
1464 }
1465
1466 void CanvasRenderingContext2D::drawImage(CanvasImageSource* imageSource,
1467     float sx, float sy, float sw, float sh,
1468     float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
1469 {
1470     GraphicsContext* c = drawingContext(); // Do not exit yet if !c because we may need to throw exceptions first
1471     CompositeOperator op = c ? c->compositeOperation() : CompositeSourceOver;
1472     blink::WebBlendMode blendMode = c ? c->blendModeOperation() : blink::WebBlendModeNormal;
1473     drawImageInternal(imageSource, sx, sy, sw, sh, dx, dy, dw, dh, exceptionState, op, blendMode);
1474 }
1475
1476 void CanvasRenderingContext2D::drawImageInternal(CanvasImageSource* imageSource,
1477     float sx, float sy, float sw, float sh,
1478     float dx, float dy, float dw, float dh, ExceptionState& exceptionState,
1479     CompositeOperator op, blink::WebBlendMode blendMode)
1480 {
1481     RefPtr<Image> image;
1482     SourceImageStatus sourceImageStatus = InvalidSourceImageStatus;
1483     if (!imageSource->isVideoElement()) {
1484         SourceImageMode mode = canvas() == imageSource ? CopySourceImageIfVolatile : DontCopySourceImage; // Thunking for ==
1485         image = imageSource->getSourceImageForCanvas(mode, &sourceImageStatus);
1486         if (sourceImageStatus == UndecodableSourceImageStatus)
1487             exceptionState.throwDOMException(InvalidStateError, "The HTMLImageElement provided is in the 'broken' state.");
1488         if (!image || !image->width() || !image->height())
1489             return;
1490     }
1491
1492     GraphicsContext* c = drawingContext();
1493     if (!c)
1494         return;
1495
1496     if (!state().m_invertibleCTM)
1497         return;
1498
1499     if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh)
1500         || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh)
1501         || !dw || !dh || !sw || !sh)
1502         return;
1503
1504     FloatRect clipBounds;
1505     if (!c->getTransformedClipBounds(&clipBounds))
1506         return;
1507
1508     FloatRect srcRect = normalizeRect(FloatRect(sx, sy, sw, sh));
1509     FloatRect dstRect = normalizeRect(FloatRect(dx, dy, dw, dh));
1510
1511     clipRectsToImageRect(FloatRect(FloatPoint(), imageSource->sourceSize()), &srcRect, &dstRect);
1512
1513     imageSource->adjustDrawRects(&srcRect, &dstRect);
1514
1515     if (srcRect.isEmpty())
1516         return;
1517
1518     FloatRect dirtyRect = clipBounds;
1519     if (imageSource->isVideoElement()) {
1520         drawVideo(static_cast<HTMLVideoElement*>(imageSource), srcRect, dstRect);
1521         computeDirtyRect(dstRect, clipBounds, &dirtyRect);
1522     } else {
1523         if (rectContainsTransformedRect(dstRect, clipBounds)) {
1524             c->drawImage(image.get(), dstRect, srcRect, op, blendMode);
1525         } else if (isFullCanvasCompositeMode(op)) {
1526             fullCanvasCompositedDrawImage(image.get(), dstRect, srcRect, op);
1527         } else if (op == CompositeCopy) {
1528             clearCanvas();
1529             c->drawImage(image.get(), dstRect, srcRect, op, blendMode);
1530         } else {
1531             FloatRect dirtyRect;
1532             computeDirtyRect(dstRect, clipBounds, &dirtyRect);
1533             c->drawImage(image.get(), dstRect, srcRect, op, blendMode);
1534         }
1535
1536         if (sourceImageStatus == ExternalSourceImageStatus && isAccelerated() && canvas()->buffer())
1537             canvas()->buffer()->flush();
1538     }
1539
1540     if (canvas()->originClean() && wouldTaintOrigin(imageSource))
1541         canvas()->setOriginTainted();
1542
1543     didDraw(dirtyRect);
1544 }
1545
1546 void CanvasRenderingContext2D::drawVideo(HTMLVideoElement* video, FloatRect srcRect, FloatRect dstRect)
1547 {
1548     GraphicsContext* c = drawingContext();
1549     GraphicsContextStateSaver stateSaver(*c);
1550     c->clip(dstRect);
1551     c->translate(dstRect.x(), dstRect.y());
1552     c->scale(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height());
1553     c->translate(-srcRect.x(), -srcRect.y());
1554     video->paintCurrentFrameInContext(c, IntRect(IntPoint(), IntSize(video->videoWidth(), video->videoHeight())));
1555     stateSaver.restore();
1556     validateStateStack();
1557 }
1558
1559 void CanvasRenderingContext2D::drawImageFromRect(HTMLImageElement* image,
1560     float sx, float sy, float sw, float sh,
1561     float dx, float dy, float dw, float dh,
1562     const String& compositeOperation)
1563 {
1564     if (!image)
1565         return;
1566     CompositeOperator op;
1567     blink::WebBlendMode blendOp = blink::WebBlendModeNormal;
1568     if (!parseCompositeAndBlendOperator(compositeOperation, op, blendOp) || blendOp != blink::WebBlendModeNormal)
1569         op = CompositeSourceOver;
1570
1571     drawImageInternal(image, sx, sy, sw, sh, dx, dy, dw, dh, IGNORE_EXCEPTION, op, blendOp);
1572 }
1573
1574 void CanvasRenderingContext2D::setAlpha(float alpha)
1575 {
1576     setGlobalAlpha(alpha);
1577 }
1578
1579 void CanvasRenderingContext2D::setCompositeOperation(const String& operation)
1580 {
1581     setGlobalCompositeOperation(operation);
1582 }
1583
1584 void CanvasRenderingContext2D::clearCanvas()
1585 {
1586     FloatRect canvasRect(0, 0, canvas()->width(), canvas()->height());
1587     GraphicsContext* c = drawingContext();
1588     if (!c)
1589         return;
1590
1591     c->save();
1592     c->setCTM(canvas()->baseTransform());
1593     c->clearRect(canvasRect);
1594     c->restore();
1595 }
1596
1597 bool CanvasRenderingContext2D::rectContainsTransformedRect(const FloatRect& rect, const FloatRect& transformedRect) const
1598 {
1599     FloatQuad quad(rect);
1600     FloatQuad transformedQuad(transformedRect);
1601     return state().m_transform.mapQuad(quad).containsQuad(transformedQuad);
1602 }
1603
1604 static void drawImageToContext(Image* image, GraphicsContext* context, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
1605 {
1606     context->drawImage(image, dest, src, op);
1607 }
1608
1609 template<class T> void  CanvasRenderingContext2D::fullCanvasCompositedDrawImage(T* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
1610 {
1611     ASSERT(isFullCanvasCompositeMode(op));
1612
1613     GraphicsContext* c = drawingContext();
1614     c->beginLayer(1, op);
1615     drawImageToContext(image, c, dest, src, CompositeSourceOver);
1616     c->endLayer();
1617 }
1618
1619 static void fillPrimitive(const FloatRect& rect, GraphicsContext* context)
1620 {
1621     context->fillRect(rect);
1622 }
1623
1624 static void fillPrimitive(const Path& path, GraphicsContext* context)
1625 {
1626     context->fillPath(path);
1627 }
1628
1629 template<class T> void CanvasRenderingContext2D::fullCanvasCompositedFill(const T& area)
1630 {
1631     ASSERT(isFullCanvasCompositeMode(state().m_globalComposite));
1632
1633     GraphicsContext* c = drawingContext();
1634     ASSERT(c);
1635     c->beginLayer(1, state().m_globalComposite);
1636     CompositeOperator previousOperator = c->compositeOperation();
1637     c->setCompositeOperation(CompositeSourceOver);
1638     fillPrimitive(area, c);
1639     c->setCompositeOperation(previousOperator);
1640     c->endLayer();
1641 }
1642
1643 static void strokePrimitive(const FloatRect& rect, GraphicsContext* context)
1644 {
1645     context->strokeRect(rect);
1646 }
1647
1648 static void strokePrimitive(const Path& path, GraphicsContext* context)
1649 {
1650     context->strokePath(path);
1651 }
1652
1653 template<class T> void CanvasRenderingContext2D::fullCanvasCompositedStroke(const T& area)
1654 {
1655     ASSERT(isFullCanvasCompositeMode(state().m_globalComposite));
1656
1657     GraphicsContext* c = drawingContext();
1658     ASSERT(c);
1659     c->beginLayer(1, state().m_globalComposite);
1660     CompositeOperator previousOperator = c->compositeOperation();
1661     c->setCompositeOperation(CompositeSourceOver);
1662     strokePrimitive(area, c);
1663     c->setCompositeOperation(previousOperator);
1664     c->endLayer();
1665 }
1666
1667 PassRefPtrWillBeRawPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1)
1668 {
1669     RefPtrWillBeRawPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), FloatPoint(x1, y1));
1670     return gradient.release();
1671 }
1672
1673 PassRefPtrWillBeRawPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& exceptionState)
1674 {
1675     if (r0 < 0 || r1 < 0) {
1676         exceptionState.throwDOMException(IndexSizeError, String::format("The %s provided is less than 0.", r0 < 0 ? "r0" : "r1"));
1677         return nullptr;
1678     }
1679
1680     RefPtrWillBeRawPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), r0, FloatPoint(x1, y1), r1);
1681     return gradient.release();
1682 }
1683
1684 PassRefPtrWillBeRawPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(CanvasImageSource* imageSource,
1685     const String& repetitionType, ExceptionState& exceptionState)
1686 {
1687     Pattern::RepeatMode repeatMode = CanvasPattern::parseRepetitionType(repetitionType, exceptionState);
1688     if (exceptionState.hadException())
1689         return nullptr;
1690
1691     SourceImageStatus status;
1692     RefPtr<Image> imageForRendering = imageSource->getSourceImageForCanvas(CopySourceImageIfVolatile, &status);
1693
1694     switch (status) {
1695     case NormalSourceImageStatus:
1696         break;
1697     case ZeroSizeCanvasSourceImageStatus:
1698         exceptionState.throwDOMException(InvalidStateError, String::format("The canvas %s is 0.", imageSource->sourceSize().width() ? "height" : "width"));
1699         return nullptr;
1700     case UndecodableSourceImageStatus:
1701         exceptionState.throwDOMException(InvalidStateError, "Source image is in the 'broken' state.");
1702         return nullptr;
1703     case InvalidSourceImageStatus:
1704         imageForRendering = Image::nullImage();
1705         break;
1706     case IncompleteSourceImageStatus:
1707         return nullptr;
1708     default:
1709     case ExternalSourceImageStatus: // should not happen when mode is CopySourceImageIfVolatile
1710         ASSERT_NOT_REACHED();
1711         return nullptr;
1712     }
1713     ASSERT(imageForRendering);
1714
1715     bool originClean = !wouldTaintOrigin(imageSource);
1716
1717     return CanvasPattern::create(imageForRendering.release(), repeatMode, originClean);
1718 }
1719
1720 bool CanvasRenderingContext2D::computeDirtyRect(const FloatRect& localRect, FloatRect* dirtyRect)
1721 {
1722     FloatRect clipBounds;
1723     if (!drawingContext()->getTransformedClipBounds(&clipBounds))
1724         return false;
1725     return computeDirtyRect(localRect, clipBounds, dirtyRect);
1726 }
1727
1728 bool CanvasRenderingContext2D::computeDirtyRect(const FloatRect& localRect, const FloatRect& transformedClipBounds, FloatRect* dirtyRect)
1729 {
1730     FloatRect canvasRect = state().m_transform.mapRect(localRect);
1731
1732     if (alphaChannel(state().m_shadowColor)) {
1733         FloatRect shadowRect(canvasRect);
1734         shadowRect.move(state().m_shadowOffset);
1735         shadowRect.inflate(state().m_shadowBlur);
1736         canvasRect.unite(shadowRect);
1737     }
1738
1739     canvasRect.intersect(transformedClipBounds);
1740     if (canvasRect.isEmpty())
1741         return false;
1742
1743     if (dirtyRect)
1744         *dirtyRect = canvasRect;
1745
1746     return true;
1747 }
1748
1749 void CanvasRenderingContext2D::didDraw(const FloatRect& dirtyRect)
1750 {
1751     if (dirtyRect.isEmpty())
1752         return;
1753
1754     canvas()->didDraw(dirtyRect);
1755 }
1756
1757 GraphicsContext* CanvasRenderingContext2D::drawingContext() const
1758 {
1759     if (isContextLost())
1760         return 0;
1761     return canvas()->drawingContext();
1762 }
1763
1764 static PassRefPtrWillBeRawPtr<ImageData> createEmptyImageData(const IntSize& size)
1765 {
1766     if (RefPtrWillBeRawPtr<ImageData> data = ImageData::create(size)) {
1767         data->data()->zeroFill();
1768         return data.release();
1769     }
1770
1771     return nullptr;
1772 }
1773
1774 PassRefPtrWillBeRawPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtrWillBeRawPtr<ImageData> imageData) const
1775 {
1776     return createEmptyImageData(imageData->size());
1777 }
1778
1779 PassRefPtrWillBeRawPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& exceptionState) const
1780 {
1781     if (!sw || !sh) {
1782         exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width"));
1783         return nullptr;
1784     }
1785
1786     FloatSize logicalSize(fabs(sw), fabs(sh));
1787     if (!logicalSize.isExpressibleAsIntSize())
1788         return nullptr;
1789
1790     IntSize size = expandedIntSize(logicalSize);
1791     if (size.width() < 1)
1792         size.setWidth(1);
1793     if (size.height() < 1)
1794         size.setHeight(1);
1795
1796     return createEmptyImageData(size);
1797 }
1798
1799 PassRefPtrWillBeRawPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
1800 {
1801     if (!canvas()->originClean())
1802         exceptionState.throwSecurityError("The canvas has been tainted by cross-origin data.");
1803     else if (!sw || !sh)
1804         exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width"));
1805
1806     if (exceptionState.hadException())
1807         return nullptr;
1808
1809     if (sw < 0) {
1810         sx += sw;
1811         sw = -sw;
1812     }
1813     if (sh < 0) {
1814         sy += sh;
1815         sh = -sh;
1816     }
1817
1818     FloatRect logicalRect(sx, sy, sw, sh);
1819     if (logicalRect.width() < 1)
1820         logicalRect.setWidth(1);
1821     if (logicalRect.height() < 1)
1822         logicalRect.setHeight(1);
1823     if (!logicalRect.isExpressibleAsIntRect())
1824         return nullptr;
1825
1826     IntRect imageDataRect = enclosingIntRect(logicalRect);
1827     ImageBuffer* buffer = canvas()->buffer();
1828     if (!buffer || isContextLost())
1829         return createEmptyImageData(imageDataRect.size());
1830
1831     RefPtr<Uint8ClampedArray> byteArray = buffer->getImageData(Unmultiplied, imageDataRect);
1832     if (!byteArray)
1833         return nullptr;
1834
1835     return ImageData::create(imageDataRect.size(), byteArray.release());
1836 }
1837
1838 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy)
1839 {
1840     putImageData(data, dx, dy, 0, 0, data->width(), data->height());
1841 }
1842
1843 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight)
1844 {
1845     ImageBuffer* buffer = canvas()->buffer();
1846     if (!buffer)
1847         return;
1848
1849     if (dirtyWidth < 0) {
1850         dirtyX += dirtyWidth;
1851         dirtyWidth = -dirtyWidth;
1852     }
1853
1854     if (dirtyHeight < 0) {
1855         dirtyY += dirtyHeight;
1856         dirtyHeight = -dirtyHeight;
1857     }
1858
1859     FloatRect clipRect(dirtyX, dirtyY, dirtyWidth, dirtyHeight);
1860     clipRect.intersect(IntRect(0, 0, data->width(), data->height()));
1861     IntSize destOffset(static_cast<int>(dx), static_cast<int>(dy));
1862     IntRect destRect = enclosingIntRect(clipRect);
1863     destRect.move(destOffset);
1864     destRect.intersect(IntRect(IntPoint(), buffer->size()));
1865     if (destRect.isEmpty())
1866         return;
1867     IntRect sourceRect(destRect);
1868     sourceRect.move(-destOffset);
1869
1870     buffer->putByteArray(Unmultiplied, data->data(), IntSize(data->width(), data->height()), sourceRect, IntPoint(destOffset));
1871
1872     didDraw(destRect);
1873 }
1874
1875 String CanvasRenderingContext2D::font() const
1876 {
1877     if (!state().m_realizedFont)
1878         return defaultFont;
1879
1880     StringBuilder serializedFont;
1881     const FontDescription& fontDescription = state().m_font.fontDescription();
1882
1883     if (fontDescription.style() == FontStyleItalic)
1884         serializedFont.appendLiteral("italic ");
1885     if (fontDescription.weight() == FontWeightBold)
1886         serializedFont.appendLiteral("bold ");
1887     if (fontDescription.variant() == FontVariantSmallCaps)
1888         serializedFont.appendLiteral("small-caps ");
1889
1890     serializedFont.appendNumber(fontDescription.computedPixelSize());
1891     serializedFont.appendLiteral("px");
1892
1893     const FontFamily& firstFontFamily = fontDescription.family();
1894     for (const FontFamily* fontFamily = &firstFontFamily; fontFamily; fontFamily = fontFamily->next()) {
1895         if (fontFamily != &firstFontFamily)
1896             serializedFont.append(',');
1897
1898         // FIXME: We should append family directly to serializedFont rather than building a temporary string.
1899         String family = fontFamily->family();
1900         if (family.startsWith("-webkit-"))
1901             family = family.substring(8);
1902         if (family.contains(' '))
1903             family = "\"" + family + "\"";
1904
1905         serializedFont.append(' ');
1906         serializedFont.append(family);
1907     }
1908
1909     return serializedFont.toString();
1910 }
1911
1912 void CanvasRenderingContext2D::setFont(const String& newFont)
1913 {
1914     // The style resolution required for rendering text is not available in frame-less documents.
1915     if (!canvas()->document().frame())
1916         return;
1917
1918     MutableStylePropertyMap::iterator i = m_fetchedFonts.find(newFont);
1919     RefPtrWillBeRawPtr<MutableStylePropertySet> parsedStyle = i != m_fetchedFonts.end() ? i->value : nullptr;
1920
1921     if (!parsedStyle) {
1922         parsedStyle = MutableStylePropertySet::create();
1923         CSSParserMode mode = m_usesCSSCompatibilityParseMode ? HTMLQuirksMode : HTMLStandardMode;
1924         BisonCSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, mode, 0);
1925         m_fetchedFonts.add(newFont, parsedStyle);
1926     }
1927     if (parsedStyle->isEmpty())
1928         return;
1929
1930     String fontValue = parsedStyle->getPropertyValue(CSSPropertyFont);
1931
1932     // According to http://lists.w3.org/Archives/Public/public-html/2009Jul/0947.html,
1933     // the "inherit" and "initial" values must be ignored.
1934     if (fontValue == "inherit" || fontValue == "initial")
1935         return;
1936
1937     // The parse succeeded.
1938     String newFontSafeCopy(newFont); // Create a string copy since newFont can be deleted inside realizeSaves.
1939     realizeSaves();
1940     modifiableState().m_unparsedFont = newFontSafeCopy;
1941
1942     // Map the <canvas> font into the text style. If the font uses keywords like larger/smaller, these will work
1943     // relative to the canvas.
1944     RefPtr<RenderStyle> newStyle = RenderStyle::create();
1945     if (RenderStyle* computedStyle = canvas()->computedStyle()) {
1946         FontDescription elementFontDescription(computedStyle->fontDescription());
1947         // Reset the computed size to avoid inheriting the zoom factor from the <canvas> element.
1948         elementFontDescription.setComputedSize(elementFontDescription.specifiedSize());
1949         newStyle->setFontDescription(elementFontDescription);
1950     } else {
1951         FontFamily fontFamily;
1952         fontFamily.setFamily(defaultFontFamily);
1953
1954         FontDescription defaultFontDescription;
1955         defaultFontDescription.setFamily(fontFamily);
1956         defaultFontDescription.setSpecifiedSize(defaultFontSize);
1957         defaultFontDescription.setComputedSize(defaultFontSize);
1958
1959         newStyle->setFontDescription(defaultFontDescription);
1960     }
1961
1962     newStyle->font().update(newStyle->font().fontSelector());
1963
1964     // Now map the font property longhands into the style.
1965     CSSPropertyValue properties[] = {
1966         CSSPropertyValue(CSSPropertyFontFamily, *parsedStyle),
1967         CSSPropertyValue(CSSPropertyFontStyle, *parsedStyle),
1968         CSSPropertyValue(CSSPropertyFontVariant, *parsedStyle),
1969         CSSPropertyValue(CSSPropertyFontWeight, *parsedStyle),
1970         CSSPropertyValue(CSSPropertyFontSize, *parsedStyle),
1971         CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
1972     };
1973
1974     StyleResolver& styleResolver = canvas()->document().ensureStyleResolver();
1975     styleResolver.applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), newStyle.get());
1976
1977 #if !ENABLE(OILPAN)
1978     if (state().m_realizedFont)
1979         static_cast<CSSFontSelector*>(state().m_font.fontSelector())->unregisterForInvalidationCallbacks(&modifiableState());
1980 #endif
1981     modifiableState().m_font = newStyle->font();
1982     modifiableState().m_font.update(canvas()->document().styleEngine()->fontSelector());
1983     modifiableState().m_realizedFont = true;
1984     canvas()->document().styleEngine()->fontSelector()->registerForInvalidationCallbacks(&modifiableState());
1985 }
1986
1987 String CanvasRenderingContext2D::textAlign() const
1988 {
1989     return textAlignName(state().m_textAlign);
1990 }
1991
1992 void CanvasRenderingContext2D::setTextAlign(const String& s)
1993 {
1994     TextAlign align;
1995     if (!parseTextAlign(s, align))
1996         return;
1997     if (state().m_textAlign == align)
1998         return;
1999     realizeSaves();
2000     modifiableState().m_textAlign = align;
2001 }
2002
2003 String CanvasRenderingContext2D::textBaseline() const
2004 {
2005     return textBaselineName(state().m_textBaseline);
2006 }
2007
2008 void CanvasRenderingContext2D::setTextBaseline(const String& s)
2009 {
2010     TextBaseline baseline;
2011     if (!parseTextBaseline(s, baseline))
2012         return;
2013     if (state().m_textBaseline == baseline)
2014         return;
2015     realizeSaves();
2016     modifiableState().m_textBaseline = baseline;
2017 }
2018
2019 void CanvasRenderingContext2D::fillText(const String& text, float x, float y)
2020 {
2021     drawTextInternal(text, x, y, true);
2022 }
2023
2024 void CanvasRenderingContext2D::fillText(const String& text, float x, float y, float maxWidth)
2025 {
2026     drawTextInternal(text, x, y, true, maxWidth, true);
2027 }
2028
2029 void CanvasRenderingContext2D::strokeText(const String& text, float x, float y)
2030 {
2031     drawTextInternal(text, x, y, false);
2032 }
2033
2034 void CanvasRenderingContext2D::strokeText(const String& text, float x, float y, float maxWidth)
2035 {
2036     drawTextInternal(text, x, y, false, maxWidth, true);
2037 }
2038
2039 static inline bool isSpaceCharacter(UChar c)
2040 {
2041     // According to specification all space characters should be replaced with 0x0020 space character.
2042     // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-preparation-algorithm
2043     // The space characters according to specification are : U+0020, U+0009, U+000A, U+000C, and U+000D.
2044     // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-microsyntaxes.html#space-character
2045     // This function returns true for 0x000B also, so that this is backward compatible.
2046     // Otherwise, the test LayoutTests/canvas/philip/tests/2d.text.draw.space.collapse.space.html will fail
2047     return c == 0x0009 || c == 0x000A || c == 0x000B || c == 0x000C || c == 0x000D;
2048 }
2049
2050 static String normalizeSpaces(const String& text)
2051 {
2052     unsigned textLength = text.length();
2053     Vector<UChar> charVector(textLength);
2054
2055     for (unsigned i = 0; i < textLength; i++) {
2056         if (isSpaceCharacter(text[i]))
2057             charVector[i] = ' ';
2058         else
2059             charVector[i] = text[i];
2060     }
2061
2062     return String(charVector);
2063 }
2064
2065 PassRefPtrWillBeRawPtr<TextMetrics> CanvasRenderingContext2D::measureText(const String& text)
2066 {
2067     RefPtrWillBeRawPtr<TextMetrics> metrics = TextMetrics::create();
2068
2069     // The style resolution required for rendering text is not available in frame-less documents.
2070     if (!canvas()->document().frame())
2071         return metrics.release();
2072
2073     FontCachePurgePreventer fontCachePurgePreventer;
2074     canvas()->document().updateRenderTreeIfNeeded();
2075     const Font& font = accessFont();
2076     String normalizedText = normalizeSpaces(text);
2077     const TextRun textRun(normalizedText);
2078     FloatRect textBounds = font.selectionRectForText(textRun, FloatPoint(), font.fontDescription().computedSize(), 0, -1, true);
2079
2080     // x direction
2081     metrics->setWidth(font.width(textRun));
2082     metrics->setActualBoundingBoxLeft(-textBounds.x());
2083     metrics->setActualBoundingBoxRight(textBounds.maxX());
2084
2085     // y direction
2086     const FontMetrics& fontMetrics = font.fontMetrics();
2087     const float ascent = fontMetrics.floatAscent();
2088     const float descent = fontMetrics.floatDescent();
2089     const float baselineY = getFontBaseline(fontMetrics);
2090
2091     metrics->setFontBoundingBoxAscent(ascent - baselineY);
2092     metrics->setFontBoundingBoxDescent(descent + baselineY);
2093     metrics->setActualBoundingBoxAscent(-textBounds.y() - baselineY);
2094     metrics->setActualBoundingBoxDescent(textBounds.maxY() + baselineY);
2095
2096     // Note : top/bottom and ascend/descend are currently the same, so there's no difference
2097     //        between the EM box's top and bottom and the font's ascend and descend
2098     metrics->setEmHeightAscent(0);
2099     metrics->setEmHeightDescent(0);
2100
2101     metrics->setHangingBaseline(-0.8f * ascent + baselineY);
2102     metrics->setAlphabeticBaseline(baselineY);
2103     metrics->setIdeographicBaseline(descent + baselineY);
2104     return metrics.release();
2105 }
2106
2107 void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, float y, bool fill, float maxWidth, bool useMaxWidth)
2108 {
2109     // The style resolution required for rendering text is not available in frame-less documents.
2110     if (!canvas()->document().frame())
2111         return;
2112
2113     // accessFont needs the style to be up to date, but updating style can cause script to run,
2114     // (e.g. due to autofocus) which can free the GraphicsContext, so update style before grabbing
2115     // the GraphicsContext.
2116     canvas()->document().updateRenderTreeIfNeeded();
2117
2118     GraphicsContext* c = drawingContext();
2119     if (!c)
2120         return;
2121     if (!state().m_invertibleCTM)
2122         return;
2123     if (!std::isfinite(x) | !std::isfinite(y))
2124         return;
2125     if (useMaxWidth && (!std::isfinite(maxWidth) || maxWidth <= 0))
2126         return;
2127
2128     // If gradient size is zero, then paint nothing.
2129     Gradient* gradient = c->strokeGradient();
2130     if (!fill && gradient && gradient->isZeroSize())
2131         return;
2132
2133     gradient = c->fillGradient();
2134     if (fill && gradient && gradient->isZeroSize())
2135         return;
2136
2137     FontCachePurgePreventer fontCachePurgePreventer;
2138
2139     const Font& font = accessFont();
2140     const FontMetrics& fontMetrics = font.fontMetrics();
2141     String normalizedText = normalizeSpaces(text);
2142
2143     // FIXME: Need to turn off font smoothing.
2144
2145     RenderStyle* computedStyle = canvas()->computedStyle();
2146     TextDirection direction = computedStyle ? computedStyle->direction() : LTR;
2147     bool isRTL = direction == RTL;
2148     bool override = computedStyle ? isOverride(computedStyle->unicodeBidi()) : false;
2149
2150     TextRun textRun(normalizedText, 0, 0, TextRun::AllowTrailingExpansion, direction, override, true);
2151     // Draw the item text at the correct point.
2152     FloatPoint location(x, y + getFontBaseline(fontMetrics));
2153
2154     float fontWidth = font.width(TextRun(normalizedText, 0, 0, TextRun::AllowTrailingExpansion, direction, override));
2155
2156     useMaxWidth = (useMaxWidth && maxWidth < fontWidth);
2157     float width = useMaxWidth ? maxWidth : fontWidth;
2158
2159     TextAlign align = state().m_textAlign;
2160     if (align == StartTextAlign)
2161         align = isRTL ? RightTextAlign : LeftTextAlign;
2162     else if (align == EndTextAlign)
2163         align = isRTL ? LeftTextAlign : RightTextAlign;
2164
2165     switch (align) {
2166     case CenterTextAlign:
2167         location.setX(location.x() - width / 2);
2168         break;
2169     case RightTextAlign:
2170         location.setX(location.x() - width);
2171         break;
2172     default:
2173         break;
2174     }
2175
2176     // The slop built in to this mask rect matches the heuristic used in FontCGWin.cpp for GDI text.
2177     TextRunPaintInfo textRunPaintInfo(textRun);
2178     textRunPaintInfo.bounds = FloatRect(location.x() - fontMetrics.height() / 2,
2179                                         location.y() - fontMetrics.ascent() - fontMetrics.lineGap(),
2180                                         width + fontMetrics.height(),
2181                                         fontMetrics.lineSpacing());
2182     if (!fill)
2183         inflateStrokeRect(textRunPaintInfo.bounds);
2184
2185     c->setTextDrawingMode(fill ? TextModeFill : TextModeStroke);
2186
2187     GraphicsContextStateSaver stateSaver(*c);
2188     if (useMaxWidth) {
2189         c->translate(location.x(), location.y());
2190         // We draw when fontWidth is 0 so compositing operations (eg, a "copy" op) still work.
2191         c->scale((fontWidth > 0 ? (width / fontWidth) : 0), 1);
2192         location = FloatPoint();
2193     }
2194
2195     FloatRect clipBounds;
2196     if (!c->getTransformedClipBounds(&clipBounds)) {
2197         return;
2198     }
2199
2200     if (isFullCanvasCompositeMode(state().m_globalComposite)) {
2201         c->beginLayer(1, state().m_globalComposite);
2202         CompositeOperator previousOperator = c->compositeOperation();
2203         c->setCompositeOperation(CompositeSourceOver);
2204         c->drawBidiText(font, textRunPaintInfo, location, Font::UseFallbackIfFontNotReady);
2205         c->setCompositeOperation(previousOperator);
2206         c->endLayer();
2207         didDraw(clipBounds);
2208     } else if (state().m_globalComposite == CompositeCopy) {
2209         clearCanvas();
2210         c->drawBidiText(font, textRunPaintInfo, location, Font::UseFallbackIfFontNotReady);
2211         didDraw(clipBounds);
2212     } else {
2213         FloatRect dirtyRect;
2214         if (computeDirtyRect(textRunPaintInfo.bounds, clipBounds, &dirtyRect)) {
2215             c->drawBidiText(font, textRunPaintInfo, location, Font::UseFallbackIfFontNotReady);
2216             didDraw(dirtyRect);
2217         }
2218     }
2219 }
2220
2221 void CanvasRenderingContext2D::inflateStrokeRect(FloatRect& rect) const
2222 {
2223     // Fast approximation of the stroke's bounding rect.
2224     // This yields a slightly oversized rect but is very fast
2225     // compared to Path::strokeBoundingRect().
2226     static const float root2 = sqrtf(2);
2227     float delta = state().m_lineWidth / 2;
2228     if (state().m_lineJoin == MiterJoin)
2229         delta *= state().m_miterLimit;
2230     else if (state().m_lineCap == SquareCap)
2231         delta *= root2;
2232
2233     rect.inflate(delta);
2234 }
2235
2236 const Font& CanvasRenderingContext2D::accessFont()
2237 {
2238     // This needs style to be up to date, but can't assert so because drawTextInternal
2239     // can invalidate style before this is called (e.g. drawingContext invalidates style).
2240     if (!state().m_realizedFont)
2241         setFont(state().m_unparsedFont);
2242     return state().m_font;
2243 }
2244
2245 int CanvasRenderingContext2D::getFontBaseline(const FontMetrics& fontMetrics) const
2246 {
2247     switch (state().m_textBaseline) {
2248     case TopTextBaseline:
2249         return fontMetrics.ascent();
2250     case HangingTextBaseline:
2251         // According to http://wiki.apache.org/xmlgraphics-fop/LineLayout/AlignmentHandling
2252         // "FOP (Formatting Objects Processor) puts the hanging baseline at 80% of the ascender height"
2253         return (fontMetrics.ascent() * 4) / 5;
2254     case BottomTextBaseline:
2255     case IdeographicTextBaseline:
2256         return -fontMetrics.descent();
2257     case MiddleTextBaseline:
2258         return -fontMetrics.descent() + fontMetrics.height() / 2;
2259     case AlphabeticTextBaseline:
2260     default:
2261         // Do nothing.
2262         break;
2263     }
2264     return 0;
2265 }
2266
2267 blink::WebLayer* CanvasRenderingContext2D::platformLayer() const
2268 {
2269     return canvas()->buffer() ? canvas()->buffer()->platformLayer() : 0;
2270 }
2271
2272 bool CanvasRenderingContext2D::imageSmoothingEnabled() const
2273 {
2274     return state().m_imageSmoothingEnabled;
2275 }
2276
2277 void CanvasRenderingContext2D::setImageSmoothingEnabled(bool enabled)
2278 {
2279     if (enabled == state().m_imageSmoothingEnabled)
2280         return;
2281
2282     realizeSaves();
2283     modifiableState().m_imageSmoothingEnabled = enabled;
2284     GraphicsContext* c = drawingContext();
2285     if (c)
2286         c->setImageInterpolationQuality(enabled ? CanvasDefaultInterpolationQuality : InterpolationNone);
2287 }
2288
2289 PassRefPtrWillBeRawPtr<Canvas2DContextAttributes> CanvasRenderingContext2D::getContextAttributes() const
2290 {
2291     RefPtrWillBeRawPtr<Canvas2DContextAttributes> attributes = Canvas2DContextAttributes::create();
2292     attributes->setAlpha(m_hasAlpha);
2293     return attributes.release();
2294 }
2295
2296 void CanvasRenderingContext2D::drawFocusIfNeeded(Element* element)
2297 {
2298     drawFocusIfNeededInternal(m_path, element);
2299 }
2300
2301 void CanvasRenderingContext2D::drawFocusIfNeeded(Path2D* path2d, Element* element)
2302 {
2303     drawFocusIfNeededInternal(path2d->path(), element);
2304 }
2305
2306 void CanvasRenderingContext2D::drawFocusIfNeededInternal(const Path& path, Element* element)
2307 {
2308     if (!focusRingCallIsValid(path, element))
2309         return;
2310
2311     // Note: we need to check document->focusedElement() rather than just calling
2312     // element->focused(), because element->focused() isn't updated until after
2313     // focus events fire.
2314     if (element->document().focusedElement() == element)
2315         drawFocusRing(path);
2316 }
2317
2318 bool CanvasRenderingContext2D::focusRingCallIsValid(const Path& path, Element* element)
2319 {
2320     ASSERT(element);
2321     if (!state().m_invertibleCTM)
2322         return false;
2323     if (path.isEmpty())
2324         return false;
2325     if (!element->isDescendantOf(canvas()))
2326         return false;
2327
2328     return true;
2329 }
2330
2331 void CanvasRenderingContext2D::drawFocusRing(const Path& path)
2332 {
2333     GraphicsContext* c = drawingContext();
2334     if (!c)
2335         return;
2336
2337     // These should match the style defined in html.css.
2338     Color focusRingColor = RenderTheme::theme().focusRingColor();
2339     const int focusRingWidth = 5;
2340     const int focusRingOutline = 0;
2341
2342     // We need to add focusRingWidth to dirtyRect.
2343     StrokeData strokeData;
2344     strokeData.setThickness(focusRingWidth);
2345
2346     FloatRect dirtyRect;
2347     if (!computeDirtyRect(path.strokeBoundingRect(strokeData), &dirtyRect))
2348         return;
2349
2350     c->save();
2351     c->setAlphaAsFloat(1.0);
2352     c->clearShadow();
2353     c->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
2354     c->drawFocusRing(path, focusRingWidth, focusRingOutline, focusRingColor);
2355     c->restore();
2356     validateStateStack();
2357     didDraw(dirtyRect);
2358 }
2359
2360 void CanvasRenderingContext2D::addHitRegion(ExceptionState& exceptionState)
2361 {
2362     addHitRegion(Dictionary(), exceptionState);
2363 }
2364
2365 void CanvasRenderingContext2D::addHitRegion(const Dictionary& options, ExceptionState& exceptionState)
2366 {
2367     HitRegionOptions passOptions;
2368
2369     options.getWithUndefinedOrNullCheck("id", passOptions.id);
2370     options.getWithUndefinedOrNullCheck("control", passOptions.control);
2371     if (passOptions.id.isEmpty() && !passOptions.control) {
2372         exceptionState.throwDOMException(NotSupportedError, "Both id and control are null.");
2373         return;
2374     }
2375
2376     RefPtrWillBeMember<Path2D> path2d;
2377     options.getWithUndefinedOrNullCheck("path", path2d);
2378     Path hitRegionPath = path2d ? path2d->path() : m_path;
2379
2380     FloatRect clipBounds;
2381     GraphicsContext* context = drawingContext();
2382
2383     if (hitRegionPath.isEmpty() || !context || !state().m_invertibleCTM
2384         || !context->getTransformedClipBounds(&clipBounds)) {
2385         exceptionState.throwDOMException(NotSupportedError, "The specified path has no pixels.");
2386         return;
2387     }
2388
2389     hitRegionPath.transform(state().m_transform);
2390
2391     if (hasClip()) {
2392         // FIXME: The hit regions should take clipping region into account.
2393         // However, we have no way to get the region from canvas state stack by now.
2394         // See http://crbug.com/387057
2395         exceptionState.throwDOMException(NotSupportedError, "The specified path has no pixels.");
2396         return;
2397     }
2398
2399     passOptions.path = hitRegionPath;
2400
2401     String fillRuleString;
2402     options.getWithUndefinedOrNullCheck("fillRule", fillRuleString);
2403     if (fillRuleString.isEmpty() || fillRuleString != "evenodd")
2404         passOptions.fillRule = RULE_NONZERO;
2405     else
2406         passOptions.fillRule = RULE_EVENODD;
2407
2408     addHitRegionInternal(passOptions, exceptionState);
2409 }
2410
2411 void CanvasRenderingContext2D::addHitRegionInternal(const HitRegionOptions& options, ExceptionState& exceptionState)
2412 {
2413     if (!m_hitRegionManager)
2414         m_hitRegionManager = HitRegionManager::create();
2415
2416     // Remove previous region (with id or control)
2417     m_hitRegionManager->removeHitRegionById(options.id);
2418     m_hitRegionManager->removeHitRegionByControl(options.control.get());
2419
2420     RefPtrWillBeRawPtr<HitRegion> hitRegion = HitRegion::create(options);
2421     hitRegion->updateAccessibility(canvas());
2422     m_hitRegionManager->addHitRegion(hitRegion.release());
2423 }
2424
2425 void CanvasRenderingContext2D::removeHitRegion(const String& id)
2426 {
2427     if (m_hitRegionManager)
2428         m_hitRegionManager->removeHitRegionById(id);
2429 }
2430
2431 void CanvasRenderingContext2D::clearHitRegions()
2432 {
2433     if (m_hitRegionManager)
2434         m_hitRegionManager->removeAllHitRegions();
2435 }
2436
2437 HitRegion* CanvasRenderingContext2D::hitRegionAtPoint(const LayoutPoint& point)
2438 {
2439     if (m_hitRegionManager)
2440         return m_hitRegionManager->getHitRegionAtPoint(point);
2441
2442     return 0;
2443 }
2444
2445 unsigned CanvasRenderingContext2D::hitRegionsCount() const
2446 {
2447     if (m_hitRegionManager)
2448         return m_hitRegionManager->getHitRegionsCount();
2449
2450     return 0;
2451 }
2452
2453 } // namespace blink