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.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
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.
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.
34 #include "core/html/canvas/CanvasRenderingContext2D.h"
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"
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;
81 static bool contextLostRestoredEventsEnabled()
83 return RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled();
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)
98 m_stateStack.append(adoptPtrWillBeNoop(new State()));
99 ScriptWrappable::init(this);
102 void CanvasRenderingContext2D::unwindStateStack()
104 if (size_t stackSize = m_stateStack.size()) {
105 if (GraphicsContext* context = canvas()->existingDrawingContext()) {
112 CanvasRenderingContext2D::~CanvasRenderingContext2D()
116 void CanvasRenderingContext2D::validateStateStack()
119 GraphicsContext* context = canvas()->existingDrawingContext();
120 if (context && !context->contextDisabled())
121 ASSERT(context->saveCount() == m_stateStack.size());
125 bool CanvasRenderingContext2D::isAccelerated() const
127 if (!canvas()->hasImageBuffer())
129 GraphicsContext* context = drawingContext();
130 return context && context->isAccelerated();
133 bool CanvasRenderingContext2D::isContextLost() const
135 return m_isContextLost;
138 void CanvasRenderingContext2D::loseContext()
142 m_isContextLost = true;
143 m_dispatchContextLostEventTimer.startOneShot(0, FROM_HERE);
146 void CanvasRenderingContext2D::restoreContext()
148 if (!m_contextRestorable)
150 // This code path is for restoring from an eviction
151 // Restoring from surface failure is handled internally
152 ASSERT(m_isContextLost && !canvas()->hasImageBuffer());
154 if (canvas()->buffer()) {
155 if (contextLostRestoredEventsEnabled()) {
156 m_dispatchContextRestoredEventTimer.startOneShot(0, FROM_HERE);
158 // legacy synchronous context restoration.
160 m_isContextLost = false;
165 void CanvasRenderingContext2D::trace(Visitor* visitor)
168 visitor->trace(m_stateStack);
169 visitor->trace(m_fetchedFonts);
170 visitor->trace(m_hitRegionManager);
172 CanvasRenderingContext::trace(visitor);
175 void CanvasRenderingContext2D::dispatchContextLostEvent(Timer<CanvasRenderingContext2D>*)
177 if (contextLostRestoredEventsEnabled()) {
178 RefPtrWillBeRawPtr<Event> event = Event::createCancelable(EventTypeNames::contextlost);
179 canvas()->dispatchEvent(event);
180 if (event->defaultPrevented()) {
181 m_contextRestorable = false;
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);
193 void CanvasRenderingContext2D::tryRestoreContextEvent(Timer<CanvasRenderingContext2D>* timer)
195 if (!m_isContextLost) {
196 // Canvas was already restored (possibly thanks to a resize), so stop trying.
197 m_tryRestoreContextEventTimer.stop();
200 if (canvas()->hasImageBuffer() && canvas()->buffer()->restoreSurface()) {
201 m_tryRestoreContextEventTimer.stop();
202 dispatchContextRestoredEvent(0);
205 if (++m_tryRestoreContextAttemptCount > MaxTryRestoreContextAttempts)
206 canvas()->discardImageBuffer();
208 if (!canvas()->hasImageBuffer()) {
209 // final attempt: allocate a brand new image buffer instead of restoring
211 if (canvas()->buffer())
212 dispatchContextRestoredEvent(0);
216 void CanvasRenderingContext2D::dispatchContextRestoredEvent(Timer<CanvasRenderingContext2D>*)
218 if (!m_isContextLost)
221 m_isContextLost = false;
222 if (contextLostRestoredEventsEnabled()) {
223 RefPtrWillBeRawPtr<Event> event(Event::create(EventTypeNames::contextrestored));
224 canvas()->dispatchEvent(event);
228 void CanvasRenderingContext2D::reset()
230 validateStateStack();
232 m_stateStack.resize(1);
233 m_stateStack.first() = adoptPtrWillBeNoop(new State());
235 validateStateStack();
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))
248 , m_lineJoin(MiterJoin)
251 , m_shadowColor(Color::transparent)
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)
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)
295 static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this);
298 CanvasRenderingContext2D::State& CanvasRenderingContext2D::State::operator=(const State& other)
305 static_cast<CSSFontSelector*>(m_font.fontSelector())->unregisterForInvalidationCallbacks(this);
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;
334 static_cast<CSSFontSelector*>(m_font.fontSelector())->registerForInvalidationCallbacks(this);
339 CanvasRenderingContext2D::State::~State()
343 static_cast<CSSFontSelector*>(m_font.fontSelector())->unregisterForInvalidationCallbacks(this);
347 void CanvasRenderingContext2D::State::fontsNeedUpdate(CSSFontSelector* fontSelector)
349 ASSERT_ARG(fontSelector, fontSelector == m_font.fontSelector());
350 ASSERT(m_realizedFont);
352 m_font.update(fontSelector);
355 void CanvasRenderingContext2D::State::trace(Visitor* visitor)
357 visitor->trace(m_strokeStyle);
358 visitor->trace(m_fillStyle);
359 CSSFontSelectorClient::trace(visitor);
362 void CanvasRenderingContext2D::realizeSaves()
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();
379 validateStateStack();
383 void CanvasRenderingContext2D::restore()
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;
391 ASSERT(m_stateStack.size() >= 1);
392 if (m_stateStack.size() <= 1)
394 m_path.transform(state().m_transform);
395 m_stateStack.removeLast();
396 m_path.transform(state().m_transform.inverse());
397 GraphicsContext* c = drawingContext();
400 validateStateStack();
403 CanvasStyle* CanvasRenderingContext2D::strokeStyle() const
405 return state().m_strokeStyle.get();
408 void CanvasRenderingContext2D::setStrokeStyle(PassRefPtrWillBeRawPtr<CanvasStyle> prpStyle)
410 RefPtrWillBeRawPtr<CanvasStyle> style = prpStyle;
415 if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentColor(*style))
418 if (style->isCurrentColor()) {
419 if (style->hasOverrideAlpha())
420 style = CanvasStyle::createFromRGBA(colorWithOverrideAlpha(currentColor(canvas()), style->overrideAlpha()));
422 style = CanvasStyle::createFromRGBA(currentColor(canvas()));
423 } else if (canvas()->originClean() && style->canvasPattern() && !style->canvasPattern()->originClean()) {
424 canvas()->setOriginTainted();
428 modifiableState().m_strokeStyle = style.release();
429 GraphicsContext* c = drawingContext();
432 state().m_strokeStyle->applyStrokeColor(c);
433 modifiableState().m_unparsedStrokeColor = String();
436 CanvasStyle* CanvasRenderingContext2D::fillStyle() const
438 return state().m_fillStyle.get();
441 void CanvasRenderingContext2D::setFillStyle(PassRefPtrWillBeRawPtr<CanvasStyle> prpStyle)
443 RefPtrWillBeRawPtr<CanvasStyle> style = prpStyle;
448 if (state().m_fillStyle && state().m_fillStyle->isEquivalentColor(*style))
451 if (style->isCurrentColor()) {
452 if (style->hasOverrideAlpha())
453 style = CanvasStyle::createFromRGBA(colorWithOverrideAlpha(currentColor(canvas()), style->overrideAlpha()));
455 style = CanvasStyle::createFromRGBA(currentColor(canvas()));
456 } else if (canvas()->originClean() && style->canvasPattern() && !style->canvasPattern()->originClean()) {
457 canvas()->setOriginTainted();
461 modifiableState().m_fillStyle = style.release();
462 GraphicsContext* c = drawingContext();
465 state().m_fillStyle->applyFillColor(c);
466 modifiableState().m_unparsedFillColor = String();
469 float CanvasRenderingContext2D::lineWidth() const
471 return state().m_lineWidth;
474 void CanvasRenderingContext2D::setLineWidth(float width)
476 if (!(std::isfinite(width) && width > 0))
478 if (state().m_lineWidth == width)
481 modifiableState().m_lineWidth = width;
482 GraphicsContext* c = drawingContext();
485 c->setStrokeThickness(width);
488 String CanvasRenderingContext2D::lineCap() const
490 return lineCapName(state().m_lineCap);
493 void CanvasRenderingContext2D::setLineCap(const String& s)
496 if (!parseLineCap(s, cap))
498 if (state().m_lineCap == cap)
501 modifiableState().m_lineCap = cap;
502 GraphicsContext* c = drawingContext();
508 String CanvasRenderingContext2D::lineJoin() const
510 return lineJoinName(state().m_lineJoin);
513 void CanvasRenderingContext2D::setLineJoin(const String& s)
516 if (!parseLineJoin(s, join))
518 if (state().m_lineJoin == join)
521 modifiableState().m_lineJoin = join;
522 GraphicsContext* c = drawingContext();
525 c->setLineJoin(join);
528 float CanvasRenderingContext2D::miterLimit() const
530 return state().m_miterLimit;
533 void CanvasRenderingContext2D::setMiterLimit(float limit)
535 if (!(std::isfinite(limit) && limit > 0))
537 if (state().m_miterLimit == limit)
540 modifiableState().m_miterLimit = limit;
541 GraphicsContext* c = drawingContext();
544 c->setMiterLimit(limit);
547 float CanvasRenderingContext2D::shadowOffsetX() const
549 return state().m_shadowOffset.width();
552 void CanvasRenderingContext2D::setShadowOffsetX(float x)
554 if (!std::isfinite(x))
556 if (state().m_shadowOffset.width() == x)
559 modifiableState().m_shadowOffset.setWidth(x);
563 float CanvasRenderingContext2D::shadowOffsetY() const
565 return state().m_shadowOffset.height();
568 void CanvasRenderingContext2D::setShadowOffsetY(float y)
570 if (!std::isfinite(y))
572 if (state().m_shadowOffset.height() == y)
575 modifiableState().m_shadowOffset.setHeight(y);
579 float CanvasRenderingContext2D::shadowBlur() const
581 return state().m_shadowBlur;
584 void CanvasRenderingContext2D::setShadowBlur(float blur)
586 if (!(std::isfinite(blur) && blur >= 0))
588 if (state().m_shadowBlur == blur)
591 modifiableState().m_shadowBlur = blur;
595 String CanvasRenderingContext2D::shadowColor() const
597 return Color(state().m_shadowColor).serialized();
600 void CanvasRenderingContext2D::setShadowColor(const String& color)
603 if (!parseColorOrCurrentColor(rgba, color, canvas()))
605 if (state().m_shadowColor == rgba)
608 modifiableState().m_shadowColor = rgba;
612 const Vector<float>& CanvasRenderingContext2D::getLineDash() const
614 return state().m_lineDash;
617 static bool lineDashSequenceIsValid(const Vector<float>& dash)
619 for (size_t i = 0; i < dash.size(); i++) {
620 if (!std::isfinite(dash[i]) || dash[i] < 0)
626 void CanvasRenderingContext2D::setLineDash(const Vector<float>& dash)
628 if (!lineDashSequenceIsValid(dash))
632 modifiableState().m_lineDash = dash;
633 // Spec requires the concatenation of two copies the dash list when the
634 // number of elements is odd
636 modifiableState().m_lineDash.appendVector(dash);
641 float CanvasRenderingContext2D::lineDashOffset() const
643 return state().m_lineDashOffset;
646 void CanvasRenderingContext2D::setLineDashOffset(float offset)
648 if (!std::isfinite(offset) || state().m_lineDashOffset == offset)
652 modifiableState().m_lineDashOffset = offset;
656 void CanvasRenderingContext2D::applyLineDash() const
658 GraphicsContext* c = drawingContext();
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);
667 float CanvasRenderingContext2D::globalAlpha() const
669 return state().m_globalAlpha;
672 void CanvasRenderingContext2D::setGlobalAlpha(float alpha)
674 if (!(alpha >= 0 && alpha <= 1))
676 if (state().m_globalAlpha == alpha)
679 modifiableState().m_globalAlpha = alpha;
680 GraphicsContext* c = drawingContext();
683 c->setAlphaAsFloat(alpha);
686 String CanvasRenderingContext2D::globalCompositeOperation() const
688 return compositeOperatorName(state().m_globalComposite, state().m_globalBlend);
691 void CanvasRenderingContext2D::setGlobalCompositeOperation(const String& operation)
693 CompositeOperator op = CompositeSourceOver;
694 blink::WebBlendMode blendMode = blink::WebBlendModeNormal;
695 if (!parseCompositeAndBlendOperator(operation, op, blendMode))
697 if ((state().m_globalComposite == op) && (state().m_globalBlend == blendMode))
700 modifiableState().m_globalComposite = op;
701 modifiableState().m_globalBlend = blendMode;
702 GraphicsContext* c = drawingContext();
705 c->setCompositeOperation(op, blendMode);
708 void CanvasRenderingContext2D::setCurrentTransform(PassRefPtr<SVGMatrixTearOff> passMatrixTearOff)
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());
715 void CanvasRenderingContext2D::scale(float sx, float sy)
717 GraphicsContext* c = drawingContext();
720 if (!state().m_invertibleCTM)
723 if (!std::isfinite(sx) | !std::isfinite(sy))
726 AffineTransform newTransform = state().m_transform;
727 newTransform.scaleNonUniform(sx, sy);
728 if (state().m_transform == newTransform)
733 if (!newTransform.isInvertible()) {
734 modifiableState().m_invertibleCTM = false;
738 modifiableState().m_transform = newTransform;
740 m_path.transform(AffineTransform().scaleNonUniform(1.0 / sx, 1.0 / sy));
743 void CanvasRenderingContext2D::rotate(float angleInRadians)
745 GraphicsContext* c = drawingContext();
748 if (!state().m_invertibleCTM)
751 if (!std::isfinite(angleInRadians))
754 AffineTransform newTransform = state().m_transform;
755 newTransform.rotateRadians(angleInRadians);
756 if (state().m_transform == newTransform)
761 if (!newTransform.isInvertible()) {
762 modifiableState().m_invertibleCTM = false;
766 modifiableState().m_transform = newTransform;
767 c->rotate(angleInRadians);
768 m_path.transform(AffineTransform().rotateRadians(-angleInRadians));
771 void CanvasRenderingContext2D::translate(float tx, float ty)
773 GraphicsContext* c = drawingContext();
776 if (!state().m_invertibleCTM)
779 if (!std::isfinite(tx) | !std::isfinite(ty))
782 AffineTransform newTransform = state().m_transform;
783 newTransform.translate(tx, ty);
784 if (state().m_transform == newTransform)
789 if (!newTransform.isInvertible()) {
790 modifiableState().m_invertibleCTM = false;
794 modifiableState().m_transform = newTransform;
795 c->translate(tx, ty);
796 m_path.transform(AffineTransform().translate(-tx, -ty));
799 void CanvasRenderingContext2D::transform(float m11, float m12, float m21, float m22, float dx, float dy)
801 GraphicsContext* c = drawingContext();
804 if (!state().m_invertibleCTM)
807 if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
810 AffineTransform transform(m11, m12, m21, m22, dx, dy);
811 AffineTransform newTransform = state().m_transform * transform;
812 if (state().m_transform == newTransform)
817 modifiableState().m_transform = newTransform;
818 if (!newTransform.isInvertible()) {
819 modifiableState().m_invertibleCTM = false;
823 c->concatCTM(transform);
824 m_path.transform(transform.inverse());
827 void CanvasRenderingContext2D::resetTransform()
829 GraphicsContext* c = drawingContext();
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)
841 // resetTransform() resolves the non-invertible CTM state.
842 modifiableState().m_transform.makeIdentity();
843 modifiableState().m_invertibleCTM = true;
844 c->setCTM(canvas()->baseTransform());
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.
852 void CanvasRenderingContext2D::setTransform(float m11, float m12, float m21, float m22, float dx, float dy)
854 GraphicsContext* c = drawingContext();
858 if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
862 transform(m11, m12, m21, m22, dx, dy);
865 void CanvasRenderingContext2D::setStrokeColor(const String& color)
867 if (color == state().m_unparsedStrokeColor)
870 setStrokeStyle(CanvasStyle::createFromString(color));
871 modifiableState().m_unparsedStrokeColor = color;
874 void CanvasRenderingContext2D::setStrokeColor(float grayLevel)
876 if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, 1.0f))
878 setStrokeStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, 1.0f));
881 void CanvasRenderingContext2D::setStrokeColor(const String& color, float alpha)
883 setStrokeStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha));
886 void CanvasRenderingContext2D::setStrokeColor(float grayLevel, float alpha)
888 if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
890 setStrokeStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, alpha));
893 void CanvasRenderingContext2D::setStrokeColor(float r, float g, float b, float a)
895 if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentRGBA(r, g, b, a))
897 setStrokeStyle(CanvasStyle::createFromRGBAChannels(r, g, b, a));
900 void CanvasRenderingContext2D::setStrokeColor(float c, float m, float y, float k, float a)
902 if (state().m_strokeStyle && state().m_strokeStyle->isEquivalentCMYKA(c, m, y, k, a))
904 setStrokeStyle(CanvasStyle::createFromCMYKAChannels(c, m, y, k, a));
907 void CanvasRenderingContext2D::setFillColor(const String& color)
909 if (color == state().m_unparsedFillColor)
912 setFillStyle(CanvasStyle::createFromString(color));
913 modifiableState().m_unparsedFillColor = color;
916 void CanvasRenderingContext2D::setFillColor(float grayLevel)
918 if (state().m_fillStyle && state().m_fillStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, 1.0f))
920 setFillStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, 1.0f));
923 void CanvasRenderingContext2D::setFillColor(const String& color, float alpha)
925 setFillStyle(CanvasStyle::createFromStringWithOverrideAlpha(color, alpha));
928 void CanvasRenderingContext2D::setFillColor(float grayLevel, float alpha)
930 if (state().m_fillStyle && state().m_fillStyle->isEquivalentRGBA(grayLevel, grayLevel, grayLevel, alpha))
932 setFillStyle(CanvasStyle::createFromGrayLevelWithAlpha(grayLevel, alpha));
935 void CanvasRenderingContext2D::setFillColor(float r, float g, float b, float a)
937 if (state().m_fillStyle && state().m_fillStyle->isEquivalentRGBA(r, g, b, a))
939 setFillStyle(CanvasStyle::createFromRGBAChannels(r, g, b, a));
942 void CanvasRenderingContext2D::setFillColor(float c, float m, float y, float k, float a)
944 if (state().m_fillStyle && state().m_fillStyle->isEquivalentCMYKA(c, m, y, k, a))
946 setFillStyle(CanvasStyle::createFromCMYKAChannels(c, m, y, k, a));
949 void CanvasRenderingContext2D::beginPath()
954 static bool validateRectForCanvas(float& x, float& y, float& width, float& height)
956 if (!std::isfinite(x) | !std::isfinite(y) | !std::isfinite(width) | !std::isfinite(height))
959 if (!width && !height)
975 static bool isFullCanvasCompositeMode(CompositeOperator op)
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;
983 static WindRule parseWinding(const String& windingRuleString)
985 if (windingRuleString == "nonzero")
987 if (windingRuleString == "evenodd")
990 ASSERT_NOT_REACHED();
994 void CanvasRenderingContext2D::fillInternal(const Path& path, const String& windingRuleString)
996 if (path.isEmpty()) {
999 GraphicsContext* c = drawingContext();
1003 if (!state().m_invertibleCTM) {
1006 FloatRect clipBounds;
1007 if (!c->getTransformedClipBounds(&clipBounds)) {
1011 // If gradient size is zero, then paint nothing.
1012 Gradient* gradient = c->fillGradient();
1013 if (gradient && gradient->isZeroSize()) {
1017 WindRule windRule = c->fillRule();
1018 c->setFillRule(parseWinding(windingRuleString));
1020 if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1021 fullCanvasCompositedFill(path);
1022 didDraw(clipBounds);
1023 } else if (state().m_globalComposite == CompositeCopy) {
1026 didDraw(clipBounds);
1028 FloatRect dirtyRect;
1029 if (computeDirtyRect(path.boundingRect(), clipBounds, &dirtyRect)) {
1035 c->setFillRule(windRule);
1038 void CanvasRenderingContext2D::fill(const String& windingRuleString)
1040 fillInternal(m_path, windingRuleString);
1043 void CanvasRenderingContext2D::fill(Path2D* domPath, const String& windingRuleString)
1045 fillInternal(domPath->path(), windingRuleString);
1048 void CanvasRenderingContext2D::strokeInternal(const Path& path)
1050 if (path.isEmpty()) {
1053 GraphicsContext* c = drawingContext();
1057 if (!state().m_invertibleCTM) {
1060 FloatRect clipBounds;
1061 if (!c->getTransformedClipBounds(&clipBounds))
1064 // If gradient size is zero, then paint nothing.
1065 Gradient* gradient = c->strokeGradient();
1066 if (gradient && gradient->isZeroSize()) {
1070 if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1071 fullCanvasCompositedStroke(path);
1072 didDraw(clipBounds);
1073 } else if (state().m_globalComposite == CompositeCopy) {
1075 c->strokePath(path);
1076 didDraw(clipBounds);
1078 FloatRect bounds = path.boundingRect();
1079 inflateStrokeRect(bounds);
1080 FloatRect dirtyRect;
1081 if (computeDirtyRect(bounds, clipBounds, &dirtyRect)) {
1082 c->strokePath(path);
1088 void CanvasRenderingContext2D::stroke()
1090 strokeInternal(m_path);
1093 void CanvasRenderingContext2D::stroke(Path2D* domPath)
1095 strokeInternal(domPath->path());
1098 void CanvasRenderingContext2D::clipInternal(const Path& path, const String& windingRuleString)
1100 GraphicsContext* c = drawingContext();
1104 if (!state().m_invertibleCTM) {
1109 c->canvasClip(path, parseWinding(windingRuleString));
1110 modifiableState().m_hasClip = true;
1113 void CanvasRenderingContext2D::clip(const String& windingRuleString)
1115 clipInternal(m_path, windingRuleString);
1118 void CanvasRenderingContext2D::clip(Path2D* domPath, const String& windingRuleString)
1120 clipInternal(domPath->path(), windingRuleString);
1123 bool CanvasRenderingContext2D::isPointInPath(const float x, const float y, const String& windingRuleString)
1125 return isPointInPathInternal(m_path, x, y, windingRuleString);
1128 bool CanvasRenderingContext2D::isPointInPath(Path2D* domPath, const float x, const float y, const String& windingRuleString)
1130 return isPointInPathInternal(domPath->path(), x, y, windingRuleString);
1133 bool CanvasRenderingContext2D::isPointInPathInternal(const Path& path, const float x, const float y, const String& windingRuleString)
1135 GraphicsContext* c = drawingContext();
1138 if (!state().m_invertibleCTM)
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()))
1147 return path.contains(transformedPoint, parseWinding(windingRuleString));
1150 bool CanvasRenderingContext2D::isPointInStroke(const float x, const float y)
1152 return isPointInStrokeInternal(m_path, x, y);
1155 bool CanvasRenderingContext2D::isPointInStroke(Path2D* domPath, const float x, const float y)
1157 return isPointInStrokeInternal(domPath->path(), x, y);
1160 bool CanvasRenderingContext2D::isPointInStrokeInternal(const Path& path, const float x, const float y)
1162 GraphicsContext* c = drawingContext();
1165 if (!state().m_invertibleCTM)
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()))
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);
1183 void CanvasRenderingContext2D::scrollPathIntoView()
1185 scrollPathIntoViewInternal(m_path);
1188 void CanvasRenderingContext2D::scrollPathIntoView(Path2D* path2d)
1190 scrollPathIntoViewInternal(path2d->path());
1193 void CanvasRenderingContext2D::scrollPathIntoViewInternal(const Path& path)
1195 RenderObject* renderer = canvas()->renderer();
1196 RenderBox* renderBox = canvas()->renderBox();
1197 if (!renderer || !renderBox || !state().m_invertibleCTM || path.isEmpty())
1200 canvas()->document().updateLayoutIgnorePendingStylesheets();
1202 // Apply transformation and get the bounding rect
1203 Path transformedPath = path;
1204 transformedPath.transform(state().m_transform);
1205 FloatRect boundingRect = transformedPath.boundingRect();
1207 // Offset by the canvas rect
1208 LayoutRect pathRect(boundingRect);
1209 IntRect canvasRect = renderBox->absoluteContentBox();
1210 pathRect.move(canvasRect.x(), canvasRect.y());
1212 renderer->scrollRectToVisible(
1213 pathRect, ScrollAlignment::alignCenterAlways, ScrollAlignment::alignTopAlways);
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
1219 void CanvasRenderingContext2D::clearRect(float x, float y, float width, float height)
1221 if (!validateRectForCanvas(x, y, width, height))
1223 GraphicsContext* context = drawingContext();
1226 if (!state().m_invertibleCTM)
1228 FloatRect rect(x, y, width, height);
1230 FloatRect dirtyRect;
1231 if (!computeDirtyRect(rect, &dirtyRect))
1235 if (shouldDrawShadows()) {
1238 context->clearShadow();
1240 if (state().m_globalAlpha != 1) {
1245 context->setAlphaAsFloat(1);
1247 if (state().m_globalComposite != CompositeSourceOver) {
1252 context->setCompositeOperation(CompositeSourceOver);
1254 context->clearRect(rect);
1255 if (m_hitRegionManager)
1256 m_hitRegionManager->removeHitRegionsInRect(rect, state().m_transform);
1260 validateStateStack();
1264 void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height)
1266 if (!validateRectForCanvas(x, y, width, height))
1269 GraphicsContext* c = drawingContext();
1272 if (!state().m_invertibleCTM)
1274 FloatRect clipBounds;
1275 if (!c->getTransformedClipBounds(&clipBounds))
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())
1285 FloatRect rect(x, y, width, height);
1286 if (rectContainsTransformedRect(rect, clipBounds)) {
1288 didDraw(clipBounds);
1289 } else if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1290 fullCanvasCompositedFill(rect);
1291 didDraw(clipBounds);
1292 } else if (state().m_globalComposite == CompositeCopy) {
1295 didDraw(clipBounds);
1297 FloatRect dirtyRect;
1298 if (computeDirtyRect(rect, clipBounds, &dirtyRect)) {
1305 void CanvasRenderingContext2D::strokeRect(float x, float y, float width, float height)
1307 if (!validateRectForCanvas(x, y, width, height))
1310 if (!(state().m_lineWidth >= 0))
1313 GraphicsContext* c = drawingContext();
1316 if (!state().m_invertibleCTM)
1318 FloatRect clipBounds;
1319 if (!c->getTransformedClipBounds(&clipBounds))
1322 // If gradient size is zero, then paint nothing.
1323 Gradient* gradient = c->strokeGradient();
1324 if (gradient && gradient->isZeroSize())
1327 FloatRect rect(x, y, width, height);
1329 if (isFullCanvasCompositeMode(state().m_globalComposite)) {
1330 fullCanvasCompositedStroke(rect);
1331 didDraw(clipBounds);
1332 } else if (state().m_globalComposite == CompositeCopy) {
1334 c->strokeRect(rect);
1335 didDraw(clipBounds);
1337 FloatRect boundingRect = rect;
1338 boundingRect.inflate(state().m_lineWidth / 2);
1339 FloatRect dirtyRect;
1340 if (computeDirtyRect(boundingRect, clipBounds, &dirtyRect)) {
1341 c->strokeRect(rect);
1347 void CanvasRenderingContext2D::setShadow(float width, float height, float blur)
1349 setShadow(FloatSize(width, height), blur, Color::transparent);
1352 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& color)
1355 if (!parseColorOrCurrentColor(rgba, color, canvas()))
1357 setShadow(FloatSize(width, height), blur, rgba);
1360 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float grayLevel)
1362 setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(grayLevel, grayLevel, grayLevel, 1));
1365 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, const String& color, float alpha)
1368 if (!parseColorOrCurrentColor(rgba, color, canvas()))
1370 setShadow(FloatSize(width, height), blur, colorWithOverrideAlpha(rgba, alpha));
1373 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float grayLevel, float alpha)
1375 setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(grayLevel, grayLevel, grayLevel, alpha));
1378 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float r, float g, float b, float a)
1380 setShadow(FloatSize(width, height), blur, makeRGBA32FromFloats(r, g, b, a));
1383 void CanvasRenderingContext2D::setShadow(float width, float height, float blur, float c, float m, float y, float k, float a)
1385 setShadow(FloatSize(width, height), blur, makeRGBAFromCMYKA(c, m, y, k, a));
1388 void CanvasRenderingContext2D::clearShadow()
1390 setShadow(FloatSize(), 0, Color::transparent);
1393 void CanvasRenderingContext2D::setShadow(const FloatSize& offset, float blur, RGBA32 color)
1395 if (state().m_shadowOffset == offset && state().m_shadowBlur == blur && state().m_shadowColor == color)
1397 bool wasDrawingShadows = shouldDrawShadows();
1399 modifiableState().m_shadowOffset = offset;
1400 modifiableState().m_shadowBlur = blur;
1401 modifiableState().m_shadowColor = color;
1402 if (!wasDrawingShadows && !shouldDrawShadows())
1407 void CanvasRenderingContext2D::applyShadow()
1409 GraphicsContext* c = drawingContext();
1413 if (shouldDrawShadows()) {
1414 c->setShadow(state().m_shadowOffset, state().m_shadowBlur, state().m_shadowColor,
1415 DrawLooperBuilder::ShadowIgnoresTransforms);
1421 bool CanvasRenderingContext2D::shouldDrawShadows() const
1423 return alphaChannel(state().m_shadowColor) && (state().m_shadowBlur || !state().m_shadowOffset.isZero());
1426 static inline FloatRect normalizeRect(const FloatRect& rect)
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()));
1434 static inline void clipRectsToImageRect(const FloatRect& imageRect, FloatRect* srcRect, FloatRect* dstRect)
1436 if (imageRect.contains(*srcRect))
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;
1445 srcRect->intersect(imageRect);
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);
1453 void CanvasRenderingContext2D::drawImage(CanvasImageSource* imageSource, float x, float y, ExceptionState& exceptionState)
1455 FloatSize destRectSize = imageSource->defaultDestinationSize();
1456 drawImage(imageSource, x, y, destRectSize.width(), destRectSize.height(), exceptionState);
1459 void CanvasRenderingContext2D::drawImage(CanvasImageSource* imageSource,
1460 float x, float y, float width, float height, ExceptionState& exceptionState)
1462 FloatSize sourceRectSize = imageSource->sourceSize();
1463 drawImage(imageSource, 0, 0, sourceRectSize.width(), sourceRectSize.height(), x, y, width, height, exceptionState);
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)
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);
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)
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())
1492 GraphicsContext* c = drawingContext();
1496 if (!state().m_invertibleCTM)
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)
1504 FloatRect clipBounds;
1505 if (!c->getTransformedClipBounds(&clipBounds))
1508 FloatRect srcRect = normalizeRect(FloatRect(sx, sy, sw, sh));
1509 FloatRect dstRect = normalizeRect(FloatRect(dx, dy, dw, dh));
1511 clipRectsToImageRect(FloatRect(FloatPoint(), imageSource->sourceSize()), &srcRect, &dstRect);
1513 imageSource->adjustDrawRects(&srcRect, &dstRect);
1515 if (srcRect.isEmpty())
1518 FloatRect dirtyRect = clipBounds;
1519 if (imageSource->isVideoElement()) {
1520 drawVideo(static_cast<HTMLVideoElement*>(imageSource), srcRect, dstRect);
1521 computeDirtyRect(dstRect, clipBounds, &dirtyRect);
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) {
1529 c->drawImage(image.get(), dstRect, srcRect, op, blendMode);
1531 FloatRect dirtyRect;
1532 computeDirtyRect(dstRect, clipBounds, &dirtyRect);
1533 c->drawImage(image.get(), dstRect, srcRect, op, blendMode);
1536 if (sourceImageStatus == ExternalSourceImageStatus && isAccelerated() && canvas()->buffer())
1537 canvas()->buffer()->flush();
1540 if (canvas()->originClean() && wouldTaintOrigin(imageSource))
1541 canvas()->setOriginTainted();
1546 void CanvasRenderingContext2D::drawVideo(HTMLVideoElement* video, FloatRect srcRect, FloatRect dstRect)
1548 GraphicsContext* c = drawingContext();
1549 GraphicsContextStateSaver stateSaver(*c);
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();
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)
1566 CompositeOperator op;
1567 blink::WebBlendMode blendOp = blink::WebBlendModeNormal;
1568 if (!parseCompositeAndBlendOperator(compositeOperation, op, blendOp) || blendOp != blink::WebBlendModeNormal)
1569 op = CompositeSourceOver;
1571 drawImageInternal(image, sx, sy, sw, sh, dx, dy, dw, dh, IGNORE_EXCEPTION, op, blendOp);
1574 void CanvasRenderingContext2D::setAlpha(float alpha)
1576 setGlobalAlpha(alpha);
1579 void CanvasRenderingContext2D::setCompositeOperation(const String& operation)
1581 setGlobalCompositeOperation(operation);
1584 void CanvasRenderingContext2D::clearCanvas()
1586 FloatRect canvasRect(0, 0, canvas()->width(), canvas()->height());
1587 GraphicsContext* c = drawingContext();
1592 c->setCTM(canvas()->baseTransform());
1593 c->clearRect(canvasRect);
1597 bool CanvasRenderingContext2D::rectContainsTransformedRect(const FloatRect& rect, const FloatRect& transformedRect) const
1599 FloatQuad quad(rect);
1600 FloatQuad transformedQuad(transformedRect);
1601 return state().m_transform.mapQuad(quad).containsQuad(transformedQuad);
1604 static void drawImageToContext(Image* image, GraphicsContext* context, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
1606 context->drawImage(image, dest, src, op);
1609 template<class T> void CanvasRenderingContext2D::fullCanvasCompositedDrawImage(T* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
1611 ASSERT(isFullCanvasCompositeMode(op));
1613 GraphicsContext* c = drawingContext();
1614 c->beginLayer(1, op);
1615 drawImageToContext(image, c, dest, src, CompositeSourceOver);
1619 static void fillPrimitive(const FloatRect& rect, GraphicsContext* context)
1621 context->fillRect(rect);
1624 static void fillPrimitive(const Path& path, GraphicsContext* context)
1626 context->fillPath(path);
1629 template<class T> void CanvasRenderingContext2D::fullCanvasCompositedFill(const T& area)
1631 ASSERT(isFullCanvasCompositeMode(state().m_globalComposite));
1633 GraphicsContext* c = drawingContext();
1635 c->beginLayer(1, state().m_globalComposite);
1636 CompositeOperator previousOperator = c->compositeOperation();
1637 c->setCompositeOperation(CompositeSourceOver);
1638 fillPrimitive(area, c);
1639 c->setCompositeOperation(previousOperator);
1643 static void strokePrimitive(const FloatRect& rect, GraphicsContext* context)
1645 context->strokeRect(rect);
1648 static void strokePrimitive(const Path& path, GraphicsContext* context)
1650 context->strokePath(path);
1653 template<class T> void CanvasRenderingContext2D::fullCanvasCompositedStroke(const T& area)
1655 ASSERT(isFullCanvasCompositeMode(state().m_globalComposite));
1657 GraphicsContext* c = drawingContext();
1659 c->beginLayer(1, state().m_globalComposite);
1660 CompositeOperator previousOperator = c->compositeOperation();
1661 c->setCompositeOperation(CompositeSourceOver);
1662 strokePrimitive(area, c);
1663 c->setCompositeOperation(previousOperator);
1667 PassRefPtrWillBeRawPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1)
1669 RefPtrWillBeRawPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), FloatPoint(x1, y1));
1670 return gradient.release();
1673 PassRefPtrWillBeRawPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& exceptionState)
1675 if (r0 < 0 || r1 < 0) {
1676 exceptionState.throwDOMException(IndexSizeError, String::format("The %s provided is less than 0.", r0 < 0 ? "r0" : "r1"));
1680 RefPtrWillBeRawPtr<CanvasGradient> gradient = CanvasGradient::create(FloatPoint(x0, y0), r0, FloatPoint(x1, y1), r1);
1681 return gradient.release();
1684 PassRefPtrWillBeRawPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(CanvasImageSource* imageSource,
1685 const String& repetitionType, ExceptionState& exceptionState)
1687 Pattern::RepeatMode repeatMode = CanvasPattern::parseRepetitionType(repetitionType, exceptionState);
1688 if (exceptionState.hadException())
1691 SourceImageStatus status;
1692 RefPtr<Image> imageForRendering = imageSource->getSourceImageForCanvas(CopySourceImageIfVolatile, &status);
1695 case NormalSourceImageStatus:
1697 case ZeroSizeCanvasSourceImageStatus:
1698 exceptionState.throwDOMException(InvalidStateError, String::format("The canvas %s is 0.", imageSource->sourceSize().width() ? "height" : "width"));
1700 case UndecodableSourceImageStatus:
1701 exceptionState.throwDOMException(InvalidStateError, "Source image is in the 'broken' state.");
1703 case InvalidSourceImageStatus:
1704 imageForRendering = Image::nullImage();
1706 case IncompleteSourceImageStatus:
1709 case ExternalSourceImageStatus: // should not happen when mode is CopySourceImageIfVolatile
1710 ASSERT_NOT_REACHED();
1713 ASSERT(imageForRendering);
1715 bool originClean = !wouldTaintOrigin(imageSource);
1717 return CanvasPattern::create(imageForRendering.release(), repeatMode, originClean);
1720 bool CanvasRenderingContext2D::computeDirtyRect(const FloatRect& localRect, FloatRect* dirtyRect)
1722 FloatRect clipBounds;
1723 if (!drawingContext()->getTransformedClipBounds(&clipBounds))
1725 return computeDirtyRect(localRect, clipBounds, dirtyRect);
1728 bool CanvasRenderingContext2D::computeDirtyRect(const FloatRect& localRect, const FloatRect& transformedClipBounds, FloatRect* dirtyRect)
1730 FloatRect canvasRect = state().m_transform.mapRect(localRect);
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);
1739 canvasRect.intersect(transformedClipBounds);
1740 if (canvasRect.isEmpty())
1744 *dirtyRect = canvasRect;
1749 void CanvasRenderingContext2D::didDraw(const FloatRect& dirtyRect)
1751 if (dirtyRect.isEmpty())
1754 canvas()->didDraw(dirtyRect);
1757 GraphicsContext* CanvasRenderingContext2D::drawingContext() const
1759 if (isContextLost())
1761 return canvas()->drawingContext();
1764 static PassRefPtrWillBeRawPtr<ImageData> createEmptyImageData(const IntSize& size)
1766 if (RefPtrWillBeRawPtr<ImageData> data = ImageData::create(size)) {
1767 data->data()->zeroFill();
1768 return data.release();
1774 PassRefPtrWillBeRawPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtrWillBeRawPtr<ImageData> imageData) const
1776 return createEmptyImageData(imageData->size());
1779 PassRefPtrWillBeRawPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& exceptionState) const
1782 exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width"));
1786 FloatSize logicalSize(fabs(sw), fabs(sh));
1787 if (!logicalSize.isExpressibleAsIntSize())
1790 IntSize size = expandedIntSize(logicalSize);
1791 if (size.width() < 1)
1793 if (size.height() < 1)
1796 return createEmptyImageData(size);
1799 PassRefPtrWillBeRawPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
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"));
1806 if (exceptionState.hadException())
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())
1826 IntRect imageDataRect = enclosingIntRect(logicalRect);
1827 ImageBuffer* buffer = canvas()->buffer();
1828 if (!buffer || isContextLost())
1829 return createEmptyImageData(imageDataRect.size());
1831 RefPtr<Uint8ClampedArray> byteArray = buffer->getImageData(Unmultiplied, imageDataRect);
1835 return ImageData::create(imageDataRect.size(), byteArray.release());
1838 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy)
1840 putImageData(data, dx, dy, 0, 0, data->width(), data->height());
1843 void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight)
1845 ImageBuffer* buffer = canvas()->buffer();
1849 if (dirtyWidth < 0) {
1850 dirtyX += dirtyWidth;
1851 dirtyWidth = -dirtyWidth;
1854 if (dirtyHeight < 0) {
1855 dirtyY += dirtyHeight;
1856 dirtyHeight = -dirtyHeight;
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())
1867 IntRect sourceRect(destRect);
1868 sourceRect.move(-destOffset);
1870 buffer->putByteArray(Unmultiplied, data->data(), IntSize(data->width(), data->height()), sourceRect, IntPoint(destOffset));
1875 String CanvasRenderingContext2D::font() const
1877 if (!state().m_realizedFont)
1880 StringBuilder serializedFont;
1881 const FontDescription& fontDescription = state().m_font.fontDescription();
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 ");
1890 serializedFont.appendNumber(fontDescription.computedPixelSize());
1891 serializedFont.appendLiteral("px");
1893 const FontFamily& firstFontFamily = fontDescription.family();
1894 for (const FontFamily* fontFamily = &firstFontFamily; fontFamily; fontFamily = fontFamily->next()) {
1895 if (fontFamily != &firstFontFamily)
1896 serializedFont.append(',');
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 + "\"";
1905 serializedFont.append(' ');
1906 serializedFont.append(family);
1909 return serializedFont.toString();
1912 void CanvasRenderingContext2D::setFont(const String& newFont)
1914 // The style resolution required for rendering text is not available in frame-less documents.
1915 if (!canvas()->document().frame())
1918 MutableStylePropertyMap::iterator i = m_fetchedFonts.find(newFont);
1919 RefPtrWillBeRawPtr<MutableStylePropertySet> parsedStyle = i != m_fetchedFonts.end() ? i->value : nullptr;
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);
1927 if (parsedStyle->isEmpty())
1930 String fontValue = parsedStyle->getPropertyValue(CSSPropertyFont);
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")
1937 // The parse succeeded.
1938 String newFontSafeCopy(newFont); // Create a string copy since newFont can be deleted inside realizeSaves.
1940 modifiableState().m_unparsedFont = newFontSafeCopy;
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);
1951 FontFamily fontFamily;
1952 fontFamily.setFamily(defaultFontFamily);
1954 FontDescription defaultFontDescription;
1955 defaultFontDescription.setFamily(fontFamily);
1956 defaultFontDescription.setSpecifiedSize(defaultFontSize);
1957 defaultFontDescription.setComputedSize(defaultFontSize);
1959 newStyle->setFontDescription(defaultFontDescription);
1962 newStyle->font().update(newStyle->font().fontSelector());
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),
1974 StyleResolver& styleResolver = canvas()->document().ensureStyleResolver();
1975 styleResolver.applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), newStyle.get());
1978 if (state().m_realizedFont)
1979 static_cast<CSSFontSelector*>(state().m_font.fontSelector())->unregisterForInvalidationCallbacks(&modifiableState());
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());
1987 String CanvasRenderingContext2D::textAlign() const
1989 return textAlignName(state().m_textAlign);
1992 void CanvasRenderingContext2D::setTextAlign(const String& s)
1995 if (!parseTextAlign(s, align))
1997 if (state().m_textAlign == align)
2000 modifiableState().m_textAlign = align;
2003 String CanvasRenderingContext2D::textBaseline() const
2005 return textBaselineName(state().m_textBaseline);
2008 void CanvasRenderingContext2D::setTextBaseline(const String& s)
2010 TextBaseline baseline;
2011 if (!parseTextBaseline(s, baseline))
2013 if (state().m_textBaseline == baseline)
2016 modifiableState().m_textBaseline = baseline;
2019 void CanvasRenderingContext2D::fillText(const String& text, float x, float y)
2021 drawTextInternal(text, x, y, true);
2024 void CanvasRenderingContext2D::fillText(const String& text, float x, float y, float maxWidth)
2026 drawTextInternal(text, x, y, true, maxWidth, true);
2029 void CanvasRenderingContext2D::strokeText(const String& text, float x, float y)
2031 drawTextInternal(text, x, y, false);
2034 void CanvasRenderingContext2D::strokeText(const String& text, float x, float y, float maxWidth)
2036 drawTextInternal(text, x, y, false, maxWidth, true);
2039 static inline bool isSpaceCharacter(UChar c)
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;
2050 static String normalizeSpaces(const String& text)
2052 unsigned textLength = text.length();
2053 Vector<UChar> charVector(textLength);
2055 for (unsigned i = 0; i < textLength; i++) {
2056 if (isSpaceCharacter(text[i]))
2057 charVector[i] = ' ';
2059 charVector[i] = text[i];
2062 return String(charVector);
2065 PassRefPtrWillBeRawPtr<TextMetrics> CanvasRenderingContext2D::measureText(const String& text)
2067 RefPtrWillBeRawPtr<TextMetrics> metrics = TextMetrics::create();
2069 // The style resolution required for rendering text is not available in frame-less documents.
2070 if (!canvas()->document().frame())
2071 return metrics.release();
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);
2081 metrics->setWidth(font.width(textRun));
2082 metrics->setActualBoundingBoxLeft(-textBounds.x());
2083 metrics->setActualBoundingBoxRight(textBounds.maxX());
2086 const FontMetrics& fontMetrics = font.fontMetrics();
2087 const float ascent = fontMetrics.floatAscent();
2088 const float descent = fontMetrics.floatDescent();
2089 const float baselineY = getFontBaseline(fontMetrics);
2091 metrics->setFontBoundingBoxAscent(ascent - baselineY);
2092 metrics->setFontBoundingBoxDescent(descent + baselineY);
2093 metrics->setActualBoundingBoxAscent(-textBounds.y() - baselineY);
2094 metrics->setActualBoundingBoxDescent(textBounds.maxY() + baselineY);
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);
2101 metrics->setHangingBaseline(-0.8f * ascent + baselineY);
2102 metrics->setAlphabeticBaseline(baselineY);
2103 metrics->setIdeographicBaseline(descent + baselineY);
2104 return metrics.release();
2107 void CanvasRenderingContext2D::drawTextInternal(const String& text, float x, float y, bool fill, float maxWidth, bool useMaxWidth)
2109 // The style resolution required for rendering text is not available in frame-less documents.
2110 if (!canvas()->document().frame())
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();
2118 GraphicsContext* c = drawingContext();
2121 if (!state().m_invertibleCTM)
2123 if (!std::isfinite(x) | !std::isfinite(y))
2125 if (useMaxWidth && (!std::isfinite(maxWidth) || maxWidth <= 0))
2128 // If gradient size is zero, then paint nothing.
2129 Gradient* gradient = c->strokeGradient();
2130 if (!fill && gradient && gradient->isZeroSize())
2133 gradient = c->fillGradient();
2134 if (fill && gradient && gradient->isZeroSize())
2137 FontCachePurgePreventer fontCachePurgePreventer;
2139 const Font& font = accessFont();
2140 const FontMetrics& fontMetrics = font.fontMetrics();
2141 String normalizedText = normalizeSpaces(text);
2143 // FIXME: Need to turn off font smoothing.
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;
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));
2154 float fontWidth = font.width(TextRun(normalizedText, 0, 0, TextRun::AllowTrailingExpansion, direction, override));
2156 useMaxWidth = (useMaxWidth && maxWidth < fontWidth);
2157 float width = useMaxWidth ? maxWidth : fontWidth;
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;
2166 case CenterTextAlign:
2167 location.setX(location.x() - width / 2);
2169 case RightTextAlign:
2170 location.setX(location.x() - width);
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());
2183 inflateStrokeRect(textRunPaintInfo.bounds);
2185 c->setTextDrawingMode(fill ? TextModeFill : TextModeStroke);
2187 GraphicsContextStateSaver stateSaver(*c);
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();
2195 FloatRect clipBounds;
2196 if (!c->getTransformedClipBounds(&clipBounds)) {
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);
2207 didDraw(clipBounds);
2208 } else if (state().m_globalComposite == CompositeCopy) {
2210 c->drawBidiText(font, textRunPaintInfo, location, Font::UseFallbackIfFontNotReady);
2211 didDraw(clipBounds);
2213 FloatRect dirtyRect;
2214 if (computeDirtyRect(textRunPaintInfo.bounds, clipBounds, &dirtyRect)) {
2215 c->drawBidiText(font, textRunPaintInfo, location, Font::UseFallbackIfFontNotReady);
2221 void CanvasRenderingContext2D::inflateStrokeRect(FloatRect& rect) const
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)
2233 rect.inflate(delta);
2236 const Font& CanvasRenderingContext2D::accessFont()
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;
2245 int CanvasRenderingContext2D::getFontBaseline(const FontMetrics& fontMetrics) const
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:
2267 blink::WebLayer* CanvasRenderingContext2D::platformLayer() const
2269 return canvas()->buffer() ? canvas()->buffer()->platformLayer() : 0;
2272 bool CanvasRenderingContext2D::imageSmoothingEnabled() const
2274 return state().m_imageSmoothingEnabled;
2277 void CanvasRenderingContext2D::setImageSmoothingEnabled(bool enabled)
2279 if (enabled == state().m_imageSmoothingEnabled)
2283 modifiableState().m_imageSmoothingEnabled = enabled;
2284 GraphicsContext* c = drawingContext();
2286 c->setImageInterpolationQuality(enabled ? CanvasDefaultInterpolationQuality : InterpolationNone);
2289 PassRefPtrWillBeRawPtr<Canvas2DContextAttributes> CanvasRenderingContext2D::getContextAttributes() const
2291 RefPtrWillBeRawPtr<Canvas2DContextAttributes> attributes = Canvas2DContextAttributes::create();
2292 attributes->setAlpha(m_hasAlpha);
2293 return attributes.release();
2296 void CanvasRenderingContext2D::drawFocusIfNeeded(Element* element)
2298 drawFocusIfNeededInternal(m_path, element);
2301 void CanvasRenderingContext2D::drawFocusIfNeeded(Path2D* path2d, Element* element)
2303 drawFocusIfNeededInternal(path2d->path(), element);
2306 void CanvasRenderingContext2D::drawFocusIfNeededInternal(const Path& path, Element* element)
2308 if (!focusRingCallIsValid(path, element))
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);
2318 bool CanvasRenderingContext2D::focusRingCallIsValid(const Path& path, Element* element)
2321 if (!state().m_invertibleCTM)
2325 if (!element->isDescendantOf(canvas()))
2331 void CanvasRenderingContext2D::drawFocusRing(const Path& path)
2333 GraphicsContext* c = drawingContext();
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;
2342 // We need to add focusRingWidth to dirtyRect.
2343 StrokeData strokeData;
2344 strokeData.setThickness(focusRingWidth);
2346 FloatRect dirtyRect;
2347 if (!computeDirtyRect(path.strokeBoundingRect(strokeData), &dirtyRect))
2351 c->setAlphaAsFloat(1.0);
2353 c->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
2354 c->drawFocusRing(path, focusRingWidth, focusRingOutline, focusRingColor);
2356 validateStateStack();
2360 void CanvasRenderingContext2D::addHitRegion(ExceptionState& exceptionState)
2362 addHitRegion(Dictionary(), exceptionState);
2365 void CanvasRenderingContext2D::addHitRegion(const Dictionary& options, ExceptionState& exceptionState)
2367 HitRegionOptions passOptions;
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.");
2376 RefPtrWillBeMember<Path2D> path2d;
2377 options.getWithUndefinedOrNullCheck("path", path2d);
2378 Path hitRegionPath = path2d ? path2d->path() : m_path;
2380 FloatRect clipBounds;
2381 GraphicsContext* context = drawingContext();
2383 if (hitRegionPath.isEmpty() || !context || !state().m_invertibleCTM
2384 || !context->getTransformedClipBounds(&clipBounds)) {
2385 exceptionState.throwDOMException(NotSupportedError, "The specified path has no pixels.");
2389 hitRegionPath.transform(state().m_transform);
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.");
2399 passOptions.path = hitRegionPath;
2401 String fillRuleString;
2402 options.getWithUndefinedOrNullCheck("fillRule", fillRuleString);
2403 if (fillRuleString.isEmpty() || fillRuleString != "evenodd")
2404 passOptions.fillRule = RULE_NONZERO;
2406 passOptions.fillRule = RULE_EVENODD;
2408 addHitRegionInternal(passOptions, exceptionState);
2411 void CanvasRenderingContext2D::addHitRegionInternal(const HitRegionOptions& options, ExceptionState& exceptionState)
2413 if (!m_hitRegionManager)
2414 m_hitRegionManager = HitRegionManager::create();
2416 // Remove previous region (with id or control)
2417 m_hitRegionManager->removeHitRegionById(options.id);
2418 m_hitRegionManager->removeHitRegionByControl(options.control.get());
2420 RefPtrWillBeRawPtr<HitRegion> hitRegion = HitRegion::create(options);
2421 hitRegion->updateAccessibility(canvas());
2422 m_hitRegionManager->addHitRegion(hitRegion.release());
2425 void CanvasRenderingContext2D::removeHitRegion(const String& id)
2427 if (m_hitRegionManager)
2428 m_hitRegionManager->removeHitRegionById(id);
2431 void CanvasRenderingContext2D::clearHitRegions()
2433 if (m_hitRegionManager)
2434 m_hitRegionManager->removeAllHitRegions();
2437 HitRegion* CanvasRenderingContext2D::hitRegionAtPoint(const LayoutPoint& point)
2439 if (m_hitRegionManager)
2440 return m_hitRegionManager->getHitRegionAtPoint(point);
2445 unsigned CanvasRenderingContext2D::hitRegionsCount() const
2447 if (m_hitRegionManager)
2448 return m_hitRegionManager->getHitRegionsCount();
2453 } // namespace blink