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 "HTMLCanvasElement.h"
31 #include "Attribute.h"
32 #include "CanvasContextAttributes.h"
33 #include "CanvasGradient.h"
34 #include "CanvasPattern.h"
35 #include "CanvasRenderingContext2D.h"
36 #include "CanvasStyle.h"
39 #include "ExceptionCode.h"
41 #include "GraphicsContext.h"
42 #include "HTMLNames.h"
43 #include "ImageBuffer.h"
44 #include "MIMETypeRegistry.h"
46 #include "RenderHTMLCanvas.h"
52 #include <runtime/JSLock.h>
56 #include "WebGLContextAttributes.h"
57 #include "WebGLRenderingContext.h"
62 using namespace HTMLNames;
64 // These values come from the WhatWG spec.
65 static const int DefaultWidth = 300;
66 static const int DefaultHeight = 150;
68 // Firefox limits width/height to 32767 pixels, but slows down dramatically before it
69 // reaches that limit. We limit by area instead, giving us larger maximum dimensions,
70 // in exchange for a smaller maximum canvas size.
71 static const float MaxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels
73 //In Skia, we will also limit width/height to 32767.
74 static const float MaxSkiaDim = 32767.0F; // Maximum width/height in CSS pixels.
76 HTMLCanvasElement::HTMLCanvasElement(const QualifiedName& tagName, Document* document)
77 : HTMLElement(tagName, document)
78 , m_size(DefaultWidth, DefaultHeight)
79 , m_ignoreReset(false)
80 , m_pageScaleFactor(document->frame() ? document->frame()->page()->chrome()->scaleFactor() : 1)
82 , m_hasCreatedImageBuffer(false)
84 ASSERT(hasTagName(canvasTag));
87 PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(Document* document)
89 return adoptRef(new HTMLCanvasElement(canvasTag, document));
92 PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(const QualifiedName& tagName, Document* document)
94 return adoptRef(new HTMLCanvasElement(tagName, document));
97 HTMLCanvasElement::~HTMLCanvasElement()
99 HashSet<CanvasObserver*>::iterator end = m_observers.end();
100 for (HashSet<CanvasObserver*>::iterator it = m_observers.begin(); it != end; ++it)
101 (*it)->canvasDestroyed(this);
104 void HTMLCanvasElement::parseMappedAttribute(Attribute* attr)
106 const QualifiedName& attrName = attr->name();
107 if (attrName == widthAttr || attrName == heightAttr)
109 HTMLElement::parseMappedAttribute(attr);
112 RenderObject* HTMLCanvasElement::createRenderer(RenderArena* arena, RenderStyle* style)
114 Frame* frame = document()->frame();
115 if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
116 m_rendererIsCanvas = true;
117 return new (arena) RenderHTMLCanvas(this);
120 m_rendererIsCanvas = false;
121 return HTMLElement::createRenderer(arena, style);
124 void HTMLCanvasElement::addObserver(CanvasObserver* observer)
126 m_observers.add(observer);
129 void HTMLCanvasElement::removeObserver(CanvasObserver* observer)
131 m_observers.remove(observer);
134 void HTMLCanvasElement::setHeight(int value)
136 setAttribute(heightAttr, String::number(value));
139 void HTMLCanvasElement::setWidth(int value)
141 setAttribute(widthAttr, String::number(value));
144 CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, CanvasContextAttributes* attrs)
146 // A Canvas can either be "2D" or "webgl" but never both. If you request a 2D canvas and the existing
147 // context is already 2D, just return that. If the existing context is WebGL, then destroy it
148 // before creating a new 2D context. Vice versa when requesting a WebGL canvas. Requesting a
149 // context with any other type string will destroy any existing context.
151 // FIXME - The code depends on the context not going away once created, to prevent JS from
152 // seeing a dangling pointer. So for now we will disallow the context from being changed
153 // once it is created.
155 if (m_context && !m_context->is2d())
158 bool usesDashbardCompatibilityMode = false;
159 #if ENABLE(DASHBOARD_SUPPORT)
160 if (Settings* settings = document()->settings())
161 usesDashbardCompatibilityMode = settings->usesDashboardBackwardCompatibilityMode();
163 m_context = adoptPtr(new CanvasRenderingContext2D(this, document()->inQuirksMode(), usesDashbardCompatibilityMode));
164 #if USE(IOSURFACE_CANVAS_BACKING_STORE) || (ENABLE(ACCELERATED_2D_CANVAS) && USE(ACCELERATED_COMPOSITING))
166 // Need to make sure a RenderLayer and compositing layer get created for the Canvas
167 setNeedsStyleRecalc(SyntheticStyleChange);
171 return m_context.get();
174 Settings* settings = document()->settings();
175 if (settings && settings->webGLEnabled()
176 #if !PLATFORM(CHROMIUM) && !PLATFORM(QT)
177 && settings->acceleratedCompositingEnabled()
180 // Accept the legacy "webkit-3d" name as well as the provisional "experimental-webgl" name.
181 // Once ratified, we will also accept "webgl" as the context name.
182 if ((type == "webkit-3d") ||
183 (type == "experimental-webgl")) {
184 if (m_context && !m_context->is3d())
187 m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
189 // Need to make sure a RenderLayer and compositing layer get created for the Canvas
190 setNeedsStyleRecalc(SyntheticStyleChange);
193 return m_context.get();
202 void HTMLCanvasElement::didDraw(const FloatRect& rect)
204 m_copiedImage.clear(); // Clear our image snapshot if we have one.
206 if (RenderBox* ro = renderBox()) {
207 FloatRect destRect = ro->contentBoxRect();
208 FloatRect r = mapRect(rect, FloatRect(0, 0, size().width(), size().height()), destRect);
209 r.intersect(destRect);
210 if (r.isEmpty() || m_dirtyRect.contains(r))
213 m_dirtyRect.unite(r);
214 ro->repaintRectangle(enclosingIntRect(m_dirtyRect));
217 HashSet<CanvasObserver*>::iterator end = m_observers.end();
218 for (HashSet<CanvasObserver*>::iterator it = m_observers.begin(); it != end; ++it)
219 (*it)->canvasChanged(this, rect);
222 void HTMLCanvasElement::reset()
228 bool hadImageBuffer = hasCreatedImageBuffer();
229 int w = getAttribute(widthAttr).toInt(&ok);
232 int h = getAttribute(heightAttr).toInt(&ok);
236 IntSize oldSize = size();
237 setSurfaceSize(IntSize(w, h)); // The image buffer gets cleared here.
240 if (m_context && m_context->is3d() && oldSize != size())
241 static_cast<WebGLRenderingContext*>(m_context.get())->reshape(width(), height());
244 if (m_context && m_context->is2d())
245 static_cast<CanvasRenderingContext2D*>(m_context.get())->reset();
247 if (RenderObject* renderer = this->renderer()) {
248 if (m_rendererIsCanvas) {
249 if (oldSize != size())
250 toRenderHTMLCanvas(renderer)->canvasSizeChanged();
256 HashSet<CanvasObserver*>::iterator end = m_observers.end();
257 for (HashSet<CanvasObserver*>::iterator it = m_observers.begin(); it != end; ++it)
258 (*it)->canvasResized(this);
261 void HTMLCanvasElement::paint(GraphicsContext* context, const IntRect& r)
263 // Clear the dirty rect
264 m_dirtyRect = FloatRect();
266 if (context->paintingDisabled())
270 if (!m_context->paintsIntoCanvasBuffer())
272 m_context->paintRenderingResultsToCanvas();
275 if (hasCreatedImageBuffer()) {
276 ImageBuffer* imageBuffer = buffer();
278 if (imageBuffer->drawsUsingCopy())
279 context->drawImage(copiedImage(), ColorSpaceDeviceRGB, r);
281 context->drawImageBuffer(imageBuffer, ColorSpaceDeviceRGB, r);
287 bool HTMLCanvasElement::is3D() const
289 return m_context && m_context->is3d();
293 void HTMLCanvasElement::makeRenderingResultsAvailable()
296 m_context->paintRenderingResultsToCanvas();
299 void HTMLCanvasElement::attach()
301 HTMLElement::attach();
303 if (m_context && m_context->is2d()) {
304 CanvasRenderingContext2D* ctx = static_cast<CanvasRenderingContext2D*>(m_context.get());
309 void HTMLCanvasElement::recalcStyle(StyleChange change)
311 HTMLElement::recalcStyle(change);
313 // Update font if needed.
314 if (change == Force && m_context && m_context->is2d()) {
315 CanvasRenderingContext2D* ctx = static_cast<CanvasRenderingContext2D*>(m_context.get());
320 void HTMLCanvasElement::setSurfaceSize(const IntSize& size)
323 m_hasCreatedImageBuffer = false;
324 m_imageBuffer.clear();
325 m_copiedImage.clear();
328 String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionCode& ec)
330 if (!m_originClean) {
335 if (m_size.isEmpty() || !buffer())
336 return String("data:,");
338 String lowercaseMimeType = mimeType.lower();
340 makeRenderingResultsAvailable();
342 // FIXME: Make isSupportedImageMIMETypeForEncoding threadsafe (to allow this method to be used on a worker thread).
343 if (mimeType.isNull() || !MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(lowercaseMimeType))
344 return buffer()->toDataURL("image/png");
346 return buffer()->toDataURL(lowercaseMimeType, quality);
349 IntRect HTMLCanvasElement::convertLogicalToDevice(const FloatRect& logicalRect) const
351 float left = floorf(logicalRect.x() * m_pageScaleFactor);
352 float top = floorf(logicalRect.y() * m_pageScaleFactor);
353 float right = ceilf(logicalRect.maxX() * m_pageScaleFactor);
354 float bottom = ceilf(logicalRect.maxY() * m_pageScaleFactor);
356 return IntRect(IntPoint(left, top), convertToValidDeviceSize(right - left, bottom - top));
359 IntSize HTMLCanvasElement::convertLogicalToDevice(const FloatSize& logicalSize) const
361 return convertToValidDeviceSize(logicalSize.width() * m_pageScaleFactor, logicalSize.height() * m_pageScaleFactor);
364 IntSize HTMLCanvasElement::convertToValidDeviceSize(float width, float height) const
366 width = ceilf(width);
367 height = ceilf(height);
369 if (width < 1 || height < 1 || width * height > MaxCanvasArea)
373 if (width > MaxSkiaDim || height > MaxSkiaDim)
377 return IntSize(width, height);
380 const SecurityOrigin& HTMLCanvasElement::securityOrigin() const
382 return *document()->securityOrigin();
385 CSSStyleSelector* HTMLCanvasElement::styleSelector()
387 return document()->styleSelector();
390 void HTMLCanvasElement::createImageBuffer() const
392 ASSERT(!m_imageBuffer);
394 m_hasCreatedImageBuffer = true;
396 FloatSize unscaledSize(width(), height());
397 IntSize size = convertLogicalToDevice(unscaledSize);
398 if (!size.width() || !size.height())
401 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
402 m_imageBuffer = ImageBuffer::create(size, ColorSpaceDeviceRGB, Accelerated);
404 m_imageBuffer = ImageBuffer::create(size);
406 // The convertLogicalToDevice MaxCanvasArea check should prevent common cases
407 // where ImageBuffer::create() returns 0, however we could still be low on memory.
410 m_imageBuffer->context()->scale(FloatSize(size.width() / unscaledSize.width(), size.height() / unscaledSize.height()));
411 m_imageBuffer->context()->setShadowsIgnoreTransforms(true);
412 m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
415 if (hasCachedDOMNodeWrapperUnchecked(document(), const_cast<HTMLCanvasElement*>(this))) {
416 JSC::JSLock lock(JSC::SilenceAssertionsOnly);
417 scriptExecutionContext()->globalData()->heap.reportExtraMemoryCost(m_imageBuffer->dataSize());
422 GraphicsContext* HTMLCanvasElement::drawingContext() const
424 return buffer() ? m_imageBuffer->context() : 0;
427 ImageBuffer* HTMLCanvasElement::buffer() const
429 if (!m_hasCreatedImageBuffer)
431 return m_imageBuffer.get();
434 Image* HTMLCanvasElement::copiedImage() const
436 if (!m_copiedImage && buffer()) {
438 // If we're not rendering to the ImageBuffer, copy the rendering results to it.
439 if (!m_context->paintsIntoCanvasBuffer())
440 m_context->paintRenderingResultsToCanvas();
442 m_copiedImage = buffer()->copyImage();
444 return m_copiedImage.get();
447 void HTMLCanvasElement::clearCopiedImage()
449 m_copiedImage.clear();
452 AffineTransform HTMLCanvasElement::baseTransform() const
454 ASSERT(m_hasCreatedImageBuffer);
455 FloatSize unscaledSize(width(), height());
456 IntSize size = convertLogicalToDevice(unscaledSize);
457 AffineTransform transform;
458 if (size.width() && size.height())
459 transform.scaleNonUniform(size.width() / unscaledSize.width(), size.height() / unscaledSize.height());
460 return m_imageBuffer->baseTransform() * transform;