Avoid repainting the entire canvas element when possible.
[WebKit-https.git] / 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  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "HTMLCanvasElement.h"
29
30 #include "CanvasGradient.h"
31 #include "CanvasPattern.h"
32 #include "CanvasRenderingContext2D.h"
33 #include "CanvasStyle.h"
34 #include "Chrome.h"
35 #include "Document.h"
36 #include "Frame.h"
37 #include "GraphicsContext.h"
38 #include "HTMLNames.h"
39 #include "Page.h"
40 #include "RenderHTMLCanvas.h"
41 #include "Settings.h"
42 #include <math.h>
43
44 #if PLATFORM(QT)
45 #include <QPainter>
46 #include <QPixmap>
47 #elif PLATFORM(CAIRO)
48 #include <cairo.h>
49 #endif
50
51 namespace WebCore {
52
53 using namespace HTMLNames;
54
55 // These values come from the WhatWG spec.
56 static const int defaultWidth = 300;
57 static const int defaultHeight = 150;
58
59 // Firefox limits width/height to 32767 pixels, but slows down dramatically before it 
60 // reaches that limit. We limit by area instead, giving us larger maximum dimensions,
61 // in exchange for a smaller maximum canvas size.
62 static const float maxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels
63
64 HTMLCanvasElement::HTMLCanvasElement(Document* doc)
65     : HTMLElement(canvasTag, doc)
66     , m_size(defaultWidth, defaultHeight)
67     , m_createdDrawingContext(false)
68     , m_data(0)
69 #if PLATFORM(QT)
70     , m_painter(0)
71 #elif PLATFORM(CAIRO)
72     , m_surface(0)
73 #endif
74     , m_drawingContext(0)
75 {
76 }
77
78 HTMLCanvasElement::~HTMLCanvasElement()
79 {
80     if (m_2DContext)
81         m_2DContext->detachCanvas();
82 #if PLATFORM(CG)
83     fastFree(m_data);
84 #elif PLATFORM(QT)
85     delete m_painter;
86     delete m_data;
87 #elif PLATFORM(CAIRO)
88     if (m_surface)
89         cairo_surface_destroy(m_surface);
90 #endif
91     delete m_drawingContext;
92 }
93
94 HTMLTagStatus HTMLCanvasElement::endTagRequirement() const 
95 {
96     Settings* settings = document()->settings();
97     if (settings && settings->usesDashboardBackwardCompatibilityMode())
98         return TagStatusForbidden; 
99
100     return HTMLElement::endTagRequirement();
101 }
102
103 int HTMLCanvasElement::tagPriority() const 
104
105     Settings* settings = document()->settings();
106     if (settings && settings->usesDashboardBackwardCompatibilityMode())
107         return 0; 
108
109     return HTMLElement::tagPriority();
110 }
111
112 void HTMLCanvasElement::parseMappedAttribute(MappedAttribute* attr)
113 {
114     const QualifiedName& attrName = attr->name();
115     if (attrName == widthAttr || attrName == heightAttr)
116         reset();
117     HTMLElement::parseMappedAttribute(attr);
118 }
119
120 RenderObject* HTMLCanvasElement::createRenderer(RenderArena* arena, RenderStyle* style)
121 {
122     Settings* settings = document()->settings();
123     if (settings && settings->isJavaScriptEnabled()) {
124         m_rendererIsCanvas = true;
125         return new (arena) RenderHTMLCanvas(this);
126     }
127
128     m_rendererIsCanvas = false;
129     return HTMLElement::createRenderer(arena, style);
130 }
131
132 void HTMLCanvasElement::setHeight(int value)
133 {
134     setAttribute(heightAttr, String::number(value));
135 }
136
137 void HTMLCanvasElement::setWidth(int value)
138 {
139     setAttribute(widthAttr, String::number(value));
140 }
141
142 CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type)
143 {
144     if (type == "2d") {
145         if (!m_2DContext)
146             m_2DContext = new CanvasRenderingContext2D(this);
147         return m_2DContext.get();
148     }
149     return 0;
150 }
151
152 void HTMLCanvasElement::willDraw(const FloatRect& rect)
153 {
154     if (RenderObject* ro = renderer()) {
155         // Handle CSS triggered scaling
156         float widthScale = static_cast<float>(ro->width()) / static_cast<float>(m_size.width());
157         float heightScale = static_cast<float>(ro->height()) / static_cast<float>(m_size.height());
158         FloatRect r(rect.x() * widthScale, rect.y() * heightScale, rect.width() * widthScale, rect.height() * heightScale);
159         ro->repaintRectangle(enclosingIntRect(r));
160     }
161 }
162
163 void HTMLCanvasElement::reset()
164 {
165     bool ok;
166     int w = getAttribute(widthAttr).toInt(&ok);
167     if (!ok)
168         w = defaultWidth;
169     int h = getAttribute(heightAttr).toInt(&ok);
170     if (!ok)
171         h = defaultHeight;
172
173     IntSize oldSize = m_size;
174     m_size = IntSize(w, h);
175
176     bool hadDrawingContext = m_createdDrawingContext;
177     m_createdDrawingContext = false;
178 #if PLATFORM(CG)
179     fastFree(m_data);
180 #elif PLATFORM(QT)
181     delete m_painter;
182     m_painter = 0;
183     delete m_data;
184 #elif PLATFORM(CAIRO)
185     if (m_surface)
186         cairo_surface_destroy(m_surface);
187     m_surface = 0;
188 #endif
189     m_data = 0;
190     delete m_drawingContext;
191     m_drawingContext = 0;
192     if (m_2DContext)
193         m_2DContext->reset();
194
195     if (RenderObject* ro = renderer())
196         if (m_rendererIsCanvas) {
197             if (oldSize != m_size)
198                 static_cast<RenderHTMLCanvas*>(ro)->canvasSizeChanged();
199             if (hadDrawingContext)
200                 ro->repaint();
201         }
202 }
203
204 void HTMLCanvasElement::paint(GraphicsContext* p, const IntRect& r)
205 {
206     if (p->paintingDisabled())
207         return;
208 #if PLATFORM(CG)
209     if (CGImageRef image = createPlatformImage()) {
210         CGContextDrawImage(p->platformContext(), p->roundToDevicePixels(r), image);
211         CGImageRelease(image);
212     }
213 #elif PLATFORM(QT)
214     if (m_data) {
215         QPen currentPen = m_painter->pen();
216         qreal currentOpacity = m_painter->opacity();
217         QBrush currentBrush = m_painter->brush();
218         QBrush currentBackground = m_painter->background();
219         if (m_painter->isActive())
220             m_painter->end();
221         static_cast<QPainter*>(p->platformContext())->drawImage(r, *m_data);
222         m_painter->begin(m_data);
223         m_painter->setPen(currentPen);
224         m_painter->setBrush(currentBrush);
225         m_painter->setOpacity(currentOpacity);
226         m_painter->setBackground(currentBackground);
227     }
228 #elif PLATFORM(CAIRO)
229     if (cairo_surface_t* image = createPlatformImage()) {
230         cairo_t* cr = p->platformContext();
231         cairo_save(cr);
232         cairo_translate(cr, r.x(), r.y());
233         cairo_set_source_surface(cr, image, 0, 0);
234         cairo_surface_destroy(image);
235         cairo_rectangle(cr, 0, 0, r.width(), r.height());
236         cairo_fill(cr);
237         cairo_restore(cr);
238     }
239 #endif
240 }
241
242 void HTMLCanvasElement::createDrawingContext() const
243 {
244     ASSERT(!m_createdDrawingContext);
245     ASSERT(!m_data);
246
247     m_createdDrawingContext = true;
248
249     float unscaledWidth = width();
250     float unscaledHeight = height();
251     float pageScaleFactor = document()->frame() ? document()->frame()->page()->chrome()->scaleFactor() : 1.0f;
252     float wf = ceilf(unscaledWidth * pageScaleFactor);
253     float hf = ceilf(unscaledHeight * pageScaleFactor);
254
255     if (!(wf >= 1 && hf >= 1 && wf * hf <= maxCanvasArea))
256         return;
257
258     unsigned w = static_cast<unsigned>(wf);
259     unsigned h = static_cast<unsigned>(hf);
260
261 #if PLATFORM(CG)
262     size_t bytesPerRow = w * 4;
263     if (bytesPerRow / 4 != w) // check for overflow
264         return;
265     m_data = fastCalloc(h, bytesPerRow);
266     if (!m_data)
267         return;
268     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
269     CGContextRef bitmapContext = CGBitmapContextCreate(m_data, w, h, 8, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
270     CGContextScaleCTM(bitmapContext, w / unscaledWidth, h / unscaledHeight);
271     CGColorSpaceRelease(colorSpace);
272     m_drawingContext = new GraphicsContext(bitmapContext);
273     CGContextRelease(bitmapContext);
274 #elif PLATFORM(QT)
275     m_data = new QImage(w, h, QImage::Format_ARGB32_Premultiplied);
276     if (!m_data)
277         return;
278     m_painter = new QPainter(m_data);
279     m_painter->setBackground(QBrush(Qt::transparent));
280     m_painter->fillRect(0, 0, w, h, QColor(Qt::transparent));
281     m_drawingContext = new GraphicsContext(m_painter);
282 #elif PLATFORM(CAIRO)
283     m_surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h);
284     // m_data is owned by m_surface
285     m_data = cairo_image_surface_get_data(m_surface);
286     cairo_t* cr = cairo_create(m_surface);
287     cairo_scale(cr, w / unscaledWidth, h / unscaledHeight);
288     m_drawingContext = new GraphicsContext(cr);
289     cairo_destroy(cr);
290 #endif
291 }
292
293 GraphicsContext* HTMLCanvasElement::drawingContext() const
294 {
295     if (!m_createdDrawingContext)
296         createDrawingContext();
297     return m_drawingContext;
298 }
299
300 #if PLATFORM(CG)
301
302 CGImageRef HTMLCanvasElement::createPlatformImage() const
303 {
304     GraphicsContext* context = drawingContext();
305     if (!context)
306         return 0;
307
308     CGContextRef contextRef = context->platformContext();
309     if (!contextRef)
310         return 0;
311
312     CGContextFlush(contextRef);
313
314     return CGBitmapContextCreateImage(contextRef);
315 }
316
317 #elif PLATFORM(QT)
318
319 QImage HTMLCanvasElement::createPlatformImage() const
320 {
321     if (m_data)
322         return *m_data;
323     return QImage();
324 }
325
326 #elif PLATFORM(CAIRO)
327 cairo_surface_t* HTMLCanvasElement::createPlatformImage() const
328 {
329     if (!m_surface)
330         return 0;
331
332     // Note that unlike CG, our returned image is not a copy or
333     // copy-on-write, but the original. This is fine, since it is only
334     // ever used as a source.
335
336     cairo_surface_flush(m_surface);
337     cairo_surface_reference(m_surface);
338     return m_surface;
339 }
340
341 #endif
342
343 }