2 * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Alp Toker <alp@atoker.com>
4 * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include "core/html/HTMLCanvasElement.h"
31 #include "bindings/core/v8/ExceptionMessages.h"
32 #include "bindings/core/v8/ExceptionState.h"
33 #include "bindings/core/v8/ScriptController.h"
34 #include "bindings/core/v8/WrapCanvasContext.h"
35 #include "core/HTMLNames.h"
36 #include "core/dom/Document.h"
37 #include "core/dom/ExceptionCode.h"
38 #include "core/frame/LocalFrame.h"
39 #include "core/frame/Settings.h"
40 #include "core/html/ImageData.h"
41 #include "core/html/canvas/Canvas2DContextAttributes.h"
42 #include "core/html/canvas/CanvasRenderingContext2D.h"
43 #include "core/html/canvas/WebGL2RenderingContext.h"
44 #include "core/html/canvas/WebGLContextAttributes.h"
45 #include "core/html/canvas/WebGLContextEvent.h"
46 #include "core/html/canvas/WebGLRenderingContext.h"
47 #include "core/layout/Layer.h"
48 #include "core/layout/LayoutHTMLCanvas.h"
49 #include "platform/MIMETypeRegistry.h"
50 #include "platform/RuntimeEnabledFeatures.h"
51 #include "platform/graphics/BitmapImage.h"
52 #include "platform/graphics/Canvas2DImageBufferSurface.h"
53 #include "platform/graphics/GraphicsContextStateSaver.h"
54 #include "platform/graphics/ImageBuffer.h"
55 #include "platform/graphics/RecordingImageBufferSurface.h"
56 #include "platform/graphics/StaticBitmapImage.h"
57 #include "platform/graphics/UnacceleratedImageBufferSurface.h"
58 #include "platform/graphics/gpu/WebGLImageBufferSurface.h"
59 #include "platform/transforms/AffineTransform.h"
60 #include "public/platform/Platform.h"
66 using namespace HTMLNames
;
70 // These values come from the WhatWG spec.
71 const int DefaultWidth
= 300;
72 const int DefaultHeight
= 150;
74 // Firefox limits width/height to 32767 pixels, but slows down dramatically before it
75 // reaches that limit. We limit by area instead, giving us larger maximum dimensions,
76 // in exchange for a smaller maximum canvas size.
77 const int MaxCanvasArea
= 32768 * 8192; // Maximum canvas area in CSS pixels
79 //In Skia, we will also limit width/height to 32767.
80 const int MaxSkiaDim
= 32767; // Maximum width/height in CSS pixels.
82 bool canCreateImageBuffer(const IntSize
& size
)
86 if (size
.width() * size
.height() > MaxCanvasArea
)
88 if (size
.width() > MaxSkiaDim
|| size
.height() > MaxSkiaDim
)
93 PassRefPtr
<Image
> createTransparentImage(const IntSize
& size
)
95 ASSERT(canCreateImageBuffer(size
));
97 bitmap
.allocN32Pixels(size
.width(), size
.height());
98 bitmap
.eraseColor(SK_ColorTRANSPARENT
);
99 return BitmapImage::create(NativeImageSkia::create(bitmap
));
104 DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(CanvasObserver
);
106 inline HTMLCanvasElement::HTMLCanvasElement(Document
& document
)
107 : HTMLElement(canvasTag
, document
)
108 , DocumentVisibilityObserver(document
)
109 , m_size(DefaultWidth
, DefaultHeight
)
110 , m_ignoreReset(false)
111 , m_accelerationDisabled(false)
112 , m_externallyAllocatedMemory(0)
113 , m_originClean(true)
114 , m_didFailToCreateImageBuffer(false)
115 , m_imageBufferIsClear(false)
117 setHasCustomStyleCallbacks();
120 DEFINE_NODE_FACTORY(HTMLCanvasElement
)
122 HTMLCanvasElement::~HTMLCanvasElement()
124 v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(-m_externallyAllocatedMemory
);
126 for (CanvasObserver
* canvasObserver
: m_observers
)
127 canvasObserver
->canvasDestroyed(this);
128 // Ensure these go away before the ImageBuffer.
129 m_contextStateSaver
.clear();
134 void HTMLCanvasElement::parseAttribute(const QualifiedName
& name
, const AtomicString
& value
)
136 if (name
== widthAttr
|| name
== heightAttr
)
138 HTMLElement::parseAttribute(name
, value
);
141 LayoutObject
* HTMLCanvasElement::createRenderer(const LayoutStyle
& style
)
143 LocalFrame
* frame
= document().frame();
144 if (frame
&& frame
->script().canExecuteScripts(NotAboutToExecuteScript
))
145 return new LayoutHTMLCanvas(this);
146 return HTMLElement::createRenderer(style
);
149 void HTMLCanvasElement::didRecalcStyle(StyleRecalcChange
)
151 SkPaint::FilterLevel filterLevel
= computedStyle()->imageRendering() == ImageRenderingPixelated
? SkPaint::kNone_FilterLevel
: SkPaint::kLow_FilterLevel
;
153 toWebGLRenderingContext(m_context
.get())->setFilterLevel(filterLevel
);
154 setNeedsCompositingUpdate();
155 } else if (hasImageBuffer()) {
156 m_imageBuffer
->setFilterLevel(filterLevel
);
160 Node::InsertionNotificationRequest
HTMLCanvasElement::insertedInto(ContainerNode
* node
)
162 setIsInCanvasSubtree(true);
163 return HTMLElement::insertedInto(node
);
166 void HTMLCanvasElement::addObserver(CanvasObserver
* observer
)
168 m_observers
.add(observer
);
171 void HTMLCanvasElement::removeObserver(CanvasObserver
* observer
)
173 m_observers
.remove(observer
);
176 void HTMLCanvasElement::setHeight(int value
)
178 setIntegralAttribute(heightAttr
, value
);
181 void HTMLCanvasElement::setWidth(int value
)
183 setIntegralAttribute(widthAttr
, value
);
186 ScriptValue
HTMLCanvasElement::getContext(ScriptState
* scriptState
, const String
& type
, const CanvasContextCreationAttributes
& attributes
)
188 CanvasRenderingContext2DOrWebGLRenderingContext result
;
189 getContext(type
, attributes
, result
);
190 if (result
.isNull()) {
191 return ScriptValue::createNull(scriptState
);
194 if (result
.isCanvasRenderingContext2D()) {
195 return wrapCanvasContext(scriptState
, this, result
.getAsCanvasRenderingContext2D());
198 ASSERT(result
.isWebGLRenderingContext());
199 return wrapCanvasContext(scriptState
, this, result
.getAsWebGLRenderingContext());
202 void HTMLCanvasElement::getContext(const String
& type
, const CanvasContextCreationAttributes
& attributes
, CanvasRenderingContext2DOrWebGLRenderingContext
& result
)
204 // A Canvas can either be "2D" or "webgl" but never both. If you request a 2D canvas and the existing
205 // context is already 2D, just return that. If the existing context is WebGL, then destroy it
206 // before creating a new 2D context. Vice versa when requesting a WebGL canvas. Requesting a
207 // context with any other type string will destroy any existing context.
209 // Do not change assigned numbers of existing items: add new features to the end of the list.
211 ContextExperimentalWebgl
= 2,
217 // FIXME - The code depends on the context not going away once created, to prevent JS from
218 // seeing a dangling pointer. So for now we will disallow the context from being changed
219 // once it is created.
221 if (m_context
&& !m_context
->is2d())
224 blink::Platform::current()->histogramEnumeration("Canvas.ContextType", Context2d
, ContextTypeCount
);
226 m_context
= CanvasRenderingContext2D::create(this, attributes
, document());
227 setNeedsCompositingUpdate();
229 result
.setCanvasRenderingContext2D(static_cast<CanvasRenderingContext2D
*>(m_context
.get()));
233 // Accept the the provisional "experimental-webgl" or official "webgl" context ID.
234 ContextType contextType
= Context2d
;
235 bool is3dContext
= true;
236 if (type
== "experimental-webgl")
237 contextType
= ContextExperimentalWebgl
;
238 else if (type
== "webgl")
239 contextType
= ContextWebgl
;
240 else if (type
== "webgl2")
241 contextType
= ContextWebgl2
;
247 blink::Platform::current()->histogramEnumeration("Canvas.ContextType", contextType
, ContextTypeCount
);
248 if (contextType
== ContextWebgl2
) {
249 m_context
= WebGL2RenderingContext::create(this, attributes
);
251 m_context
= WebGLRenderingContext::create(this, attributes
);
253 LayoutStyle
* style
= computedStyle();
254 if (style
&& m_context
)
255 toWebGLRenderingContext(m_context
.get())->setFilterLevel(style
->imageRendering() == ImageRenderingPixelated
? SkPaint::kNone_FilterLevel
: SkPaint::kLow_FilterLevel
);
256 setNeedsCompositingUpdate();
257 updateExternallyAllocatedMemory();
258 } else if (!m_context
->is3d()) {
259 dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror
, false, true, "Canvas has an existing, non-WebGL context"));
262 result
.setWebGLRenderingContext(static_cast<WebGLRenderingContext
*>(m_context
.get()));
268 bool HTMLCanvasElement::isPaintable() const
271 return canCreateImageBuffer(size());
275 void HTMLCanvasElement::didDraw(const FloatRect
& rect
)
279 m_imageBufferIsClear
= false;
282 renderer()->setMayNeedPaintInvalidation();
283 m_dirtyRect
.unite(rect
);
284 if (m_context
&& m_context
->is2d() && hasImageBuffer())
288 void HTMLCanvasElement::didFinalizeFrame()
290 if (m_dirtyRect
.isEmpty())
293 // Propagate the m_dirtyRect accumulated so far to the compositor
294 // before restarting with a blank dirty rect.
295 FloatRect
srcRect(0, 0, size().width(), size().height());
296 m_dirtyRect
.intersect(srcRect
);
297 if (LayoutBox
* ro
= layoutBox()) {
298 FloatRect mappedDirtyRect
= mapRect(m_dirtyRect
, srcRect
, ro
->contentBoxRect());
299 // For querying Layer::compositingState()
300 // FIXME: is this invalidation using the correct compositing state?
301 DisableCompositingQueryAsserts disabler
;
302 ro
->invalidatePaintRectangle(enclosingIntRect(mappedDirtyRect
));
304 notifyObserversCanvasChanged(m_dirtyRect
);
305 m_dirtyRect
= FloatRect();
308 void HTMLCanvasElement::restoreCanvasMatrixClipStack()
310 if (m_context
&& m_context
->is2d())
311 toCanvasRenderingContext2D(m_context
.get())->restoreCanvasMatrixClipStack();
314 void HTMLCanvasElement::doDeferredPaintInvalidation()
316 ASSERT(!m_dirtyRect
.isEmpty());
320 ASSERT(hasImageBuffer());
321 m_imageBuffer
->finalizeFrame(m_dirtyRect
);
323 ASSERT(m_dirtyRect
.isEmpty());
327 void HTMLCanvasElement::notifyObserversCanvasChanged(const FloatRect
& rect
)
329 for (CanvasObserver
* canvasObserver
: m_observers
)
330 canvasObserver
->canvasChanged(this, rect
);
333 void HTMLCanvasElement::reset()
338 m_dirtyRect
= FloatRect();
341 bool hadImageBuffer
= hasImageBuffer();
343 int w
= getAttribute(widthAttr
).toInt(&ok
);
347 int h
= getAttribute(heightAttr
).toInt(&ok
);
351 if (m_contextStateSaver
) {
352 // Reset to the initial graphics context state.
353 m_contextStateSaver
->restore();
354 m_contextStateSaver
->save();
357 if (m_context
&& m_context
->is2d())
358 toCanvasRenderingContext2D(m_context
.get())->reset();
360 IntSize oldSize
= size();
361 IntSize
newSize(w
, h
);
363 // If the size of an existing buffer matches, we can just clear it instead of reallocating.
364 // This optimization is only done for 2D canvases for now.
365 if (hadImageBuffer
&& oldSize
== newSize
&& m_context
&& m_context
->is2d() && !buffer()->isRecording()) {
366 if (!m_imageBufferIsClear
) {
367 m_imageBufferIsClear
= true;
368 toCanvasRenderingContext2D(m_context
.get())->clearRect(0, 0, width(), height());
373 setSurfaceSize(newSize
);
375 if (m_context
&& m_context
->is3d() && oldSize
!= size())
376 toWebGLRenderingContext(m_context
.get())->reshape(width(), height());
378 if (LayoutObject
* renderer
= this->renderer()) {
379 if (renderer
->isCanvas()) {
380 if (oldSize
!= size()) {
381 toLayoutHTMLCanvas(renderer
)->canvasSizeChanged();
382 if (layoutBox() && layoutBox()->hasAcceleratedCompositing())
383 layoutBox()->contentChanged(CanvasChanged
);
386 renderer
->setShouldDoFullPaintInvalidation();
390 for (CanvasObserver
* canvasObserver
: m_observers
)
391 canvasObserver
->canvasResized(this);
394 bool HTMLCanvasElement::paintsIntoCanvasBuffer() const
398 if (!m_context
->isAccelerated())
401 if (layoutBox() && layoutBox()->hasAcceleratedCompositing())
408 void HTMLCanvasElement::paint(GraphicsContext
* context
, const LayoutRect
& r
)
410 // FIXME: crbug.com/438240; there is a bug with the new CSS blending and compositing feature.
413 if (!paintsIntoCanvasBuffer() && !document().printing())
416 m_context
->paintRenderingResultsToCanvas(FrontBuffer
);
417 if (hasImageBuffer()) {
418 SkXfermode::Mode compositeOperator
= !m_context
|| m_context
->hasAlpha() ? SkXfermode::kSrcOver_Mode
: SkXfermode::kSrc_Mode
;
419 context
->drawImageBuffer(buffer(), pixelSnappedIntRect(r
), 0, compositeOperator
);
421 // When alpha is false, we should draw to opaque black.
422 if (!m_context
->hasAlpha())
423 context
->fillRect(FloatRect(r
), Color(0, 0, 0));
426 if (is3D() && paintsIntoCanvasBuffer())
427 toWebGLRenderingContext(m_context
.get())->markLayerComposited();
430 bool HTMLCanvasElement::is3D() const
432 return m_context
&& m_context
->is3d();
435 void HTMLCanvasElement::setSurfaceSize(const IntSize
& size
)
438 m_didFailToCreateImageBuffer
= false;
439 discardImageBuffer();
441 if (m_context
&& m_context
->is2d()) {
442 CanvasRenderingContext2D
* context2d
= toCanvasRenderingContext2D(m_context
.get());
443 if (context2d
->isContextLost()) {
444 context2d
->restoreContext();
449 String
HTMLCanvasElement::toEncodingMimeType(const String
& mimeType
)
451 String lowercaseMimeType
= mimeType
.lower();
453 // FIXME: Make isSupportedImageMIMETypeForEncoding threadsafe (to allow this method to be used on a worker thread).
454 if (mimeType
.isNull() || !MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(lowercaseMimeType
))
455 lowercaseMimeType
= "image/png";
457 return lowercaseMimeType
;
460 const AtomicString
HTMLCanvasElement::imageSourceURL() const
462 return AtomicString(toDataURLInternal("image/png", 0, FrontBuffer
));
465 String
HTMLCanvasElement::toDataURLInternal(const String
& mimeType
, const double* quality
, SourceDrawingBuffer sourceBuffer
) const
468 return String("data:,");
470 String encodingMimeType
= toEncodingMimeType(mimeType
);
472 RefPtrWillBeRawPtr
<ImageData
> imageData
= ImageData::create(m_size
);
473 return ImageDataBuffer(imageData
->size(), imageData
->data()->data()).toDataURL(encodingMimeType
, quality
);
476 if (m_context
->is3d()) {
477 // Get non-premultiplied data because of inaccurate premultiplied alpha conversion of buffer()->toDataURL().
478 RefPtrWillBeRawPtr
<ImageData
> imageData
=
479 toWebGLRenderingContext(m_context
.get())->paintRenderingResultsToImageData(sourceBuffer
);
481 return ImageDataBuffer(imageData
->size(), imageData
->data()->data()).toDataURL(encodingMimeType
, quality
);
482 m_context
->paintRenderingResultsToCanvas(sourceBuffer
);
485 return buffer()->toDataURL(encodingMimeType
, quality
);
488 String
HTMLCanvasElement::toDataURL(const String
& mimeType
, const ScriptValue
& qualityArgument
, ExceptionState
& exceptionState
) const
490 if (!originClean()) {
491 exceptionState
.throwSecurityError("Tainted canvases may not be exported.");
495 double* qualityPtr
= nullptr;
496 if (!qualityArgument
.isEmpty()) {
497 v8::Local
<v8::Value
> v8Value
= qualityArgument
.v8Value();
498 if (v8Value
->IsNumber()) {
499 quality
= v8Value
->NumberValue();
500 qualityPtr
= &quality
;
503 return toDataURLInternal(mimeType
, qualityPtr
, BackBuffer
);
506 SecurityOrigin
* HTMLCanvasElement::securityOrigin() const
508 return document().securityOrigin();
511 bool HTMLCanvasElement::originClean() const
513 if (document().settings() && document().settings()->disableReadingFromCanvas())
515 return m_originClean
;
518 bool HTMLCanvasElement::shouldAccelerate(const IntSize
& size
) const
520 if (m_context
&& !m_context
->is2d())
523 if (m_accelerationDisabled
)
526 Settings
* settings
= document().settings();
527 if (!settings
|| !settings
->accelerated2dCanvasEnabled())
530 // Do not use acceleration for small canvas.
531 if (size
.width() * size
.height() < settings
->minimumAccelerated2dCanvasSize())
534 if (!blink::Platform::current()->canAccelerate2dCanvas())
540 class UnacceleratedSurfaceFactory
: public RecordingImageBufferFallbackSurfaceFactory
{
542 virtual PassOwnPtr
<ImageBufferSurface
> createSurface(const IntSize
& size
, OpacityMode opacityMode
)
544 return adoptPtr(new UnacceleratedImageBufferSurface(size
, opacityMode
));
547 virtual ~UnacceleratedSurfaceFactory() { }
550 class Accelerated2dSurfaceFactory
: public RecordingImageBufferFallbackSurfaceFactory
{
552 Accelerated2dSurfaceFactory(int msaaSampleCount
) : m_msaaSampleCount(msaaSampleCount
) { }
554 virtual PassOwnPtr
<ImageBufferSurface
> createSurface(const IntSize
& size
, OpacityMode opacityMode
)
556 OwnPtr
<ImageBufferSurface
> surface
= adoptPtr(new Canvas2DImageBufferSurface(size
, opacityMode
, m_msaaSampleCount
));
557 if (surface
->isValid())
558 return surface
.release();
559 return adoptPtr(new UnacceleratedImageBufferSurface(size
, opacityMode
));
562 virtual ~Accelerated2dSurfaceFactory() { }
564 int m_msaaSampleCount
;
567 PassOwnPtr
<RecordingImageBufferFallbackSurfaceFactory
> HTMLCanvasElement::createSurfaceFactory(const IntSize
& deviceSize
, int* msaaSampleCount
) const
569 *msaaSampleCount
= 0;
570 OwnPtr
<RecordingImageBufferFallbackSurfaceFactory
> surfaceFactory
;
571 if (shouldAccelerate(deviceSize
)) {
572 if (document().settings())
573 *msaaSampleCount
= document().settings()->accelerated2dCanvasMSAASampleCount();
574 surfaceFactory
= adoptPtr(new Accelerated2dSurfaceFactory(*msaaSampleCount
));
576 surfaceFactory
= adoptPtr(new UnacceleratedSurfaceFactory());
578 return surfaceFactory
.release();
581 bool HTMLCanvasElement::shouldUseDisplayList(const IntSize
& deviceSize
)
583 if (RuntimeEnabledFeatures::forceDisplayList2dCanvasEnabled())
586 if (!RuntimeEnabledFeatures::displayList2dCanvasEnabled())
589 if (shouldAccelerate(deviceSize
))
595 PassOwnPtr
<ImageBufferSurface
> HTMLCanvasElement::createImageBufferSurface(const IntSize
& deviceSize
, int* msaaSampleCount
)
597 OpacityMode opacityMode
= !m_context
|| m_context
->hasAlpha() ? NonOpaque
: Opaque
;
599 *msaaSampleCount
= 0;
601 // If 3d, but the use of the canvas will be for non-accelerated content
602 // (such as -webkit-canvas, then then make a non-accelerated
603 // ImageBuffer. This means copying the internal Image will require a
604 // pixel readback, but that is unavoidable in this case.
605 // FIXME: Actually, avoid setting m_accelerationDisabled at all when
606 // doing GPU-based rasterization.
607 if (m_accelerationDisabled
)
608 return adoptPtr(new UnacceleratedImageBufferSurface(deviceSize
, opacityMode
));
609 return adoptPtr(new WebGLImageBufferSurface(deviceSize
, opacityMode
));
612 OwnPtr
<RecordingImageBufferFallbackSurfaceFactory
> surfaceFactory
= createSurfaceFactory(deviceSize
, msaaSampleCount
);
614 if (shouldUseDisplayList(deviceSize
)) {
615 OwnPtr
<ImageBufferSurface
> surface
= adoptPtr(new RecordingImageBufferSurface(deviceSize
, surfaceFactory
.release(), opacityMode
));
616 if (surface
->isValid())
617 return surface
.release();
618 surfaceFactory
= createSurfaceFactory(deviceSize
, msaaSampleCount
); // recreate because previous one was released
621 return surfaceFactory
->createSurface(deviceSize
, opacityMode
);
624 void HTMLCanvasElement::createImageBuffer()
626 createImageBufferInternal(nullptr);
627 if (m_didFailToCreateImageBuffer
&& m_context
->is2d())
628 toCanvasRenderingContext2D(m_context
.get())->loseContext();
631 void HTMLCanvasElement::createImageBufferInternal(PassOwnPtr
<ImageBufferSurface
> externalSurface
)
633 ASSERT(!m_imageBuffer
);
634 ASSERT(!m_contextStateSaver
);
636 m_didFailToCreateImageBuffer
= true;
637 m_imageBufferIsClear
= true;
639 if (!canCreateImageBuffer(size()))
642 int msaaSampleCount
= 0;
643 OwnPtr
<ImageBufferSurface
> surface
;
644 if (externalSurface
) {
645 surface
= externalSurface
;
647 surface
= createImageBufferSurface(size(), &msaaSampleCount
);
649 m_imageBuffer
= ImageBuffer::create(surface
.release());
652 m_imageBuffer
->setClient(this);
654 document().updateRenderTreeIfNeeded();
655 LayoutStyle
* style
= computedStyle();
656 m_imageBuffer
->setFilterLevel((style
&& (style
->imageRendering() == ImageRenderingPixelated
)) ? SkPaint::kNone_FilterLevel
: SkPaint::kLow_FilterLevel
);
658 m_didFailToCreateImageBuffer
= false;
660 updateExternallyAllocatedMemory();
663 // Early out for WebGL canvases
667 m_imageBuffer
->setClient(this);
668 m_imageBuffer
->context()->setShouldClampToSourceRect(false);
669 m_imageBuffer
->context()->disableAntialiasingOptimizationForHairlineImages();
670 m_imageBuffer
->context()->setImageInterpolationQuality(CanvasDefaultInterpolationQuality
);
671 // Enabling MSAA overrides a request to disable antialiasing. This is true regardless of whether the
672 // rendering mode is accelerated or not. For consistency, we don't want to apply AA in accelerated
673 // canvases but not in unaccelerated canvases.
674 if (!msaaSampleCount
&& document().settings() && !document().settings()->antialiased2dCanvasEnabled())
675 m_imageBuffer
->context()->setShouldAntialias(false);
676 // GraphicsContext's defaults don't always agree with the 2d canvas spec.
677 // See CanvasRenderingContext2D::State::State() for more information.
678 m_imageBuffer
->context()->setMiterLimit(10);
679 m_imageBuffer
->context()->setStrokeThickness(1);
681 m_imageBuffer
->context()->disableDestructionChecks(); // 2D canvas is allowed to leave context in an unfinalized state.
683 m_contextStateSaver
= adoptPtr(new GraphicsContextStateSaver(*m_imageBuffer
->context()));
686 setNeedsCompositingUpdate();
689 void HTMLCanvasElement::notifySurfaceInvalid()
691 if (m_context
&& m_context
->is2d()) {
692 CanvasRenderingContext2D
* context2d
= toCanvasRenderingContext2D(m_context
.get());
693 context2d
->loseContext();
697 DEFINE_TRACE(HTMLCanvasElement
)
700 visitor
->trace(m_observers
);
701 visitor
->trace(m_context
);
703 DocumentVisibilityObserver::trace(visitor
);
704 HTMLElement::trace(visitor
);
707 void HTMLCanvasElement::updateExternallyAllocatedMemory() const
712 if (m_imageBuffer
->isAccelerated()) {
713 // The number of internal GPU buffers vary between one (stable
714 // non-displayed state) and three (triple-buffered animations).
715 // Adding 2 is a pessimistic but relevant estimate.
716 // Note: These buffers might be allocated in GPU memory.
723 // Four bytes per pixel per buffer.
724 Checked
<intptr_t, RecordOverflow
> checkedExternallyAllocatedMemory
= 4 * bufferCount
;
726 checkedExternallyAllocatedMemory
+= toWebGLRenderingContext(m_context
.get())->externallyAllocatedBytesPerPixel();
728 checkedExternallyAllocatedMemory
*= width();
729 checkedExternallyAllocatedMemory
*= height();
730 intptr_t externallyAllocatedMemory
;
731 if (checkedExternallyAllocatedMemory
.safeGet(externallyAllocatedMemory
) == CheckedState::DidOverflow
)
732 externallyAllocatedMemory
= std::numeric_limits
<intptr_t>::max();
734 // Subtracting two intptr_t that are known to be positive will never underflow.
735 v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(externallyAllocatedMemory
- m_externallyAllocatedMemory
);
736 m_externallyAllocatedMemory
= externallyAllocatedMemory
;
739 GraphicsContext
* HTMLCanvasElement::drawingContext() const
741 return buffer() ? m_imageBuffer
->context() : nullptr;
744 SkCanvas
* HTMLCanvasElement::drawingCanvas() const
746 return buffer() ? m_imageBuffer
->canvas() : nullptr;
749 SkCanvas
* HTMLCanvasElement::existingDrawingCanvas() const
751 if (!hasImageBuffer())
754 return m_imageBuffer
->canvas();
757 ImageBuffer
* HTMLCanvasElement::buffer() const
760 if (!hasImageBuffer() && !m_didFailToCreateImageBuffer
)
761 const_cast<HTMLCanvasElement
*>(this)->createImageBuffer();
762 return m_imageBuffer
.get();
765 void HTMLCanvasElement::createImageBufferUsingSurface(PassOwnPtr
<ImageBufferSurface
> surface
)
767 discardImageBuffer();
768 createImageBufferInternal(surface
);
771 void HTMLCanvasElement::ensureUnacceleratedImageBuffer()
774 if ((hasImageBuffer() && !m_imageBuffer
->isAccelerated()) || m_didFailToCreateImageBuffer
)
776 discardImageBuffer();
777 OpacityMode opacityMode
= m_context
->hasAlpha() ? NonOpaque
: Opaque
;
778 m_imageBuffer
= ImageBuffer::create(size(), opacityMode
);
779 m_didFailToCreateImageBuffer
= !m_imageBuffer
;
782 PassRefPtr
<Image
> HTMLCanvasElement::copiedImage(SourceDrawingBuffer sourceBuffer
) const
787 return createTransparentImage(size());
789 bool needToUpdate
= !m_copiedImage
;
790 // The concept of SourceDrawingBuffer is valid on only WebGL.
791 if (m_context
->is3d())
792 needToUpdate
|= m_context
->paintRenderingResultsToCanvas(sourceBuffer
);
793 if (needToUpdate
&& buffer()) {
794 m_copiedImage
= buffer()->copyImage(CopyBackingStore
, Unscaled
);
795 updateExternallyAllocatedMemory();
797 return m_copiedImage
;
800 void HTMLCanvasElement::discardImageBuffer()
802 m_contextStateSaver
.clear(); // uses context owned by m_imageBuffer
803 m_imageBuffer
.clear();
804 m_dirtyRect
= FloatRect();
805 updateExternallyAllocatedMemory();
808 void HTMLCanvasElement::clearCopiedImage()
811 m_copiedImage
.clear();
812 updateExternallyAllocatedMemory();
816 AffineTransform
HTMLCanvasElement::baseTransform() const
818 ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer
);
819 return m_imageBuffer
->baseTransform();
822 void HTMLCanvasElement::didChangeVisibilityState(PageVisibilityState visibility
)
826 bool hidden
= visibility
!= PageVisibilityStateVisible
;
827 m_context
->setIsHidden(hidden
);
831 discardImageBuffer();
836 void HTMLCanvasElement::didMoveToNewDocument(Document
& oldDocument
)
838 setObservedDocument(document());
839 HTMLElement::didMoveToNewDocument(oldDocument
);
842 PassRefPtr
<Image
> HTMLCanvasElement::getSourceImageForCanvas(SourceImageMode mode
, SourceImageStatus
* status
) const
844 if (!width() || !height()) {
845 *status
= ZeroSizeCanvasSourceImageStatus
;
849 if (!isPaintable()) {
850 *status
= InvalidSourceImageStatus
;
855 *status
= NormalSourceImageStatus
;
856 return createTransparentImage(size());
859 m_imageBuffer
->willAccessPixels();
861 if (m_context
->is3d()) {
862 m_context
->paintRenderingResultsToCanvas(BackBuffer
);
863 *status
= ExternalSourceImageStatus
;
865 // can't create SkImage from WebGLImageBufferSurface (contains only SkBitmap)
866 return buffer()->copyImage(DontCopyBackingStore
, Unscaled
);
869 RefPtr
<SkImage
> image
= buffer()->newImageSnapshot();
871 *status
= NormalSourceImageStatus
;
872 return StaticBitmapImage::create(image
.release());
875 *status
= InvalidSourceImageStatus
;
879 bool HTMLCanvasElement::wouldTaintOrigin(SecurityOrigin
*) const
881 return !originClean();
884 FloatSize
HTMLCanvasElement::sourceSize() const
886 return FloatSize(width(), height());
889 bool HTMLCanvasElement::isOpaque() const
891 return m_context
&& !m_context
->hasAlpha();