OSDN Git Service

Merge WebKit at r78450: Initial merge by git.
[android-x86/external-webkit.git] / Source / WebCore / html / HTMLCanvasElement.cpp
1 /*
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.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
14  *
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. 
26  */
27
28 #include "config.h"
29 #include "HTMLCanvasElement.h"
30
31 #include "Attribute.h"
32 #include "CanvasContextAttributes.h"
33 #include "CanvasGradient.h"
34 #include "CanvasPattern.h"
35 #include "CanvasRenderingContext2D.h"
36 #include "CanvasStyle.h"
37 #include "Chrome.h"
38 #include "Document.h"
39 #include "ExceptionCode.h"
40 #include "Frame.h"
41 #include "GraphicsContext.h"
42 #include "HTMLNames.h"
43 #include "ImageBuffer.h"
44 #include "MIMETypeRegistry.h"
45 #include "Page.h"
46 #include "RenderHTMLCanvas.h"
47 #include "Settings.h"
48 #include <math.h>
49 #include <stdio.h>
50
51 #if USE(JSC)
52 #include <runtime/JSLock.h>
53 #endif
54
55 #if ENABLE(WEBGL)    
56 #include "WebGLContextAttributes.h"
57 #include "WebGLRenderingContext.h"
58 #endif
59
60 namespace WebCore {
61
62 using namespace HTMLNames;
63
64 // These values come from the WhatWG spec.
65 static const int DefaultWidth = 300;
66 static const int DefaultHeight = 150;
67
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
72
73 //In Skia, we will also limit width/height to 32767.
74 static const float MaxSkiaDim = 32767.0F; // Maximum width/height in CSS pixels.
75
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)
81     , m_originClean(true)
82     , m_hasCreatedImageBuffer(false)
83 {
84     ASSERT(hasTagName(canvasTag));
85 }
86
87 PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(Document* document)
88 {
89     return adoptRef(new HTMLCanvasElement(canvasTag, document));
90 }
91
92 PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(const QualifiedName& tagName, Document* document)
93 {
94     return adoptRef(new HTMLCanvasElement(tagName, document));
95 }
96
97 HTMLCanvasElement::~HTMLCanvasElement()
98 {
99     HashSet<CanvasObserver*>::iterator end = m_observers.end();
100     for (HashSet<CanvasObserver*>::iterator it = m_observers.begin(); it != end; ++it)
101         (*it)->canvasDestroyed(this);
102 }
103
104 void HTMLCanvasElement::parseMappedAttribute(Attribute* attr)
105 {
106     const QualifiedName& attrName = attr->name();
107     if (attrName == widthAttr || attrName == heightAttr)
108         reset();
109     HTMLElement::parseMappedAttribute(attr);
110 }
111
112 RenderObject* HTMLCanvasElement::createRenderer(RenderArena* arena, RenderStyle* style)
113 {
114     Frame* frame = document()->frame();
115     if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
116         m_rendererIsCanvas = true;
117         return new (arena) RenderHTMLCanvas(this);
118     }
119
120     m_rendererIsCanvas = false;
121     return HTMLElement::createRenderer(arena, style);
122 }
123
124 void HTMLCanvasElement::addObserver(CanvasObserver* observer)
125 {
126     m_observers.add(observer);
127 }
128
129 void HTMLCanvasElement::removeObserver(CanvasObserver* observer)
130 {
131     m_observers.remove(observer);
132 }
133
134 void HTMLCanvasElement::setHeight(int value)
135 {
136     setAttribute(heightAttr, String::number(value));
137 }
138
139 void HTMLCanvasElement::setWidth(int value)
140 {
141     setAttribute(widthAttr, String::number(value));
142 }
143
144 CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, CanvasContextAttributes* attrs)
145 {
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.
150     
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.
154     if (type == "2d") {
155         if (m_context && !m_context->is2d())
156             return 0;
157         if (!m_context) {
158             bool usesDashbardCompatibilityMode = false;
159 #if ENABLE(DASHBOARD_SUPPORT)
160             if (Settings* settings = document()->settings())
161                 usesDashbardCompatibilityMode = settings->usesDashboardBackwardCompatibilityMode();
162 #endif
163             m_context = adoptPtr(new CanvasRenderingContext2D(this, document()->inQuirksMode(), usesDashbardCompatibilityMode));
164 #if USE(IOSURFACE_CANVAS_BACKING_STORE) || (ENABLE(ACCELERATED_2D_CANVAS) && USE(ACCELERATED_COMPOSITING))
165             if (m_context) {
166                 // Need to make sure a RenderLayer and compositing layer get created for the Canvas
167                 setNeedsStyleRecalc(SyntheticStyleChange);
168             }
169 #endif
170         }
171         return m_context.get();
172     }
173 #if ENABLE(WEBGL)    
174     Settings* settings = document()->settings();
175     if (settings && settings->webGLEnabled()
176 #if !PLATFORM(CHROMIUM) && !PLATFORM(QT)
177         && settings->acceleratedCompositingEnabled()
178 #endif
179         ) {
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())
185                 return 0;
186             if (!m_context) {
187                 m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
188                 if (m_context) {
189                     // Need to make sure a RenderLayer and compositing layer get created for the Canvas
190                     setNeedsStyleRecalc(SyntheticStyleChange);
191                 }
192             }
193             return m_context.get();
194         }
195     }
196 #else
197     UNUSED_PARAM(attrs);
198 #endif
199     return 0;
200 }
201
202 void HTMLCanvasElement::didDraw(const FloatRect& rect)
203 {
204     m_copiedImage.clear(); // Clear our image snapshot if we have one.
205
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))
211             return;
212
213         m_dirtyRect.unite(r);
214         ro->repaintRectangle(enclosingIntRect(m_dirtyRect));
215     }
216
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);
220 }
221
222 void HTMLCanvasElement::reset()
223 {
224     if (m_ignoreReset)
225         return;
226
227     bool ok;
228     bool hadImageBuffer = hasCreatedImageBuffer();
229     int w = getAttribute(widthAttr).toInt(&ok);
230     if (!ok || w < 0)
231         w = DefaultWidth;
232     int h = getAttribute(heightAttr).toInt(&ok);
233     if (!ok || h < 0)
234         h = DefaultHeight;
235
236     IntSize oldSize = size();
237     setSurfaceSize(IntSize(w, h)); // The image buffer gets cleared here.
238
239 #if ENABLE(WEBGL)
240     if (m_context && m_context->is3d() && oldSize != size())
241         static_cast<WebGLRenderingContext*>(m_context.get())->reshape(width(), height());
242 #endif
243
244     if (m_context && m_context->is2d())
245         static_cast<CanvasRenderingContext2D*>(m_context.get())->reset();
246
247     if (RenderObject* renderer = this->renderer()) {
248         if (m_rendererIsCanvas) {
249             if (oldSize != size())
250                 toRenderHTMLCanvas(renderer)->canvasSizeChanged();
251             if (hadImageBuffer)
252                 renderer->repaint();
253         }
254     }
255
256     HashSet<CanvasObserver*>::iterator end = m_observers.end();
257     for (HashSet<CanvasObserver*>::iterator it = m_observers.begin(); it != end; ++it)
258         (*it)->canvasResized(this);
259 }
260
261 void HTMLCanvasElement::paint(GraphicsContext* context, const IntRect& r)
262 {
263     // Clear the dirty rect
264     m_dirtyRect = FloatRect();
265
266     if (context->paintingDisabled())
267         return;
268     
269     if (m_context) {
270         if (!m_context->paintsIntoCanvasBuffer())
271             return;
272         m_context->paintRenderingResultsToCanvas();
273     }
274
275     if (hasCreatedImageBuffer()) {
276         ImageBuffer* imageBuffer = buffer();
277         if (imageBuffer) {
278             if (imageBuffer->drawsUsingCopy())
279                 context->drawImage(copiedImage(), ColorSpaceDeviceRGB, r);
280             else
281                 context->drawImageBuffer(imageBuffer, ColorSpaceDeviceRGB, r);
282         }
283     }
284 }
285
286 #if ENABLE(WEBGL)    
287 bool HTMLCanvasElement::is3D() const
288 {
289     return m_context && m_context->is3d();
290 }
291 #endif
292
293 void HTMLCanvasElement::makeRenderingResultsAvailable()
294 {
295     if (m_context)
296         m_context->paintRenderingResultsToCanvas();
297 }
298
299 void HTMLCanvasElement::attach()
300 {
301     HTMLElement::attach();
302
303     if (m_context && m_context->is2d()) {
304         CanvasRenderingContext2D* ctx = static_cast<CanvasRenderingContext2D*>(m_context.get());
305         ctx->updateFont();
306     }
307 }
308
309 void HTMLCanvasElement::recalcStyle(StyleChange change)
310 {
311     HTMLElement::recalcStyle(change);
312
313     // Update font if needed.
314     if (change == Force && m_context && m_context->is2d()) {
315         CanvasRenderingContext2D* ctx = static_cast<CanvasRenderingContext2D*>(m_context.get());
316         ctx->updateFont();
317     }
318 }
319
320 void HTMLCanvasElement::setSurfaceSize(const IntSize& size)
321 {
322     m_size = size;
323     m_hasCreatedImageBuffer = false;
324     m_imageBuffer.clear();
325     m_copiedImage.clear();
326 }
327
328 String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionCode& ec)
329 {
330     if (!m_originClean) {
331         ec = SECURITY_ERR;
332         return String();
333     }
334
335     if (m_size.isEmpty() || !buffer())
336         return String("data:,");
337
338     String lowercaseMimeType = mimeType.lower();
339
340     makeRenderingResultsAvailable();
341
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");
345
346     return buffer()->toDataURL(lowercaseMimeType, quality);
347 }
348
349 IntRect HTMLCanvasElement::convertLogicalToDevice(const FloatRect& logicalRect) const
350 {
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);
355     
356     return IntRect(IntPoint(left, top), convertToValidDeviceSize(right - left, bottom - top));
357 }
358
359 IntSize HTMLCanvasElement::convertLogicalToDevice(const FloatSize& logicalSize) const
360 {
361     return convertToValidDeviceSize(logicalSize.width() * m_pageScaleFactor, logicalSize.height() * m_pageScaleFactor);
362 }
363
364 IntSize HTMLCanvasElement::convertToValidDeviceSize(float width, float height) const
365 {
366     width = ceilf(width);
367     height = ceilf(height);
368     
369     if (width < 1 || height < 1 || width * height > MaxCanvasArea)
370         return IntSize();
371
372 #if PLATFORM(SKIA)
373     if (width > MaxSkiaDim || height > MaxSkiaDim)
374         return IntSize();
375 #endif
376
377     return IntSize(width, height);
378 }
379
380 const SecurityOrigin& HTMLCanvasElement::securityOrigin() const
381 {
382     return *document()->securityOrigin();
383 }
384
385 CSSStyleSelector* HTMLCanvasElement::styleSelector()
386 {
387     return document()->styleSelector();
388 }
389
390 void HTMLCanvasElement::createImageBuffer() const
391 {
392     ASSERT(!m_imageBuffer);
393
394     m_hasCreatedImageBuffer = true;
395
396     FloatSize unscaledSize(width(), height());
397     IntSize size = convertLogicalToDevice(unscaledSize);
398     if (!size.width() || !size.height())
399         return;
400
401 #if USE(IOSURFACE_CANVAS_BACKING_STORE)
402     m_imageBuffer = ImageBuffer::create(size, ColorSpaceDeviceRGB, Accelerated);
403 #else
404     m_imageBuffer = ImageBuffer::create(size);
405 #endif
406     // The convertLogicalToDevice MaxCanvasArea check should prevent common cases
407     // where ImageBuffer::create() returns 0, however we could still be low on memory.
408     if (!m_imageBuffer)
409         return;
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);
413
414 #if USE(JSC)
415     if (hasCachedDOMNodeWrapperUnchecked(document(), const_cast<HTMLCanvasElement*>(this))) {
416         JSC::JSLock lock(JSC::SilenceAssertionsOnly);
417         scriptExecutionContext()->globalData()->heap.reportExtraMemoryCost(m_imageBuffer->dataSize());
418     }
419 #endif
420 }
421
422 GraphicsContext* HTMLCanvasElement::drawingContext() const
423 {
424     return buffer() ? m_imageBuffer->context() : 0;
425 }
426
427 ImageBuffer* HTMLCanvasElement::buffer() const
428 {
429     if (!m_hasCreatedImageBuffer)
430         createImageBuffer();
431     return m_imageBuffer.get();
432 }
433
434 Image* HTMLCanvasElement::copiedImage() const
435 {
436     if (!m_copiedImage && buffer()) {
437         if (m_context) {
438             // If we're not rendering to the ImageBuffer, copy the rendering results to it.
439             if (!m_context->paintsIntoCanvasBuffer())
440                 m_context->paintRenderingResultsToCanvas();
441         }
442         m_copiedImage = buffer()->copyImage();
443     }
444     return m_copiedImage.get();
445 }
446
447 void HTMLCanvasElement::clearCopiedImage()
448 {
449     m_copiedImage.clear();
450 }
451
452 AffineTransform HTMLCanvasElement::baseTransform() const
453 {
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;
461 }
462
463 }