summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJustin McPherson <justin.mcpherson@nokia.com>2012-02-09 15:46:09 +1000
committerQt by Nokia <qt-info@nokia.com>2012-02-10 07:24:29 +0100
commit66f740c5e7ea74e00808d8f1b73570726eeda5a0 (patch)
treea25f2eb3a3c38a19b31c48f1c281d80bf5f0b6a5
parentb06f7aa36c9c80211e662b30d248a1e5192b0460 (diff)
Refactor Canvas rendering paths.
Refactor Canvas rendering paths to enable different drawing contexts. Change-Id: If0e00a14baa673fca6b999a787b4e89885bb1e51 Reviewed-by: Yunqiao Yin <charles.yin@nokia.com>
-rw-r--r--examples/declarative/canvas/bezierCurve/bezierCurve.qml2
-rw-r--r--examples/declarative/canvas/clip/clip.qml2
-rw-r--r--examples/declarative/canvas/pixels/pixels.qml14
-rw-r--r--examples/declarative/canvas/quadraticCurveTo/quadraticCurveTo.qml2
-rw-r--r--examples/declarative/canvas/roundedrect/roundedrect.qml2
-rw-r--r--examples/declarative/canvas/smile/smile.qml2
-rw-r--r--examples/declarative/canvas/squircle/squircle.qml2
-rw-r--r--examples/declarative/canvas/stockchart/stock.qml2
-rw-r--r--examples/declarative/canvas/tiger/tiger.qml2
-rw-r--r--examples/declarative/canvas/twitterfriends/twitter.qml2
-rw-r--r--src/quick/items/context2d/context2d.pri6
-rw-r--r--src/quick/items/context2d/qquickcanvascontext.cpp75
-rw-r--r--src/quick/items/context2d/qquickcanvascontext_p.h93
-rw-r--r--src/quick/items/context2d/qquickcanvasitem.cpp675
-rw-r--r--src/quick/items/context2d/qquickcanvasitem_p.h93
-rw-r--r--src/quick/items/context2d/qquickcanvasitemnode.cpp (renamed from src/quick/items/context2d/qquickcontext2dnode.cpp)41
-rw-r--r--src/quick/items/context2d/qquickcanvasitemnode_p.h (renamed from src/quick/items/context2d/qquickcontext2dnode_p.h)23
-rw-r--r--src/quick/items/context2d/qquickcontext2d.cpp173
-rw-r--r--src/quick/items/context2d/qquickcontext2d_p.h45
-rw-r--r--src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h5
-rw-r--r--src/quick/items/context2d/qquickcontext2dtexture.cpp104
-rw-r--r--src/quick/items/context2d/qquickcontext2dtile.cpp5
-rw-r--r--tests/auto/qtquick2/qquickcanvasitem/data/tst_canvas.qml78
-rw-r--r--tests/auto/qtquick2/qquickcanvasitem/data/tst_context.qml73
-rw-r--r--tests/auto/qtquick2/qquickcanvasitem/data/tst_fillrect.qml17
-rw-r--r--tests/auto/qtquick2/qquickcanvasitem/qquickcanvasitem.pro3
26 files changed, 1102 insertions, 439 deletions
diff --git a/examples/declarative/canvas/bezierCurve/bezierCurve.qml b/examples/declarative/canvas/bezierCurve/bezierCurve.qml
index 1e29911076..4dc9dd1cf5 100644
--- a/examples/declarative/canvas/bezierCurve/bezierCurve.qml
+++ b/examples/declarative/canvas/bezierCurve/bezierCurve.qml
@@ -65,7 +65,7 @@ Item {
property real rotate : rotateCtrl.value
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
Behavior on scaleX { SpringAnimation { spring: 2; damping: 0.2; loops:Animation.Infinite } }
diff --git a/examples/declarative/canvas/clip/clip.qml b/examples/declarative/canvas/clip/clip.qml
index c7c5ed0f5f..bf0d8fb75b 100644
--- a/examples/declarative/canvas/clip/clip.qml
+++ b/examples/declarative/canvas/clip/clip.qml
@@ -66,7 +66,7 @@ Item {
property string imagefile:"../contents/qt-logo.png"
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
Component.onCompleted:loadImage(canvas.imagefile);
onAlphaChanged:requestPaint();
diff --git a/examples/declarative/canvas/pixels/pixels.qml b/examples/declarative/canvas/pixels/pixels.qml
index 6bd0525f6a..bb67eae965 100644
--- a/examples/declarative/canvas/pixels/pixels.qml
+++ b/examples/declarative/canvas/pixels/pixels.qml
@@ -56,7 +56,7 @@ Item {
height:360
smooth:true
renderTarget:Canvas.FramebufferObject
- renderInThread:false
+ renderStrategy: Canvas.Cooperative
property string image :"../contents/qt-logo.png"
Component.onCompleted:loadImage(image);
onImageLoaded:requestPaint();
@@ -66,12 +66,12 @@ Item {
if (canvas.isImageLoaded(image)) {
var pixels = ctx.createImageData(image);
//pixels.mirror();
- pixels.filter(Canvas.GrayScale);
- //pixels.filter(Canvas.Threshold, 100); //default 127
- //pixels.filter(Canvas.Blur, 20); //default 10
- //pixels.filter(Canvas.Opaque);
- //pixels.filter(Canvas.Invert);
- //pixels.filter(Canvas.Convolute, [0,-1,0,
+ pixels.filter(ctx.GrayScale);
+ //pixels.filter(ctx.Threshold, 100); //default 127
+ //pixels.filter(ctx.Blur, 20); //default 10
+ //pixels.filter(ctx.Opaque);
+ //pixels.filter(ctx.Invert);
+ //pixels.filter(ctx.Convolute, [0,-1,0,
// -1,5,-1,
// 0,-1,0]);
//ctx.putImageData(pixels, 0, 0, canvas.width, canvas.height);
diff --git a/examples/declarative/canvas/quadraticCurveTo/quadraticCurveTo.qml b/examples/declarative/canvas/quadraticCurveTo/quadraticCurveTo.qml
index 3f565a8493..047fcfd949 100644
--- a/examples/declarative/canvas/quadraticCurveTo/quadraticCurveTo.qml
+++ b/examples/declarative/canvas/quadraticCurveTo/quadraticCurveTo.qml
@@ -65,7 +65,7 @@ Item {
property real rotate : rotateCtrl.value
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
onLineWidthChanged:requestPaint();
onFillChanged:requestPaint();
diff --git a/examples/declarative/canvas/roundedrect/roundedrect.qml b/examples/declarative/canvas/roundedrect/roundedrect.qml
index fceed9c38a..9fb9181fd1 100644
--- a/examples/declarative/canvas/roundedrect/roundedrect.qml
+++ b/examples/declarative/canvas/roundedrect/roundedrect.qml
@@ -55,7 +55,7 @@ Item {
height:360
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
property int radius: rCtrl.value
property int rectx: rxCtrl.value
diff --git a/examples/declarative/canvas/smile/smile.qml b/examples/declarative/canvas/smile/smile.qml
index 5963cde9af..44909564c9 100644
--- a/examples/declarative/canvas/smile/smile.qml
+++ b/examples/declarative/canvas/smile/smile.qml
@@ -56,7 +56,7 @@ Item {
height:360
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
property string strokeStyle:"green"
property string fillStyle:"yellow"
diff --git a/examples/declarative/canvas/squircle/squircle.qml b/examples/declarative/canvas/squircle/squircle.qml
index 801249b4d6..9c0860c9f5 100644
--- a/examples/declarative/canvas/squircle/squircle.qml
+++ b/examples/declarative/canvas/squircle/squircle.qml
@@ -61,7 +61,7 @@ Item {
height:360
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
property string strokeStyle:"blue"
property string fillStyle:"steelblue"
diff --git a/examples/declarative/canvas/stockchart/stock.qml b/examples/declarative/canvas/stockchart/stock.qml
index 0dfad6cf70..d02f07bc38 100644
--- a/examples/declarative/canvas/stockchart/stock.qml
+++ b/examples/declarative/canvas/stockchart/stock.qml
@@ -337,8 +337,8 @@ Rectangle {
anchors.bottom : view.top
width:container.width;
opacity:0
- renderInThread:false
renderTarget: Canvas.Image
+ renderStrategy: Canvas.Immediate
property bool running:false
property int frames:first
property int mouseX:0;
diff --git a/examples/declarative/canvas/tiger/tiger.qml b/examples/declarative/canvas/tiger/tiger.qml
index 4b1d9ff031..0e3770e6e3 100644
--- a/examples/declarative/canvas/tiger/tiger.qml
+++ b/examples/declarative/canvas/tiger/tiger.qml
@@ -57,7 +57,7 @@ Item {
height:360
smooth:true
renderTarget:Canvas.FramebufferObject
- renderInThread:false
+ renderStrategy: Canvas.Cooperative
property string strokeStyle:"steelblue"
property string fillStyle:"yellow"
property bool fill:true
diff --git a/examples/declarative/canvas/twitterfriends/twitter.qml b/examples/declarative/canvas/twitterfriends/twitter.qml
index d25773127d..81b29d2fda 100644
--- a/examples/declarative/canvas/twitterfriends/twitter.qml
+++ b/examples/declarative/canvas/twitterfriends/twitter.qml
@@ -98,7 +98,7 @@ Rectangle {
anchors.bottom : parent.bottom
smooth:true
renderTarget:Canvas.Image
- renderInThread:false
+ renderStrategy: Canvas.Immediate
property bool layoutChanged:true
property string twitterName:""
diff --git a/src/quick/items/context2d/context2d.pri b/src/quick/items/context2d/context2d.pri
index 60b3e4b0c1..84346f68c6 100644
--- a/src/quick/items/context2d/context2d.pri
+++ b/src/quick/items/context2d/context2d.pri
@@ -1,15 +1,17 @@
SOURCES += \
$$PWD/qquickcanvasitem.cpp \
+ $$PWD/qquickcanvascontext.cpp \
$$PWD/qquickcontext2d.cpp \
- $$PWD/qquickcontext2dnode.cpp \
+ $$PWD/qquickcanvasitemnode.cpp \
$$PWD/qquickcontext2dtile.cpp \
$$PWD/qquickcontext2dtexture.cpp \
$$PWD/qquickcontext2dcommandbuffer.cpp \
HEADERS += \
$$PWD/qquickcanvasitem_p.h \
+ $$PWD/qquickcanvascontext_p.h \
$$PWD/qquickcontext2d_p.h \
- $$PWD/qquickcontext2dnode_p.h \
+ $$PWD/qquickcanvasitemnode_p.h \
$$PWD/qquickcontext2dtile_p.h \
$$PWD/qquickcontext2dtexture_p.h \
$$PWD/qquickcontext2dcommandbuffer_p.h \
diff --git a/src/quick/items/context2d/qquickcanvascontext.cpp b/src/quick/items/context2d/qquickcanvascontext.cpp
new file mode 100644
index 0000000000..3e6e51c89d
--- /dev/null
+++ b/src/quick/items/context2d/qquickcanvascontext.cpp
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/
+**
+** This file is part of the QtDeclarative module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** GNU Lesser General Public License Usage
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this
+** file. Please review the following information to ensure the GNU Lesser
+** General Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU General
+** Public License version 3.0 as published by the Free Software Foundation
+** and appearing in the file LICENSE.GPL included in the packaging of this
+** file. Please review the following information to ensure the GNU General
+** Public License version 3.0 requirements will be met:
+** http://www.gnu.org/copyleft/gpl.html.
+**
+** Other Usage
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <private/qquickcanvascontext_p.h>
+
+
+QT_BEGIN_NAMESPACE
+
+QQuickCanvasContext::QQuickCanvasContext(QObject *parent)
+ : QObject(parent)
+{
+}
+
+QQuickCanvasContext::~QQuickCanvasContext()
+{
+}
+
+void QQuickCanvasContext::prepare(const QSize& canvasSize, const QSize& tileSize, const QRect& canvasWindow, const QRect& dirtyRect, bool smooth)
+{
+ Q_UNUSED(canvasSize);
+ Q_UNUSED(tileSize);
+ Q_UNUSED(canvasWindow);
+ Q_UNUSED(dirtyRect);
+ Q_UNUSED(smooth);
+}
+
+void QQuickCanvasContext::flush()
+{
+}
+
+void QQuickCanvasContext::sync()
+{
+}
+
+QT_END_NAMESPACE
+
+
diff --git a/src/quick/items/context2d/qquickcanvascontext_p.h b/src/quick/items/context2d/qquickcanvascontext_p.h
new file mode 100644
index 0000000000..6a2edef7a8
--- /dev/null
+++ b/src/quick/items/context2d/qquickcanvascontext_p.h
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/
+**
+** This file is part of the QtDeclarative module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** GNU Lesser General Public License Usage
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this
+** file. Please review the following information to ensure the GNU Lesser
+** General Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU General
+** Public License version 3.0 as published by the Free Software Foundation
+** and appearing in the file LICENSE.GPL included in the packaging of this
+** file. Please review the following information to ensure the GNU General
+** Public License version 3.0 requirements will be met:
+** http://www.gnu.org/copyleft/gpl.html.
+**
+** Other Usage
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QQUICKCANVASCONTEXT_P_H
+#define QQUICKCANVASCONTEXT_P_H
+
+#include <QtQuick/qquickitem.h>
+#include <private/qv8engine_p.h>
+
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+class QQuickCanvasItem;
+class QSGDynamicTexture;
+
+class QQuickCanvasContextPrivate;
+class QQuickCanvasContext : public QObject
+{
+ Q_OBJECT
+
+public:
+ QQuickCanvasContext(QObject *parent = 0);
+ ~QQuickCanvasContext();
+
+ virtual QStringList contextNames() const = 0;
+
+ // Init (ignore options if necessary)
+ virtual void init(QQuickCanvasItem *canvasItem, const QVariantMap &args) = 0;
+
+ virtual void prepare(const QSize& canvasSize, const QSize& tileSize, const QRect& canvasWindow, const QRect& dirtyRect, bool smooth);
+
+ // Indicate this is a good time to begin composition
+ virtual void flush();
+
+ // Cause render (if necessary) to surface via execution unit
+ virtual void sync();
+
+ virtual void setV8Engine(QV8Engine *engine) = 0;
+ virtual v8::Handle<v8::Object> v8value() const = 0;
+
+ virtual QSGDynamicTexture *texture() const = 0;
+
+ virtual QImage toImage(const QRectF& bounds) = 0;
+
+Q_SIGNALS:
+ void textureChanged();
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif //QQUICKCANVASCONTEXT_P_H
diff --git a/src/quick/items/context2d/qquickcanvasitem.cpp b/src/quick/items/context2d/qquickcanvasitem.cpp
index 2286be2ffd..53550b0b01 100644
--- a/src/quick/items/context2d/qquickcanvasitem.cpp
+++ b/src/quick/items/context2d/qquickcanvasitem.cpp
@@ -42,9 +42,9 @@
#include <private/qsgadaptationlayer_p.h>
#include "qquickcanvasitem_p.h"
#include <private/qquickitem_p.h>
-#include "qquickcontext2d_p.h"
-#include "qquickcontext2dnode_p.h"
-#include "qquickcontext2dtexture_p.h"
+#include <private/qquickcanvascontext_p.h>
+#include <private/qquickcontext2d_p.h>
+#include <private/qquickcanvasitemnode_p.h>
#include <QtQuick/private/qdeclarativepixmapcache_p.h>
#include <qdeclarativeinfo.h>
@@ -58,34 +58,36 @@ class QQuickCanvasItemPrivate : public QQuickItemPrivate
public:
QQuickCanvasItemPrivate();
~QQuickCanvasItemPrivate();
- QQuickContext2D* context;
- QQuickContext2DTexture* texture;
+ QQuickCanvasContext* context;
QSizeF canvasSize;
QSize tileSize;
QRectF canvasWindow;
QRectF dirtyRect;
- uint renderInThread : 1;
uint hasCanvasSize :1;
uint hasTileSize :1;
uint hasCanvasWindow :1;
- uint componentCompleted :1;
+ uint available :1;
+ uint contextInitialized :1;
QQuickCanvasItem::RenderTarget renderTarget;
+ QQuickCanvasItem::RenderStrategy renderStrategy;
+ QString contextType;
QHash<QUrl, QDeclarativePixmap*> images;
QUrl baseUrl;
+ QMap<int, v8::Persistent<v8::Function> > animationCallbacks;
};
QQuickCanvasItemPrivate::QQuickCanvasItemPrivate()
: QQuickItemPrivate()
, context(0)
- , texture(0)
, canvasSize(1, 1)
, tileSize(1, 1)
- , renderInThread(false)
, hasCanvasSize(false)
, hasTileSize(false)
, hasCanvasWindow(false)
- , componentCompleted(false)
- , renderTarget(QQuickCanvasItem::FramebufferObject)
+ , available(false)
+ , contextInitialized(false)
+ , renderTarget(QQuickCanvasItem::Image)
+ , renderStrategy(QQuickCanvasItem::Threaded)
{
}
@@ -94,6 +96,17 @@ QQuickCanvasItemPrivate::~QQuickCanvasItemPrivate()
qDeleteAll(images);
}
+class QQuickCanvasItemCallback : public QQuickCanvasItemNode::Callback
+{
+public:
+ QQuickCanvasItemCallback(QQuickCanvasItemPrivate *d):item(d) {}
+ void process() const {
+ // on SG render thread
+ item->context->sync();
+ }
+ QQuickCanvasItemPrivate *item;
+};
+
/*!
\qmlclass Canvas QQuickCanvasItem
\inqmlmodule QtQuick 2
@@ -103,19 +116,20 @@ QQuickCanvasItemPrivate::~QQuickCanvasItemPrivate()
\ingroup qml-basic-visual-elements
The Canvas item allows drawing of straight and curved lines, simple and
- complex shapes, graphs, and referenced graphic images. It can also add text, colors,
- shadows, gradients, and patterns, and do low level pixel operations. The Canvas
- output may be saved as an image file or serialized to a url.
-
- To define a drawing area in the Canvas item set the \c width and \c height properties.
- For example, the following code creates a Canvas item which has a drawing area with a height of 100
- pixels and width of 200 pixels:
+ complex shapes, graphs, and referenced graphic images. It can also add
+ text, colors, shadows, gradients, and patterns, and do low level pixel
+ operations. The Canvas output may be saved as an image file or serialized
+ to a URL.
+
+ To define a drawing area in the Canvas item set the \c width and \c height
+ properties. For example, the following code creates a Canvas item which
+ has a drawing area with a height of 100 pixels and width of 200 pixels:
\qml
import QtQuick 2.0
Canvas {
- id:mycanvas
- width:100
- height:200
+ id: mycanvas
+ width: 100
+ height: 200
}
\endqml
@@ -123,44 +137,52 @@ QQuickCanvasItemPrivate::~QQuickCanvasItemPrivate()
\section1 Threaded Rendering and Render Target
- The Canvas item supports two render targets: \c Canvas.Image and \c Canvas.FramebufferObject.
+ The Canvas item supports two render targets: \c Canvas.Image and
+ \c Canvas.FramebufferObject.
- The \c Canvas.Image render target is a \a QImage object. This render target supports background
- thread rendering, allowing complex or long running painting to be executed without blocking the UI.
+ The \c Canvas.Image render target is a \a QImage object. This render
+ target supports background thread rendering, allowing complex or long
+ running painting to be executed without blocking the UI.
- The Canvas.FramebufferObject render target utilizes OpenGL hardware accelaration rather than rendering into
- system memory, which in many cases results in faster rendering.
+ The Canvas.FramebufferObject render target utilizes OpenGL hardware
+ acceleration rather than rendering into system memory, which in many cases
+ results in faster rendering.
- The default render target is Canvas.Image and the default renderInThread property is
- false.
+ The default render target is Canvas.Image and the default renderStrategy is
+ Canvas.Threaded.
\section1 Tiled Canvas
The Canvas item supports tiled rendering by setting \l canvasSize, \l tileSize
and \l canvasWindow properties.
- Tiling allows efficient display of a very large virtual via a smaller canvas
- window. The actual memory consumption is in relatation to the canvas window size. The painting
- code can draw within the virtual canvas without handling coordinate system transformations.
+ Tiling allows efficient display of a very large virtual canvas via a smaller
+ canvas window. The actual memory consumption is in relation to the canvas
+ window size. The painting code can draw within the virtual canvas without
+ handling coordinate system transformations.
- The tiles overlapping with the canvas window may be cached eliminating the need to redraw,
- which can lead to significantly improved performance in some situations.
+ The tiles overlapping with the canvas window may be cached eliminating the
+ need to redraw, which can lead to significantly improved performance in
+ some situations.
\section1 Pixel Operations
- All HTML5 2D context pixel operations are supported. In order to ensure improved
- pixel reading/writing performance the \a Canvas.Image render target should be chosen. The
- \a Canvas.FramebufferObject render target requires the pixel data to be exchanged between
- the system memory and the graphic card, which is significantly more expensive. Rendering
- may also be synchronized with the V-sync signal (to avoid {en.wikipedia.org/wiki/Screen_tearing}{screen tearing})
- which will futher impact pixel operations with \c Canvas.FrambufferObject render target.
+ All HTML5 2D context pixel operations are supported. In order to ensure
+ improved pixel reading/writing performance the \a Canvas.Image render
+ target should be chosen. The \a Canvas.FramebufferObject render target
+ requires the pixel data to be exchanged between the system memory and the
+ graphic card, which is significantly more expensive. Rendering may also be
+ synchronized with the V-sync signal (to avoid
+ {en.wikipedia.org/wiki/Screen_tearing}{screen tearing}) which will further
+ impact pixel operations with \c Canvas.FrambufferObject render target.
\section1 Tips for Porting Existing HTML5 Canvas applications
- Although the Canvas item is provides a HTML5 like API, HTML5 canvas applications
- need to be modified to run in the Canvas item:
+ Although the Canvas item is provides a HTML5 like API, HTML5 canvas
+ applications need to be modified to run in the Canvas item:
\list
\o Replace all DOM API calls with QML property bindings or Canvas item methods.
\o Replace all HTML event handlers with the \a MouseArea item.
- \o Change setInterval/setTimeout function calls with the \a Timer item.
+ \o Change setInterval/setTimeout function calls with the \a Timer item or
+ the use of requestAnimationFrame.
\o Place painting code into the \a QtQuick2::Canvas::onPaint handler and trigger
painting by calling the \c markDirty or \c requestPaint methods.
\o To draw images, load them by calling the Canvas's loadImage method and then request to paint
@@ -183,14 +205,85 @@ QQuickCanvasItem::~QQuickCanvasItem()
}
/*!
+ \qmlproperty size QtQuick2::Canvas::available
+
+ Indicates when Canvas is able to provide a drawing context to operate on.
+*/
+
+bool QQuickCanvasItem::isAvailable() const
+{
+ return d_func()->available;
+}
+
+/*!
+ \qmlproperty string QtQuick2::Canvas::contextType
+ The type of drawing context to use.
+
+ This property is set to the name of the active context type.
+
+ If set explicitly the canvas will attempt to create a context of the
+ named type after becoming available.
+
+ The type name is the same as used in the getContext() call, for the 2d
+ canvas the value will be "2d".
+
+ \sa QtQuick2::Canvas::getContext QtQuick2::Canvas::available
+*/
+
+QString QQuickCanvasItem::contextType() const
+{
+ return d_func()->contextType;
+}
+
+void QQuickCanvasItem::setContextType(const QString &contextType)
+{
+ Q_D(QQuickCanvasItem);
+
+ if (contextType.compare(d->contextType, Qt::CaseInsensitive) == 0)
+ return;
+
+ if (d->contextInitialized) {
+ qmlInfo(this) << "Canvas already initialized with a different context type";
+ return;
+ }
+
+ d->contextType = contextType;
+
+ if (d->available)
+ createContext(contextType);
+
+ emit contextTypeChanged();
+}
+
+/*!
+ \qmlproperty object QtQuick2::Canvas::context
+ Holds the active drawing context.
+
+ If the canvas is ready and there has been a successful call to getContext()
+ or the contextType property has been set with a supported context type,
+ this property will contain the current drawing context, otherwise null.
+*/
+
+QDeclarativeV8Handle QQuickCanvasItem::context() const
+{
+ Q_D(const QQuickCanvasItem);
+ if (d->contextInitialized)
+ return QDeclarativeV8Handle::fromHandle(d->context->v8value());
+
+ return QDeclarativeV8Handle::fromHandle(v8::Null());
+}
+
+/*!
\qmlproperty size QtQuick2::Canvas::canvasSize
- Holds the logical canvas size that the context paints on.
+ Holds the logical canvas size that the context paints on.
- By default, the canvas size is the same size as the current canvas item size.
- By setting the canvasSize, tileSize and canvasWindow, the Canvas
- item can act as a large virtual canvas with many seperately rendered tile rectangles
- Only those tiles within the current canvas window are painted by
- the Canvas render engine.
+ By default, the canvas size is the same size as the current canvas item
+ size.
+
+ By setting the canvasSize, tileSize and canvasWindow, the Canvas item can
+ act as a large virtual canvas with many separately rendered tile rectangles
+ Only those tiles within the current canvas window are painted by the Canvas
+ render engine.
\sa QtQuick2::Canvas::tileSize QtQuick2::Canvas::canvasWindow
*/
@@ -207,24 +300,26 @@ void QQuickCanvasItem::setCanvasSize(const QSizeF & size)
d->hasCanvasSize = true;
d->canvasSize = size;
emit canvasSizeChanged();
- polish();
- update();
+
+ if (d->contextInitialized)
+ polish();
}
}
/*!
\qmlproperty size QtQuick2::Canvas::tileSize
- Holds the canvas rendering tile size.
+ Holds the canvas rendering tile size.
- The Canvas item enters tiled mode by setting canvasSize, tileSize and
- the canvasWindow. This can improve rendering performance
- by rendering and caching tiles instead of rendering the whole canvas every time.
+ The Canvas item enters tiled mode by setting canvasSize, tileSize and the
+ canvasWindow. This can improve rendering performance by rendering and
+ caching tiles instead of rendering the whole canvas every time.
- Memory will be consumed only by those tiles within the current visible region.
+ Memory will be consumed only by those tiles within the current visible
+ region.
- By default the tileSize is the same as the canvasSize.
+ By default the tileSize is the same as the canvasSize.
- \sa QtQuick2::Canvas::canvaasSize QtQuick2::Canvas::canvasWindow
+ \sa QtQuick2::Canvas::canvaasSize QtQuick2::Canvas::canvasWindow
*/
QSize QQuickCanvasItem::tileSize() const
{
@@ -240,8 +335,9 @@ void QQuickCanvasItem::setTileSize(const QSize & size)
d->tileSize = size;
emit tileSizeChanged();
- polish();
- update();
+
+ if (d->contextInitialized)
+ polish();
}
}
@@ -249,11 +345,11 @@ void QQuickCanvasItem::setTileSize(const QSize & size)
\qmlproperty rect QtQuick2::Canvas::canvasWindow
Holds the current canvas visible window.
- By default the canvasWindow size is the same as the Canvas item
- size with the topleft point as (0, 0).
+ By default the canvasWindow size is the same as the Canvas item size with
+ the top-left point as (0, 0).
- If the canvasSize is different to the Canvas item size, the Canvas
- item can display different visible areas by changing the canvas windowSize
+ If the canvasSize is different to the Canvas item size, the Canvas item
+ can display different visible areas by changing the canvas windowSize
and/or position.
\sa QtQuick2::Canvas::canvasSize QtQuick2::Canvas::tileSize
@@ -272,54 +368,28 @@ void QQuickCanvasItem::setCanvasWindow(const QRectF& rect)
d->hasCanvasWindow = true;
emit canvasWindowChanged();
- polish();
- update();
+
+ if (d->contextInitialized)
+ polish();
}
}
-
-QQuickContext2D* QQuickCanvasItem::context() const
-{
- Q_D(const QQuickCanvasItem);
- return d->context;
-}
/*!
- \qmlproperty bool QtQuick2::Canvas::renderInThread
- Holds the current canvas rendering mode.
+ \qmlproperty bool QtQuick2::Canvas::renderTarget
+ Holds the current canvas render target.
- Set renderInThread to true to render complex and long
- running painting in a dedicated background
- thread, avoiding blocking the main UI.
+ \list
+ \o Canvas.Image - render to an in memory image buffer.
+ \o Canvas.FramebufferObject - render to an OpenGL frame buffer
+ \endlist
- \note: Not all renderTargets support background rendering. If background rendering
- is not supported by the current renderTarget, the renderInThread
- property is ignored.
+ This hint is supplied along with renderStrategy to the graphics context to
+ determine the method of rendering. A renderStrategy, renderTarget or a
+ combination may not be supported by a graphics context, in which case the
+ context will choose appropriate options and Canvas will signal the change
+ to the properties.
- The default value is false.
- \sa QtQuick2::Canvas::renderTarget
-*/
-bool QQuickCanvasItem::renderInThread() const
-{
- Q_D(const QQuickCanvasItem);
- return d->renderInThread;
-}
-/*!
- \qmlproperty bool QtQuick2::Canvas::renderTarget
- Holds the current canvas render target.
-
- \list
- \o Canvas.Image - render to an in memory image buffer, the render
- target supports background rendering.
- \o Canvas.FramebufferObject - render to an OpenGL frame buffer,
- this render target will ignore the
- renderInThread property. The actual
- rendering happens in the main QML rendering
- process, which may be in a seperate render thread
- or in the main GUI thread depending upon the platform.
- \endlist
-
- The default render target is \c Canvas.Image.
- \sa QtQuick2::Canvas::renderInThread
+ The default render target is \c Canvas.Image.
*/
QQuickCanvasItem::RenderTarget QQuickCanvasItem::renderTarget() const
{
@@ -327,48 +397,80 @@ QQuickCanvasItem::RenderTarget QQuickCanvasItem::renderTarget() const
return d->renderTarget;
}
-void QQuickCanvasItem::setRenderTarget(RenderTarget target)
+void QQuickCanvasItem::setRenderTarget(QQuickCanvasItem::RenderTarget target)
{
Q_D(QQuickCanvasItem);
if (d->renderTarget != target) {
- d->renderTarget = target;
+ if (d->contextInitialized) // target not changeable once context is active
+ return;
- if (d->componentCompleted)
- createTexture();
+ d->renderTarget = target;
emit renderTargetChanged();
}
}
-void QQuickCanvasItem::_doPainting(const QRectF& region)
+/*!
+ \qmlproperty bool QtQuick2::Canvas::renderStrategy
+ Holds the current canvas rendering strategy.
+
+ \list
+ \o Canvas.Immediate - context will perform graphics commands immediately in the main UI thread.
+ \o Canvas.Threaded - context will defer graphics commands to a private rendering thread.
+ \o Canvas.Cooperative - context will defer graphics commands to the applications global render thread.
+ \endlist
+
+ This hint is supplied along with renderTarget to the graphics context to
+ determine the method of rendering. A renderStrategy, renderTarget or a
+ combination may not be supported by a graphics context, in which case the
+ context will choose appropriate options and Canvas will signal the change
+ to the properties.
+
+ Configuration or runtime tests may cause the QML Scene Graph to render in
+ the GUI thread. Selecting \c Canvas.Cooperative, does not guarantee
+ rendering will occur on a thread separate from the GUI thread.
+
+ The default value is \c Canvas.Threaded.
+
+ \sa QtQuick2::Canvas::renderTarget
+*/
+
+QQuickCanvasItem::RenderStrategy QQuickCanvasItem::renderStrategy() const
+{
+ return d_func()->renderStrategy;
+}
+
+void QQuickCanvasItem::setRenderStrategy(QQuickCanvasItem::RenderStrategy strategy)
{
Q_D(QQuickCanvasItem);
- emit paint(QDeclarativeV8Handle::fromHandle(d->context->v8value())
- , QQuickContext2DTexture::tiledRect(region, d->tileSize));
- if (d->texture)
- d->texture->wake();
+ if (d->renderStrategy != strategy) {
+ if (d->contextInitialized) // Render strategy not changeable once context is active
+ return;
+
+ d->renderStrategy = strategy;
+ emit renderStrategyChanged();
+ }
}
-void QQuickCanvasItem::setRenderInThread(bool renderInThread)
+QQuickCanvasContext* QQuickCanvasItem::rawContext() const
+{
+ return d_func()->context;
+}
+
+void QQuickCanvasItem::sceneGraphInitialized()
{
Q_D(QQuickCanvasItem);
- if (d->renderInThread != renderInThread) {
- d->renderInThread = renderInThread;
- if (d->componentCompleted)
- createTexture();
+ d->available = true;
+ connect(this, SIGNAL(visibleChanged()), SLOT(checkAnimationCallbacks()));
+ QMetaObject::invokeMethod(this, "availableChanged", Qt::QueuedConnection);
- if (d->renderInThread)
- connect(this, SIGNAL(painted()), SLOT(update()));
- else
- disconnect(this, SIGNAL(painted()), this, SLOT(update()));
- emit renderInThreadChanged();
- polish();
- update();
- }
+ if (!d->contextType.isNull())
+ QMetaObject::invokeMethod(this, "delayedCreate", Qt::QueuedConnection);
+ else if (receivers(SIGNAL(paint(QRect))) > 0)
+ QMetaObject::invokeMethod(this, "requestPaint", Qt::QueuedConnection);
}
-void QQuickCanvasItem::geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry)
+void QQuickCanvasItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_D(QQuickCanvasItem);
QQuickItem::geometryChanged(newGeometry, oldGeometry);
@@ -387,140 +489,236 @@ void QQuickCanvasItem::geometryChanged(const QRectF &newGeometry,
}
if (!d->hasCanvasWindow) {
- d->canvasWindow = newGeometry;
+ d->canvasWindow = QRectF(0, 0, w, h);
emit canvasWindowChanged();
}
- polish();
- update();
+ if (d->available) {
+ polish();
+ update();
+ }
}
void QQuickCanvasItem::componentComplete()
{
- Q_D(QQuickCanvasItem);
QQuickItem::componentComplete();
- if (!d->context)
- createContext();
- createTexture();
-
+ Q_D(QQuickCanvasItem);
d->baseUrl = qmlEngine(this)->contextForObject(this)->baseUrl();
- requestPaint();
- updatePolish(); //force update the canvas sizes to texture for the first time
- update();
- d->componentCompleted = true;
}
-void QQuickCanvasItem::updatePolish()
+void QQuickCanvasItem::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &value)
{
+ QQuickItem::itemChange(change, value);
+ if (change != QQuickItem::ItemSceneChange)
+ return;
+
Q_D(QQuickCanvasItem);
+ if (d->available)
+ return;
+
+ if (value.canvas == 0)
+ return;
+
+ d->canvas = value.canvas;
+ if (d->canvas->openglContext() != 0) // available context == initialized
+ sceneGraphInitialized();
+ else
+ connect(d->canvas, SIGNAL(sceneGraphInitialized()), SLOT(sceneGraphInitialized()));
+}
+
+void QQuickCanvasItem::updatePolish()
+{
QQuickItem::updatePolish();
- if (d->texture) {
- if (!d->renderInThread && d->dirtyRect.isValid())
- _doPainting(d->dirtyRect);
-
- d->texture->canvasChanged(d->canvasSize.toSize()
- , d->tileSize
- , d->canvasWindow.toAlignedRect()
- , d->dirtyRect.toAlignedRect()
- , d->smooth);
- d->dirtyRect = QRectF();
+
+ Q_D(QQuickCanvasItem);
+
+ if (d->contextInitialized)
+ d->context->prepare(d->canvasSize.toSize(), d->tileSize, d->canvasWindow.toRect(), d->dirtyRect.toRect(), d->smooth);
+
+ if (d->animationCallbacks.size() > 0 && isVisible()) {
+ QMap<int, v8::Persistent<v8::Function> > animationCallbacks = d->animationCallbacks;
+ d->animationCallbacks.clear();
+
+ foreach (int key, animationCallbacks.keys()) {
+ v8::HandleScope handle_scope;
+ v8::Handle<v8::Object> self = QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this))->newQObject(this).As<v8::Object>();
+ v8::Handle<v8::Value> args[] = { v8::Uint32::New(QDateTime::currentDateTimeUtc().toTime_t()) };
+ v8::Persistent<v8::Function> f = animationCallbacks.value(key);
+ f->Call(self, 1, args);
+ f.Dispose();
+ }
}
+ else {
+ if (d->dirtyRect.isValid()) {
+ if (d->hasTileSize && d->hasCanvasWindow)
+ emit paint(tiledRect(d->canvasWindow.intersected(d->dirtyRect.toAlignedRect()), d->tileSize));
+ else
+ emit paint(d->dirtyRect.toRect());
+ d->dirtyRect = QRectF();
+ }
+ }
+
+ if (d->contextInitialized)
+ d->context->flush();
}
QSGNode *QQuickCanvasItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
Q_D(QQuickCanvasItem);
- QQuickContext2DNode *node = static_cast<QQuickContext2DNode *>(oldNode);
- if (!node)
- node = new QQuickContext2DNode(this);
- node->setTexture(d->texture);
+ if (!d->contextInitialized)
+ return 0;
+
+ QQuickCanvasItemNode *node = static_cast<QQuickCanvasItemNode*>(oldNode);
+ if (!node) {
+ node = new QQuickCanvasItemNode;
+ if (d->renderStrategy == QQuickCanvasItem::Cooperative)
+ node->setCallback(new QQuickCanvasItemCallback(d));
+ }
+
+ node->setTexture(d->context->texture());
node->setSize(d->canvasWindow.size());
node->update();
return node;
}
-void QQuickCanvasItem::createTexture()
+/*!
+ \qmlmethod object QtQuick2::Canvas::getContext(string contextId, any... args)
+
+ Returns a drawing context or null if no context available.
+
+ The \a contextId parameter names the required context. The Canvas element
+ will return a context that implements the required drawing mode. After the
+ first call to getContext any subsequent call to getContext with the same
+ contextId will return the same context object.
+
+ If the context type is not supported or the canvas has previously been
+ requested to provide a different and incompatible context type, null will
+ be returned.
+
+ Canvas only supports a 2d context.
+*/
+
+void QQuickCanvasItem::getContext(QDeclarativeV8Function *args)
{
Q_D(QQuickCanvasItem);
- if (!d->texture
- || d->texture->threadRendering() != d->renderInThread
- || d->texture->renderTarget() != d->renderTarget) {
- if (d->texture) {
- d->texture->deleteLater();
- d->texture = 0;
- }
+ if (args->Length() < 1 || !(*args)[0]->IsString()) {
+ qmlInfo(this) << "getContext should be called with a string naming the required context type";
+ args->returnValue(v8::Null());
+ return;
+ }
- if (d->renderTarget == QQuickCanvasItem::Image) {
- d->texture = new QQuickContext2DImageTexture(d->renderInThread);
- } else if (d->renderTarget == QQuickCanvasItem::FramebufferObject) {
- d->texture = new QQuickContext2DFBOTexture();
- }
+ if (!d->available) {
+ qmlInfo(this) << "Unable to use getContext() at this time, please wait for available: true";
+ args->returnValue(v8::Null());
+ return;
+ }
- if (d->renderInThread && !d->texture->supportThreadRendering()) {
- qWarning("Canvas: render target does not support thread rendering, force to non-thread rendering mode.");
- d->renderInThread = false;
- emit renderInThreadChanged();
- }
+ QString contextId = QString::fromUtf16(*v8::String::Value((*args)[0]));
- if (d->renderInThread)
- connect(d->texture, SIGNAL(textureChanged()), this, SLOT(update()));
+ if (d->context != 0) {
+ if (d->context->contextNames().contains(contextId, Qt::CaseInsensitive)) {
+ args->returnValue(d->context->v8value());
+ return;
+ }
- d->texture->setItem(this);
+ qmlInfo(this) << "Canvas already initialized with a different context type";
+ args->returnValue(v8::Null());
+ return;
}
+
+ if (createContext(contextId))
+ args->returnValue(d->context->v8value());
+ else
+ args->returnValue(v8::Null());
}
-void QQuickCanvasItem::createContext()
+/*!
+ \qmlmethod long QtQuick2::Canvas::requestAnimationFrame(callback)
+
+ This function schedules callback to be invoked before composing the QtQuick
+ scene.
+*/
+
+void QQuickCanvasItem::requestAnimationFrame(QDeclarativeV8Function *args)
{
+ if (args->Length() < 1 || !(*args)[0]->IsFunction()) {
+ qmlInfo(this) << "requestAnimationFrame should be called with an animation callback function";
+ args->returnValue(v8::Null());
+ return;
+ }
+
Q_D(QQuickCanvasItem);
- delete d->context;
+ static int id = 0;
- d->context = new QQuickContext2D(this);
+ d->animationCallbacks.insert(++id, v8::Persistent<v8::Function>::New(((*args)[0]).As<v8::Function>()));
- QV8Engine *e = QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this));
- d->context->setV8Engine(e);
+ if (isVisible())
+ polish();
+
+ args->returnValue(v8::Int32::New(id));
}
/*!
- \qmlmethod object QtQuick2::Canvas::getContext(string contextId)
+ \qmlmethod void QtQuick2::Canvas::cancelRequestAnimationFrmae(long handle)
- Currently, the canvas item only supports the 2D context. If the \a contextId
- parameter isn't provided or is "2d", then the QtQuick2::Context2D object is
- returned, otherwise returns an invalid value.
- */
-QDeclarativeV8Handle QQuickCanvasItem::getContext(const QString &contextId)
+ This function will cancel the animation callback referenced by \a handle.
+*/
+
+void QQuickCanvasItem::cancelRequestAnimationFrame(QDeclarativeV8Function *args)
{
- Q_D(QQuickCanvasItem);
+ if (args->Length() < 1 || !(*args)[0]->IsInt32()) {
+ qmlInfo(this) << "cancelRequestAnimationFrame should be called with an animation callback id";
+ args->returnValue(v8::Null());
+ return;
+ }
+
+ d_func()->animationCallbacks.remove((*args)[0]->Int32Value());
+}
- if (contextId.toLower() != QLatin1String("2d"))
- return QDeclarativeV8Handle::fromHandle(v8::Undefined());
- if (!d->context)
- createContext();
- return QDeclarativeV8Handle::fromHandle(d->context->v8value());
+/*!
+ \qmlmethod void QtQuick2::Canvas::requestPaint()
+
+ Request the entire visible region be re-drawn.
+
+ \sa QtQuick::Canvas::markDirty
+*/
+
+void QQuickCanvasItem::requestPaint()
+{
+ markDirty(d_func()->canvasWindow);
}
/*!
- \qmlmethod void QtQuick2::Canvas::markDirty(rect region)
+ \qmlmethod void QtQuick2::Canvas::markDirty(rect area)
- Mark the given \a region as dirty, so that when this region is visible
- the canvas renderer will redraw it. This will trigger the "onPaint" signal
+ Mark the given \a area as dirty, so that when this area is visible the
+ canvas renderer will redraw it. This will trigger the "onPaint" signal
handler function.
\sa QtQuick2::Canvas::paint QtQuick2::Canvas::requestPaint
*/
-void QQuickCanvasItem::markDirty(const QRectF& region)
+
+void QQuickCanvasItem::markDirty(const QRectF& rect)
{
Q_D(QQuickCanvasItem);
- d->dirtyRect |= region;
- if (d->componentCompleted)
- polish();
- update();
+ if (!d->available)
+ return;
+
+ d->dirtyRect |= rect;
+
+ polish();
}
+void QQuickCanvasItem::checkAnimationCallbacks()
+{
+ if (d_func()->animationCallbacks.size() > 0 && isVisible())
+ polish();
+}
/*!
\qmlmethod bool QtQuick2::Canvas::save(string filename)
@@ -642,15 +840,16 @@ bool QQuickCanvasItem::isImageLoaded(const QUrl& url) const
&& d->images.value(fullPathUrl)->isReady();
}
-QImage QQuickCanvasItem::toImage(const QRectF& region) const
+QImage QQuickCanvasItem::toImage(const QRectF& rect) const
{
Q_D(const QQuickCanvasItem);
- if (d->texture) {
- if (region.isEmpty())
- return d->texture->toImage(canvasWindow());
+ if (d->contextInitialized) {
+ if (rect.isEmpty())
+ return d->context->toImage(canvasWindow());
else
- return d->texture->toImage(region);
+ return d->context->toImage(rect);
}
+
return QImage();
}
@@ -696,13 +895,69 @@ QString QQuickCanvasItem::toDataURL(const QString& mimeType) const
return QLatin1Literal("data:,");
}
+void QQuickCanvasItem::delayedCreate()
+{
+ Q_D(QQuickCanvasItem);
+
+ if (!d->contextInitialized && !d->contextType.isNull())
+ createContext(d->contextType);
+
+ requestPaint();
+}
+
+bool QQuickCanvasItem::createContext(const QString &contextType)
+{
+ Q_D(QQuickCanvasItem);
+
+ if (contextType == QLatin1String("2d")) {
+ if (d->contextType.compare("2d", Qt::CaseInsensitive) != 0) {
+ d->contextType = QLatin1String("2d");
+ emit contextTypeChanged(); // XXX: can't be in setContextType()
+ }
+ initializeContext(new QQuickContext2D(this));
+ return true;
+ }
+
+ return false;
+}
+
+void QQuickCanvasItem::initializeContext(QQuickCanvasContext *context, const QVariantMap &args)
+{
+ Q_D(QQuickCanvasItem);
+
+ d->context = context;
+ d->context->init(this, args);
+ d->context->setV8Engine(QDeclarativeEnginePrivate::getV8Engine(qmlEngine(this)));
+ d->contextInitialized = true;
+ connect(d->context, SIGNAL(textureChanged()), SLOT(update()));
+ connect(d->context, SIGNAL(textureChanged()), SIGNAL(painted()));
+ emit contextChanged();
+}
+
+QRect QQuickCanvasItem::tiledRect(const QRectF &window, const QSize &tileSize)
+{
+ if (window.isEmpty())
+ return QRect();
+
+ const int tw = tileSize.width();
+ const int th = tileSize.height();
+ const int h1 = window.left() / tw;
+ const int v1 = window.top() / th;
+
+ const int htiles = ((window.right() - h1 * tw) + tw - 1)/tw;
+ const int vtiles = ((window.bottom() - v1 * th) + th - 1)/th;
+
+ return QRect(h1 * tw, v1 * th, htiles * tw, vtiles * th);
+}
+
/*!
- \qmlsignal QtQuick2::Canvas::onPaint(QtQuick2::Context2D context, rect region)
+ \qmlsignal QtQuick2::Canvas::onPaint(rect region)
- This handler is called to render the \a region.
+ This handler is called to render the \a region. If a context is active it
+ can be referenced from the context property.
- This signal can be triggered by QtQuick2::Canvas::markdirty, QtQuick2::Canvas::requestPaint
- or by changing the current canvas window.
+ This signal can be triggered by QtQuick2::Canvas::markdirty,
+ QtQuick2::Canvas::requestPaint or by changing the current canvas window.
*/
/*!
diff --git a/src/quick/items/context2d/qquickcanvasitem_p.h b/src/quick/items/context2d/qquickcanvasitem_p.h
index cb3ec74f21..0dad629eea 100644
--- a/src/quick/items/context2d/qquickcanvasitem_p.h
+++ b/src/quick/items/context2d/qquickcanvasitem_p.h
@@ -49,39 +49,46 @@ QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
-class QQuickContext2D;
+class QQuickCanvasContext;
+
class QQuickCanvasItemPrivate;
class Q_QUICK_EXPORT QQuickCanvasItem : public QQuickItem
{
Q_OBJECT
Q_ENUMS(RenderTarget)
- Q_ENUMS(ImageFilterMode)
+ Q_ENUMS(RenderStrategy)
+ Q_PROPERTY(bool available READ isAvailable NOTIFY availableChanged);
+ Q_PROPERTY(QString contextType READ contextType WRITE setContextType NOTIFY contextTypeChanged)
+ Q_PROPERTY(QDeclarativeV8Handle context READ context NOTIFY contextChanged);
Q_PROPERTY(QSizeF canvasSize READ canvasSize WRITE setCanvasSize NOTIFY canvasSizeChanged)
Q_PROPERTY(QSize tileSize READ tileSize WRITE setTileSize NOTIFY tileSizeChanged)
Q_PROPERTY(QRectF canvasWindow READ canvasWindow WRITE setCanvasWindow NOTIFY canvasWindowChanged)
- Q_PROPERTY(bool renderInThread READ renderInThread WRITE setRenderInThread NOTIFY renderInThreadChanged)
Q_PROPERTY(RenderTarget renderTarget READ renderTarget WRITE setRenderTarget NOTIFY renderTargetChanged)
+ Q_PROPERTY(RenderStrategy renderStrategy READ renderStrategy WRITE setRenderStrategy NOTIFY renderStrategyChanged)
+
public:
enum RenderTarget {
Image,
FramebufferObject
};
- enum ImageFilterMode {
- Threshold,
- Mono,
- GrayScale,
- Brightness,
- Invert,
- Blur,
- Opaque,
- Convolute
+ enum RenderStrategy {
+ Immediate,
+ Threaded,
+ Cooperative
};
QQuickCanvasItem(QQuickItem *parent = 0);
~QQuickCanvasItem();
+ bool isAvailable() const;
+
+ QString contextType() const;
+ void setContextType(const QString &contextType);
+
+ QDeclarativeV8Handle context() const;
+
QSizeF canvasSize() const;
void setCanvasSize(const QSizeF &);
@@ -91,54 +98,68 @@ public:
QRectF canvasWindow() const;
void setCanvasWindow(const QRectF& rect);
- bool renderInThread() const;
- void setRenderInThread(bool renderInThread);
-
RenderTarget renderTarget() const;
void setRenderTarget(RenderTarget target);
- QQuickContext2D* context() const;
- QImage toImage(const QRectF& region = QRectF()) const;
+ RenderStrategy renderStrategy() const;
+ void setRenderStrategy(RenderStrategy strategy);
+
+ QQuickCanvasContext* rawContext() const;
+
+ QImage toImage(const QRectF& rect = QRectF()) const;
+
+ Q_INVOKABLE void getContext(QDeclarativeV8Function *args);
+ Q_INVOKABLE void requestAnimationFrame(QDeclarativeV8Function *args);
+ Q_INVOKABLE void cancelRequestAnimationFrame(QDeclarativeV8Function *args);
+
+ Q_INVOKABLE void requestPaint();
+ Q_INVOKABLE void markDirty(const QRectF& dirtyRect = QRectF());
+
+ Q_INVOKABLE bool save(const QString &filename) const;
+ Q_INVOKABLE QString toDataURL(const QString& type = QLatin1String("image/png")) const;
QImage loadedImage(const QUrl& url);
Q_SIGNALS:
- void paint(QDeclarativeV8Handle context, const QRect &region);
+ void paint(const QRect &region);
void painted();
+ void availableChanged();
+ void contextTypeChanged();
+ void contextChanged();
void canvasSizeChanged();
void tileSizeChanged();
- void renderInThreadChanged();
- void textureChanged();
void canvasWindowChanged();
void renderTargetChanged();
+ void renderStrategyChanged();
void imageLoaded();
+
public Q_SLOTS:
- QString toDataURL(const QString& type = QLatin1String("image/png")) const;
- QDeclarativeV8Handle getContext(const QString & = QLatin1String("2d"));
- void markDirty(const QRectF& region);
- void requestPaint() {markDirty(canvasWindow());}
- // Save current canvas to disk
- bool save(const QString& filename) const;
void loadImage(const QUrl& url);
void unloadImage(const QUrl& url);
bool isImageLoaded(const QUrl& url) const;
bool isImageLoading(const QUrl& url) const;
bool isImageError(const QUrl& url) const;
+
private Q_SLOTS:
- void _doPainting(const QRectF& region);
+ void sceneGraphInitialized();
+ void checkAnimationCallbacks();
+
protected:
- virtual void componentComplete();
- virtual QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
- virtual void geometryChanged(const QRectF &newGeometry,
- const QRectF &oldGeometry);
- virtual void updatePolish();
+ void componentComplete();
+ void itemChange(QQuickItem::ItemChange, const QQuickItem::ItemChangeData &);
+ void updatePolish();
+ QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
+ void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
+
private:
- void createContext();
- void createTexture();
Q_DECLARE_PRIVATE(QQuickCanvasItem)
- friend class QQuickContext2D;
- friend class QQuickContext2DTexture;
+
+ Q_INVOKABLE void delayedCreate();
+ bool createContext(const QString &contextType);
+ void initializeContext(QQuickCanvasContext *context, const QVariantMap &args = QVariantMap());
+ QRect tiledRect(const QRectF &window, const QSize &tileSize);
};
+
QT_END_NAMESPACE
QML_DECLARE_TYPE(QQuickCanvasItem)
diff --git a/src/quick/items/context2d/qquickcontext2dnode.cpp b/src/quick/items/context2d/qquickcanvasitemnode.cpp
index 96959a8115..307d5716e6 100644
--- a/src/quick/items/context2d/qquickcontext2dnode.cpp
+++ b/src/quick/items/context2d/qquickcanvasitemnode.cpp
@@ -39,7 +39,7 @@
**
****************************************************************************/
-#include "qquickcontext2dnode_p.h"
+#include "qquickcanvasitemnode_p.h"
#include <QtQuick/private/qsgcontext_p.h>
#include <QtCore/qmath.h>
@@ -47,9 +47,8 @@
QT_BEGIN_NAMESPACE
-QQuickContext2DNode::QQuickContext2DNode(QQuickCanvasItem* item)
+QQuickCanvasItemNode::QQuickCanvasItemNode()
: QSGGeometryNode()
- , m_item(item)
, m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
, m_texture(0)
, m_size(1, 1)
@@ -59,15 +58,21 @@ QQuickContext2DNode::QQuickContext2DNode(QQuickCanvasItem* item)
setMaterial(&m_materialO);
setOpaqueMaterial(&m_material);
setGeometry(&m_geometry);
- setFlag(UsePreprocess, true);
}
-QQuickContext2DNode::~QQuickContext2DNode()
+QQuickCanvasItemNode::~QQuickCanvasItemNode()
{
delete m_texture;
}
-void QQuickContext2DNode::setSize(const QSizeF& size)
+// Must be called before this node is added to SG
+void QQuickCanvasItemNode::setCallback(QQuickCanvasItemNode::Callback *cb)
+{
+ m_cb = cb;
+ setFlag(UsePreprocess, true);
+}
+
+void QQuickCanvasItemNode::setSize(const QSizeF& size)
{
if (m_size != size) {
m_dirtyGeometry = true;
@@ -75,19 +80,13 @@ void QQuickContext2DNode::setSize(const QSizeF& size)
}
}
-void QQuickContext2DNode::preprocess()
+void QQuickCanvasItemNode::preprocess()
{
- bool doDirty = false;
- QSGDynamicTexture *t = qobject_cast<QSGDynamicTexture *>(m_material.texture());
- if (t) {
- doDirty = t->updateTexture();
- }
- if (doDirty) {
- m_dirtyTexture = true;
- markDirty(DirtyMaterial);
- }
+ if (m_cb)
+ m_cb->process();
}
-void QQuickContext2DNode::setTexture(QQuickContext2DTexture* texture)
+
+void QQuickCanvasItemNode::setTexture(QSGDynamicTexture* texture)
{
if (texture != m_texture) {
m_dirtyTexture = true;
@@ -95,7 +94,7 @@ void QQuickContext2DNode::setTexture(QQuickContext2DTexture* texture)
}
}
-void QQuickContext2DNode::update()
+void QQuickCanvasItemNode::update()
{
if (m_dirtyGeometry)
updateGeometry();
@@ -106,14 +105,14 @@ void QQuickContext2DNode::update()
m_dirtyTexture = false;
}
-void QQuickContext2DNode::updateTexture()
+void QQuickCanvasItemNode::updateTexture()
{
m_material.setTexture(m_texture);
m_materialO.setTexture(m_texture);
markDirty(DirtyMaterial);
}
-void QQuickContext2DNode::updateGeometry()
+void QQuickCanvasItemNode::updateGeometry()
{
QRectF source = m_texture->normalizedTextureSubRect();
QSGGeometry::updateTexturedRectGeometry(&m_geometry,
@@ -121,4 +120,6 @@ void QQuickContext2DNode::updateGeometry()
source);
markDirty(DirtyGeometry);
}
+
QT_END_NAMESPACE
+
diff --git a/src/quick/items/context2d/qquickcontext2dnode_p.h b/src/quick/items/context2d/qquickcanvasitemnode_p.h
index 401782799d..bee221554e 100644
--- a/src/quick/items/context2d/qquickcontext2dnode_p.h
+++ b/src/quick/items/context2d/qquickcanvasitemnode_p.h
@@ -53,28 +53,39 @@ QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
-class QQuickContext2DNode : public QSGGeometryNode
+
+class QSGDynamicTexture;
+
+class QQuickCanvasItemNode : public QSGGeometryNode
{
public:
- QQuickContext2DNode(QQuickCanvasItem* item);
- virtual ~QQuickContext2DNode();
- void setTexture(QQuickContext2DTexture* texture);
+ class Callback {
+ public:
+ virtual void process() const = 0;
+ };
+
+ QQuickCanvasItemNode();
+ ~QQuickCanvasItemNode();
+
+ void setCallback(Callback *cb);
+ void setTexture(QSGDynamicTexture *texture);
void update();
void preprocess();
void setSize(const QSizeF& size);
+
private:
void updateTexture();
void updateGeometry();
- QQuickCanvasItem* m_item;
QSGOpaqueTextureMaterial m_material;
QSGTextureMaterial m_materialO;
QSGGeometry m_geometry;
- QQuickContext2DTexture* m_texture;
+ QSGTexture* m_texture;
QSizeF m_size;
bool m_dirtyGeometry;
bool m_dirtyTexture;
+ Callback *m_cb;
};
QT_END_HEADER
diff --git a/src/quick/items/context2d/qquickcontext2d.cpp b/src/quick/items/context2d/qquickcontext2d.cpp
index dcdf53a70f..667b55dc63 100644
--- a/src/quick/items/context2d/qquickcontext2d.cpp
+++ b/src/quick/items/context2d/qquickcontext2d.cpp
@@ -42,6 +42,7 @@
#include "qquickcontext2d_p.h"
#include "qquickcontext2dcommandbuffer_p.h"
#include "qquickcanvasitem_p.h"
+#include <private/qquickcontext2dtexture_p.h>
#include <private/qquickitem_p.h>
#include <QtQuick/private/qquickshadereffectsource_p.h>
#include <QtGui/qopenglframebufferobject.h>
@@ -67,9 +68,11 @@ QT_BEGIN_NAMESPACE
\qmlclass Context2D QQuickContext2D
\inqmlmodule QtQuick 2
\since QtQuick 2.0
- \brief The Context2D API allows you to draw 2d graphic shapes on the \c Canvas item.
+ \brief The Context2D API allows you to draw 2d graphic shapes on the \c
+ Canvas item.
- The Context2D object can be created by \c Canvas item's \c getContext() method:
+ The Context2D object can be created by \c Canvas item's \c getContext()
+ method:
\code
Canvas {
id:canvas
@@ -79,33 +82,51 @@ QT_BEGIN_NAMESPACE
}
}
\endcode
- The Context2D API implements the same \l {http://www.w3.org/TR/2dcontext}{W3C Canvas 2D Context API standard}
- with some enhanced features.
+ The Context2D API implements the same \l
+ {http://www.w3.org/TR/2dcontext}{W3C Canvas 2D Context API standard} with
+ some enhanced features.
- The Context2D API provides the rendering \bold{context} which defines the methods and attributes needed to draw
- on the \c Canvas item. The following assigns the canvas rendering context to a \c{context}
- variable:
+ The Context2D API provides the rendering \bold{context} which defines the
+ methods and attributes needed to draw on the \c Canvas item. The following
+ assigns the canvas rendering context to a \c{context} variable:
\code
var context = mycanvas.getContext("2d")
\endcode
- The Context2D API renders the canvas as a coordinate system whose origin (0,0) is
- at the top left corner, as shown in the figure below. Coordinates increase along
- the \c{x} axis from left to right and along the \c{y} axis from top to bottom of
- the canvas.
+ The Context2D API renders the canvas as a coordinate system whose origin
+ (0,0) is at the top left corner, as shown in the figure below. Coordinates
+ increase along the \c{x} axis from left to right and along the \c{y} axis
+ from top to bottom of the canvas.
\image qml-item-canvas-context.gif
*/
+QLockedCommandBuffer::QLockedCommandBuffer(QQuickContext2DCommandBuffer *b)
+ : m_buffer(b)
+{
+ m_buffer->lockQueue();
+}
+
+QLockedCommandBuffer::~QLockedCommandBuffer()
+{
+ m_buffer->unlockQueue();
+}
+
+QQuickContext2DCommandBuffer* QLockedCommandBuffer::operator->() const
+{
+ return m_buffer;
+}
+
+
Q_CORE_EXPORT double qstrtod(const char *s00, char const **se, bool *ok);
static const double Q_PI = 3.14159265358979323846; // pi
#define DEGREES(t) ((t) * 180.0 / Q_PI)
-#define CHECK_CONTEXT(r) if (!r || !r->context || !r->context->buffer()) \
+#define CHECK_CONTEXT(r) if (!r || !r->context || !r->context->bufferValid()) \
V8THROW_ERROR("Not a Context2D object");
-#define CHECK_CONTEXT_SETTER(r) if (!r || !r->context || !r->context->buffer()) \
+#define CHECK_CONTEXT_SETTER(r) if (!r || !r->context || !r->context->bufferValid()) \
V8THROW_ERROR_SETTER("Not a Context2D object");
#define qClamp(val, min, max) qMin(qMax(val, min), max)
#define CHECK_RGBA(c) (c == '-' || c == '.' || (c >=0 && c <= 9))
@@ -2603,19 +2624,19 @@ static v8::Handle<v8::Value> ctx2d_imageData_mirror(const v8::Arguments &args)
\qmlmethod void QtQuick2::CanvasImageData::filter(enumeration mode, args)
Filters the image data as defined by one of the following modes:
\list
- \o Canvas.Threshold - converts the image to black and white pixels depending
+ \o context.Threshold - converts the image to black and white pixels depending
if they are above or below the threshold defined by the level parameter.
The level must be between 0.0 (black) and 1.0(white).
If no level is specified, 0.5 is used.
- \o Canvas.Mono - converts the image to the 1-bit per pixel format.
- \o Canvas.GrayScale - converts any colors in the image to grayscale equivalents.
- \o Canvas.Brightness -increase/decrease a fixed \c adjustment value to each pixel's RGB channel value.
- \o Canvas.Invert - sets each pixel to its inverse value.
- \o Canvas.Blur - executes a box blur with the pixel \c radius parameter specifying the range of the blurring for each pixel.
+ \o context.Mono - converts the image to the 1-bit per pixel format.
+ \o context.GrayScale - converts any colors in the image to grayscale equivalents.
+ \o context.Brightness -increase/decrease a fixed \c adjustment value to each pixel's RGB channel value.
+ \o context.Invert - sets each pixel to its inverse value.
+ \o context.Blur - executes a box blur with the pixel \c radius parameter specifying the range of the blurring for each pixel.
the default blur \c radius is 3. This filter also accepts another \c quality parameter, if true, the filter will
execute 3-passes box blur to simulate the Guassian blur. The default \c quality value is false.
- \o Canvas.Opaque - sets the alpha channel to entirely opaque.
- \o Canvas.Convolute - executes a generic {http://en.wikipedia.org/wiki/Convolution}{Convolution} filter, the second
+ \o context.Opaque - sets the alpha channel to entirely opaque.
+ \o context.Convolute - executes a generic {http://en.wikipedia.org/wiki/Convolution}{Convolution} filter, the second
parameter contains the convoluton matrix data as a number array.
\endlist
@@ -2632,12 +2653,12 @@ static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
if (args.Length() >= 1) {
int filterFlag = args[0]->IntegerValue();
switch (filterFlag) {
- case QQuickCanvasItem::Mono :
+ case QQuickContext2D::Mono :
{
r->image = r->image.convertToFormat(QImage::Format_Mono).convertToFormat(QImage::Format_ARGB32_Premultiplied);
}
break;
- case QQuickCanvasItem::GrayScale :
+ case QQuickContext2D::GrayScale :
{
for (int y = 0; y < r->image.height(); ++y) {
QRgb *row = (QRgb*)r->image.scanLine(y);
@@ -2648,7 +2669,7 @@ static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
}
}
break;
- case QQuickCanvasItem::Threshold :
+ case QQuickContext2D::Threshold :
{
qreal threshold = 0.5;
if (args.Length() > 1)
@@ -2664,7 +2685,7 @@ static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
}
}
break;
- case QQuickCanvasItem::Brightness :
+ case QQuickContext2D::Brightness :
{
int adjustment = 1;
if (args.Length() > 1)
@@ -2680,12 +2701,12 @@ static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
}
}
break;
- case QQuickCanvasItem::Invert :
+ case QQuickContext2D::Invert :
{
r->image.invertPixels();
}
break;
- case QQuickCanvasItem::Blur :
+ case QQuickContext2D::Blur :
{
int radius = 3;
bool quality = false;
@@ -2698,7 +2719,7 @@ static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
qt_image_boxblur(r->image, radius, quality);
}
break;
- case QQuickCanvasItem::Opaque :
+ case QQuickContext2D::Opaque :
{
for (int y = 0; y < r->image.height(); ++y) {
QRgb *row = (QRgb*)r->image.scanLine(y);
@@ -2708,7 +2729,7 @@ static v8::Handle<v8::Value> ctx2d_imageData_filter(const v8::Arguments &args)
}
}
break;
- case QQuickCanvasItem::Convolute :
+ case QQuickContext2D::Convolute :
{
if (args.Length() > 1 && args[1]->IsArray()) {
v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(args[1]);
@@ -3297,12 +3318,11 @@ bool QQuickContext2D::isPointInPath(qreal x, qreal y) const
return m_path.contains(QPointF(x, y));
}
-QQuickContext2D::QQuickContext2D(QQuickCanvasItem* item)
- : m_canvas(item)
+QQuickContext2D::QQuickContext2D(QObject *parent)
+ : QQuickCanvasContext(parent)
, m_buffer(new QQuickContext2DCommandBuffer)
, m_v8engine(0)
{
- reset();
}
QQuickContext2D::~QQuickContext2D()
@@ -3315,6 +3335,86 @@ v8::Handle<v8::Object> QQuickContext2D::v8value() const
return m_v8value;
}
+QStringList QQuickContext2D::contextNames() const
+{
+ return QStringList() << QLatin1String("2d");
+}
+
+void QQuickContext2D::init(QQuickCanvasItem *canvasItem, const QVariantMap &args)
+{
+ Q_UNUSED(args);
+
+ m_canvas = canvasItem;
+ m_renderTarget = canvasItem->renderTarget();
+
+ // For the FBO target we only (currently) support Cooperative
+ if (m_renderTarget == QQuickCanvasItem::FramebufferObject) {
+ canvasItem->setRenderStrategy(QQuickCanvasItem::Cooperative);
+ }
+
+ m_renderStrategy = canvasItem->renderStrategy();
+
+ switch (m_renderTarget) {
+ case QQuickCanvasItem::Image:
+ m_texture = new QQuickContext2DImageTexture(m_renderStrategy == QQuickCanvasItem::Threaded); // ?? || Coop
+ break;
+ case QQuickCanvasItem::FramebufferObject:
+ m_texture = new QQuickContext2DFBOTexture;
+ break;
+ }
+
+ m_texture->setItem(canvasItem);
+ m_texture->setCanvasWindow(canvasItem->canvasWindow().toRect());
+ m_texture->setTileSize(canvasItem->tileSize());
+ m_texture->setCanvasSize(canvasItem->canvasSize().toSize());
+ m_texture->setSmooth(canvasItem->smooth());
+
+ connect(m_texture, SIGNAL(textureChanged()), SIGNAL(textureChanged()));
+
+ reset();
+}
+
+void QQuickContext2D::prepare(const QSize& canvasSize, const QSize& tileSize, const QRect& canvasWindow, const QRect& dirtyRect, bool smooth)
+{
+ m_texture->canvasChanged(canvasSize, tileSize, canvasWindow, dirtyRect, smooth);
+}
+
+void QQuickContext2D::flush()
+{
+ switch (m_renderStrategy) {
+ case QQuickCanvasItem::Immediate:
+ // Cause the texture to consume paint commands immediately
+ m_texture->paint();
+ break;
+ case QQuickCanvasItem::Threaded:
+ // wake up thread to consume paint commands
+ m_texture->paint();
+ break;
+ case QQuickCanvasItem::Cooperative:
+ // Add to the update list in SG
+ m_canvas->update(); // FIXME
+ break;
+ }
+}
+
+// On SG render thread
+void QQuickContext2D::sync()
+{
+ if (m_renderStrategy == QQuickCanvasItem::Cooperative)
+ m_texture->paint();
+}
+
+QSGDynamicTexture *QQuickContext2D::texture() const
+{
+ return m_texture;
+}
+
+QImage QQuickContext2D::toImage(const QRectF& bounds)
+{
+ return m_texture->toImage(bounds);
+}
+
+
QQuickContext2DEngineData::QQuickContext2DEngineData(QV8Engine *engine)
{
v8::HandleScope handle_scope;
@@ -3384,6 +3484,15 @@ QQuickContext2DEngineData::QQuickContext2DEngineData(QV8Engine *engine)
ft->PrototypeTemplate()->Set(v8::String::New("getImageData"), V8FUNCTION(ctx2d_getImageData, engine));
ft->PrototypeTemplate()->Set(v8::String::New("putImageData"), V8FUNCTION(ctx2d_putImageData, engine));
+ ft->InstanceTemplate()->Set(v8::String::New("Threshold"), v8::Uint32::New(QQuickContext2D::Threshold), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("Mono"), v8::Uint32::New(QQuickContext2D::Mono), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("GrayScale"), v8::Uint32::New(QQuickContext2D::GrayScale), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("Brightness"), v8::Uint32::New(QQuickContext2D::Brightness), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("Invert"), v8::Uint32::New(QQuickContext2D::Invert), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("Blur"), v8::Uint32::New(QQuickContext2D::Blur), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("Opaque"), v8::Uint32::New(QQuickContext2D::Opaque), v8::ReadOnly);
+ ft->InstanceTemplate()->Set(v8::String::New("Convolute"), v8::Uint32::New(QQuickContext2D::Convolute), v8::ReadOnly);
+
constructorContext = qPersistentNew(ft->GetFunction());
v8::Local<v8::FunctionTemplate> ftGradient = v8::FunctionTemplate::New();
diff --git a/src/quick/items/context2d/qquickcontext2d_p.h b/src/quick/items/context2d/qquickcontext2d_p.h
index ed31c7b79d..6a9c76da57 100644
--- a/src/quick/items/context2d/qquickcontext2d_p.h
+++ b/src/quick/items/context2d/qquickcontext2d_p.h
@@ -45,7 +45,8 @@
#include <QtQuick/qtquickglobal.h>
#include <QtDeclarative/qdeclarative.h>
#include <QtDeclarative/qdeclarativecomponent.h>
-
+#include <private/qquickcanvascontext_p.h>
+#include <private/qquickcanvasitem_p.h>
#include <QtGui/qpainter.h>
#include <QtGui/qpainterpath.h>
#include <QtCore/qstring.h>
@@ -64,11 +65,21 @@ QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
-class QQuickCanvasItem;
class QQuickContext2DCommandBuffer;
+class QQuickContext2DTexture;
class QDeclarativePixmap;
+class QSGTexture;
+
+class QLockedCommandBuffer {
+public:
+ QLockedCommandBuffer(QQuickContext2DCommandBuffer *b);
+ ~QLockedCommandBuffer();
+ QQuickContext2DCommandBuffer* operator->() const;
+private:
+ QQuickContext2DCommandBuffer *m_buffer;
+};
-class Q_QUICK_EXPORT QQuickContext2D
+class Q_QUICK_EXPORT QQuickContext2D : public QQuickCanvasContext
{
public:
enum TextBaseLineType { Alphabetic=0, Top, Middle, Bottom, Hanging};
@@ -104,6 +115,16 @@ public:
GetImageData
};
+ enum ImageFilterMode {
+ Threshold,
+ Mono,
+ GrayScale,
+ Brightness,
+ Invert,
+ Blur,
+ Opaque,
+ Convolute
+ };
struct State {
State()
@@ -154,14 +175,23 @@ public:
QQuickContext2D::TextBaseLineType textBaseline;
};
- QQuickContext2D(QQuickCanvasItem* item);
+ QQuickContext2D(QObject *parent = 0);
~QQuickContext2D();
- inline QQuickCanvasItem* canvas() const {return m_canvas;}
- inline QQuickContext2DCommandBuffer* buffer() const {return m_buffer;}
+ QStringList contextNames() const;
+ void init(QQuickCanvasItem *canvasItem, const QVariantMap &args);
+ void prepare(const QSize& canvasSize, const QSize& tileSize, const QRect& canvasWindow, const QRect& dirtyRect, bool smooth);
+ void flush();
+ void sync();
+ QSGDynamicTexture *texture() const;
+ QImage toImage(const QRectF& bounds);
v8::Handle<v8::Object> v8value() const;
void setV8Engine(QV8Engine *eng);
+
+ QQuickCanvasItem* canvas() const { return m_canvas; }
+ QLockedCommandBuffer buffer() const { return m_buffer; }
+ bool bufferValid() const { return m_buffer != 0; }
void popState();
void pushState();
void reset();
@@ -199,6 +229,9 @@ public:
v8::Handle<v8::Value> m_v8path;
QV8Engine *m_v8engine;
v8::Persistent<v8::Object> m_v8value;
+ QQuickContext2DTexture *m_texture;
+ QQuickCanvasItem::RenderTarget m_renderTarget;
+ QQuickCanvasItem::RenderStrategy m_renderStrategy;
};
diff --git a/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h b/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h
index 76e4960c90..fc4c1a3a9c 100644
--- a/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h
+++ b/src/quick/items/context2d/qquickcontext2dcommandbuffer_p.h
@@ -42,6 +42,7 @@
#ifndef QQUICKCONTEXT2DCOMMANDBUFFER_P_H
#define QQUICKCONTEXT2DCOMMANDBUFFER_P_H
+#include <QtCore/qmutex.h>
#include "qquickcontext2d_p.h"
#include <QtQuick/private/qdeclarativepixmapcache_p.h>
@@ -60,6 +61,9 @@ public:
~QQuickContext2DCommandBuffer();
void reset();
void clear();
+
+ void lockQueue() { queueLock.lock(); }
+ void unlockQueue() { queueLock.unlock(); }
inline int size() {return commands.size();}
inline bool isEmpty() const {return commands.isEmpty(); }
inline bool hasNext() const {return cmdIdx < commands.size(); }
@@ -257,6 +261,7 @@ private:
QVector<QBrush> brushes;
QVector<QPainterPath> pathes;
QVector<QImage> images;
+ QMutex queueLock;
};
QT_END_HEADER
diff --git a/src/quick/items/context2d/qquickcontext2dtexture.cpp b/src/quick/items/context2d/qquickcontext2dtexture.cpp
index 61e6f27675..5d0c0ab63e 100644
--- a/src/quick/items/context2d/qquickcontext2dtexture.cpp
+++ b/src/quick/items/context2d/qquickcontext2dtexture.cpp
@@ -51,6 +51,9 @@
#include <QOpenGLFramebufferObjectFormat>
#include <QtCore/QThread>
+
+QT_BEGIN_NAMESPACE
+
#define QT_MINIMUM_FBO_SIZE 64
static inline int qt_next_power_of_two(int v)
@@ -70,8 +73,7 @@ Q_GLOBAL_STATIC(QThread, globalCanvasThreadRenderInstance)
QQuickContext2DTexture::QQuickContext2DTexture()
- : QSGDynamicTexture()
- , m_context(0)
+ : m_context(0)
, m_item(0)
, m_canvasSize(QSize(1, 1))
, m_tileSize(QSize(1, 1))
@@ -98,10 +100,12 @@ QSize QQuickContext2DTexture::textureSize() const
void QQuickContext2DTexture::markDirtyTexture()
{
- lock();
+ const bool inGrab = m_doGrabImage;
+
m_dirtyTexture = true;
- unlock();
- emit textureChanged();
+ updateTexture();
+ if (!inGrab)
+ emit textureChanged();
}
bool QQuickContext2DTexture::setCanvasSize(const QSize &size)
@@ -131,20 +135,9 @@ void QQuickContext2DTexture::setSmooth(bool smooth)
void QQuickContext2DTexture::setItem(QQuickCanvasItem* item)
{
- if (!item) {
- lock();
- m_item = 0;
- m_context = 0;
- unlock();
- wake();
- } else if (m_item != item) {
- lock();
- m_item = item;
- m_context = item->context();
- m_state = m_context->state;
- unlock();
- connect(this, SIGNAL(textureChanged()), m_item, SIGNAL(painted()));
- }
+ m_item = item;
+ m_context = (QQuickContext2D*)item->rawContext(); // FIXME
+ m_state = m_context->state;
}
bool QQuickContext2DTexture::setCanvasWindow(const QRect& r)
@@ -193,37 +186,20 @@ void QQuickContext2DTexture::canvasChanged(const QSize& canvasSize, const QSize&
m_tiledCanvas = true;
}
- bool doDirty = false;
if (dirtyRect.isValid())
- doDirty = setDirtyRect(dirtyRect);
-
- bool windowChanged = setCanvasWindow(canvasWindow);
- if (windowChanged || doDirty) {
- if (m_threadRendering)
- QMetaObject::invokeMethod(this, "paint", Qt::QueuedConnection);
- else if (supportDirectRendering()) {
- QMetaObject::invokeMethod(this, "paint", Qt::DirectConnection);
- }
- }
+ setDirtyRect(dirtyRect);
setSmooth(smooth);
+
unlock();
}
void QQuickContext2DTexture::paintWithoutTiles()
{
- QQuickContext2DCommandBuffer* ccb = m_context->buffer();
+ QLockedCommandBuffer ccb = m_context->buffer();
- if (ccb->isEmpty() && m_threadRendering && !m_doGrabImage) {
- lock();
- if (m_item)
- QMetaObject::invokeMethod(m_item, "_doPainting", Qt::QueuedConnection, Q_ARG(QRectF, QRectF(0, 0, m_canvasSize.width(), m_canvasSize.height())));
- wait();
- unlock();
- }
- if (ccb->isEmpty()) {
+ if (ccb->isEmpty())
return;
- }
QPaintDevice* device = beginPainting();
if (!device) {
@@ -240,11 +216,13 @@ void QQuickContext2DTexture::paintWithoutTiles()
p.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing
| QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, false);
p.setCompositionMode(QPainter::CompositionMode_SourceOver);
- ccb->replay(&p, m_state);
+ ccb->replay(&p, m_state);
ccb->clear();
- markDirtyTexture();
+
endPainting();
+
+ markDirtyTexture();
}
bool QQuickContext2DTexture::canvasDestroyed()
@@ -261,6 +239,12 @@ void QQuickContext2DTexture::paint()
if (canvasDestroyed())
return;
+ if (m_threadRendering && QThread::currentThread() != globalCanvasThreadRenderInstance()) {
+ Q_ASSERT(thread() == globalCanvasThreadRenderInstance());
+ QMetaObject::invokeMethod(this, "paint", Qt::QueuedConnection);
+ return;
+ }
+
if (!m_tiledCanvas) {
paintWithoutTiles();
} else {
@@ -282,19 +266,11 @@ void QQuickContext2DTexture::paint()
}
}
unlock();
-
- if (dirtyRect.isValid()) {
- lock();
- if (m_item)
- QMetaObject::invokeMethod(m_item, "_doPainting", Qt::QueuedConnection, Q_ARG(QRectF, dirtyRect));
- wait();
- unlock();
- }
}
if (beginPainting()) {
QQuickContext2D::State oldState = m_state;
- QQuickContext2DCommandBuffer* ccb = m_context->buffer();
+ QLockedCommandBuffer ccb = m_context->buffer();
foreach (QQuickContext2DTile* tile, m_tiles) {
bool dirtyTile = false, dirtyCanvas = false, smooth = false;
@@ -485,10 +461,6 @@ int QQuickContext2DFBOTexture::textureId() const
bool QQuickContext2DFBOTexture::updateTexture()
{
- if (!m_context->buffer()->isEmpty()) {
- paint();
- }
-
bool textureUpdated = m_dirtyTexture;
m_dirtyTexture = false;
@@ -530,15 +502,15 @@ bool QQuickContext2DFBOTexture::doMultisampling() const
QImage QQuickContext2DFBOTexture::toImage(const QRectF& region)
{
-#define QML_CONTEXT2D_WAIT_MAX 5000
+ const unsigned long context2d_wait_max = 5000;
m_doGrabImage = true;
- if (m_item)
+ if (m_item) // forces a call to updatePaintNode (repaints)
m_item->update();
QImage grabbed;
m_mutex.lock();
- bool ok = m_condition.wait(&m_mutex, QML_CONTEXT2D_WAIT_MAX);
+ bool ok = m_condition.wait(&m_mutex, context2d_wait_max);
if (!ok)
grabbed = QImage();
@@ -649,7 +621,7 @@ QQuickContext2DImageTexture::QQuickContext2DImageTexture(bool threadRendering)
moveToThread(thread);
if (!thread->isRunning()) {
- qAddPostRoutine(qt_quit_context2d_render_thread);
+ qAddPostRoutine(qt_quit_context2d_render_thread); // XXX: change this method
thread->start();
}
}
@@ -705,13 +677,11 @@ void QQuickContext2DImageTexture::bind()
bool QQuickContext2DImageTexture::updateTexture()
{
- lock();
bool textureUpdated = m_dirtyTexture;
if (m_dirtyTexture) {
m_texture->setImage(m_image);
m_dirtyTexture = false;
}
- unlock();
return textureUpdated;
}
@@ -728,9 +698,9 @@ void QQuickContext2DImageTexture::grabImage(const QRect& r)
m_grabedImage = m_image.copy(r);
}
-QImage QQuickContext2DImageTexture::toImage(const QRectF& region)
+QImage QQuickContext2DImageTexture::toImage(const QRectF& rect)
{
- QRect r = region.isValid() ? region.toRect() : QRect(QPoint(0, 0), m_canvasWindow.size());
+ QRect r = rect.isValid() ? rect.toRect() : QRect(QPoint(0, 0), m_canvasWindow.size());
if (threadRendering()) {
wake();
QMetaObject::invokeMethod(this, "grabImage", Qt::BlockingQueuedConnection, Q_ARG(QRect, r));
@@ -744,17 +714,16 @@ QImage QQuickContext2DImageTexture::toImage(const QRectF& region)
QPaintDevice* QQuickContext2DImageTexture::beginPainting()
{
- QQuickContext2DTexture::beginPainting();
+ QQuickContext2DTexture::beginPainting();
if (m_canvasWindow.size().isEmpty())
return 0;
- lock();
if (m_image.size() != m_canvasWindow.size()) {
m_image = QImage(m_canvasWindow.size(), QImage::Format_ARGB32_Premultiplied);
m_image.fill(0x00000000);
}
- unlock();
+
return &m_image;
}
@@ -776,3 +745,6 @@ void QQuickContext2DImageTexture::compositeTile(QQuickContext2DTile* tile)
unlock();
}
}
+
+QT_END_NAMESPACE
+
diff --git a/src/quick/items/context2d/qquickcontext2dtile.cpp b/src/quick/items/context2d/qquickcontext2dtile.cpp
index a71490e939..284cdcef83 100644
--- a/src/quick/items/context2d/qquickcontext2dtile.cpp
+++ b/src/quick/items/context2d/qquickcontext2dtile.cpp
@@ -45,6 +45,8 @@
#include <QOpenGLFramebufferObjectFormat>
#include <QOpenGLPaintDevice>
+QT_BEGIN_NAMESPACE
+
QQuickContext2DTile::QQuickContext2DTile()
: m_dirty(true)
, m_rect(QRect(0, 0, 1, 1))
@@ -163,3 +165,6 @@ void QQuickContext2DImageTile::setRect(const QRect& r)
}
m_device = &m_image;
}
+
+QT_END_NAMESPACE
+
diff --git a/tests/auto/qtquick2/qquickcanvasitem/data/tst_canvas.qml b/tests/auto/qtquick2/qquickcanvasitem/data/tst_canvas.qml
index 98ddab66b5..a00ccc3c3f 100644
--- a/tests/auto/qtquick2/qquickcanvasitem/data/tst_canvas.qml
+++ b/tests/auto/qtquick2/qquickcanvasitem/data/tst_canvas.qml
@@ -11,6 +11,7 @@ Rectangle {
id:c
width:100;height:100
onPaint: {
+ var context = getContext("2d");
context.fillStyle = "red";
context.fillRect(0, 0, 100, 100);
}
@@ -18,27 +19,31 @@ Rectangle {
property int paintedCount:spyPainted.count
property int canvasSizeChangedCount:spyCanvasSizeChanged.count
property int tileSizeChangedCount:spyTileSizeChanged.count
- property int renderInThreadChangedCount:spyRenderInThreadChanged.count
+ property int renderStrategyChangedCount:spyRenderStrategyChanged.count
property int canvasWindowChangedCount:spyCanvasWindowChanged.count
property int renderTargetChangedCount:spyRenderTargetChanged.count
property int imageLoadedCount:spyImageLoaded.count
+ property int availableChangedCount:spyAvailableChanged.count
SignalSpy {id: spyPaint;target:c;signalName: "paint"}
SignalSpy {id: spyPainted;target:c;signalName: "painted"}
SignalSpy {id: spyCanvasSizeChanged;target:c;signalName: "canvasSizeChanged"}
SignalSpy {id: spyTileSizeChanged;target:c;signalName: "tileSizeChanged"}
- SignalSpy {id: spyRenderInThreadChanged;target:c;signalName: "renderInThreadChanged"}
+ SignalSpy {id: spyRenderStrategyChanged;target:c;signalName: "renderStrategyChanged"}
SignalSpy {id: spyCanvasWindowChanged;target:c;signalName: "canvasWindowChanged"}
SignalSpy {id: spyRenderTargetChanged;target:c;signalName: "renderTargetChanged"}
SignalSpy {id: spyImageLoaded;target:c;signalName: "imageLoaded"}
+ SignalSpy {id: spyAvailableChanged;target:c;signalName: "availableChanged"}
}
}
TestCase {
name: "Canvas"; when: windowShown
function test_canvasSize() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
//by default canvasSize is same with canvas' actual size
// when canvas size changes, canvasSize should be changed as well.
@@ -74,8 +79,10 @@ Rectangle {
c.destroy();
}
function test_tileSize() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
compare(c.tileSize.width, c.width);
compare(c.tileSize.height, c.height);
@@ -109,8 +116,10 @@ Rectangle {
}
function test_canvasWindow() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
compare(c.canvasWindow.x, 0);
compare(c.canvasWindow.y, 0);
compare(c.canvasWindow.width, c.width);
@@ -135,34 +144,22 @@ Rectangle {
c.destroy();
}
- function test_renderTargetAndThread() {
- var c = canvas.createObject();
+ function test_renderTargetAndStrategy() {
+ var c = canvas.createObject(container);
verify(c);
-
- compare(c.renderTarget, Canvas.FramebufferObject);
- verify(!c.renderInThread);
- c.renderTarget = Canvas.Image;
- compare(c.renderTargetChangedCount, 1);
- compare(c.renderInThreadChangedCount, 0);
+ wait(100);
+ verify(c.availableChangedCount, 1);
compare(c.renderTarget, Canvas.Image);
- verify(!c.renderInThread);
- c.renderInThread = true;
- verify(c.renderInThread);
- compare(c.renderTargetChangedCount, 1);
- compare(c.renderInThreadChangedCount, 1);
-
- ignoreWarning("Canvas: render target does not support thread rendering, force to non-thread rendering mode.");
- c.renderTarget = Canvas.FramebufferObject;
- verify(!c.renderInThread);
- compare(c.renderTargetChangedCount, 2);
- compare(c.renderInThreadChangedCount, 2);
+ compare(c.renderStrategy, Canvas.Threaded);
c.destroy();
}
function test_save() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
c.renderTarget = Canvas.Image;
c.requestPaint();
@@ -188,16 +185,16 @@ Rectangle {
}
function test_toDataURL(data) {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
- c.renderTarget = Canvas.Image;
- var ctx = c.getContext();
+ var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, c.width, c.height);
-
- c.requestPaint();
wait(100);
+
var dataUrl = c.toDataURL();
verify(dataUrl != "data:,");
dataUrl = c.toDataURL("image/invalid");
@@ -205,12 +202,13 @@ Rectangle {
dataUrl = c.toDataURL(data.mimeType);
verify(dataUrl != "data:,");
+
ctx.save();
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, c.width, c.height);
ctx.restore();
- c.requestPaint();
wait(100);
+
var dataUrl2 = c.toDataURL(data.mimeType);
verify (dataUrl2 != "data:,");
verify (dataUrl2 != dataUrl);
@@ -218,12 +216,14 @@ Rectangle {
}
function test_paint() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
c.renderTarget = Canvas.Image;
- c.renderInThread = true;
- var ctx = c.getContext();
+ c.renderStrategy = Canvas.Immediate;
+ var ctx = c.getContext("2d");
ctx.fillRect(0, 0, c.width, c.height);
c.toDataURL();
wait(100);
@@ -234,8 +234,10 @@ Rectangle {
}
function test_loadImage() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
c.loadImage("red.png");
wait(200);
@@ -253,10 +255,12 @@ Rectangle {
}
function test_getContext() {
- var c = canvas.createObject();
+ var c = canvas.createObject(container);
verify(c);
+ wait(100);
+ verify(c.availableChangedCount, 1);
- var ctx = c.getContext();
+ var ctx = c.getContext("2d");
verify(ctx);
compare(ctx.canvas, c);
ctx = c.getContext('2d');
diff --git a/tests/auto/qtquick2/qquickcanvasitem/data/tst_context.qml b/tests/auto/qtquick2/qquickcanvasitem/data/tst_context.qml
new file mode 100644
index 0000000000..b72e755ed9
--- /dev/null
+++ b/tests/auto/qtquick2/qquickcanvasitem/data/tst_context.qml
@@ -0,0 +1,73 @@
+
+import QtQuick 2.0
+import QtTest 1.0
+
+Canvas {
+ id: canvas
+ width: 1
+ height: 1
+ contextType: "2d"
+
+ property var contextInPaint
+
+ SignalSpy {
+ id: paintedSpy
+ target: canvas
+ signalName: "paint"
+ }
+
+ SignalSpy {
+ id: contextSpy
+ target: canvas
+ signalName: "contextChanged"
+ }
+
+ onPaint: {
+ contextInPaint = context;
+ }
+
+ TestCase {
+ name: "ContextTypeStored"
+ when: windowShown
+
+ function test_contextType() {
+ compare(canvas.contextType, "2d");
+ }
+ }
+
+ TestCase {
+ name: "ContextValidWhenTypePredefined"
+ when: canvas.available
+
+ function test_context() {
+ // Wait for the context to become active
+ wait(100);
+ compare(contextSpy.count, 1);
+
+ // Context is available
+ verify(canvas.context)
+ }
+
+ function test_contextIsConsistent() {
+ // Wait for the context to become active
+ wait(100);
+ compare(contextSpy.count, 1);
+
+ // getContext("2d") is the same as the context property
+ compare(canvas.getContext("2d"), canvas.context);
+ }
+
+ function test_paintHadContext() {
+ // Make there was a paint signal
+ wait(100);
+ verify(paintedSpy.count, 1)
+
+ // Paint was called with a valid context when contextType is
+ // specified
+ verify(canvas.contextInPaint)
+
+ // paints context was the correct one
+ compare(canvas.contextInPaint, canvas.getContext("2d"));
+ }
+ }
+}
diff --git a/tests/auto/qtquick2/qquickcanvasitem/data/tst_fillrect.qml b/tests/auto/qtquick2/qquickcanvasitem/data/tst_fillrect.qml
index 2061647268..08197816e9 100644
--- a/tests/auto/qtquick2/qquickcanvasitem/data/tst_fillrect.qml
+++ b/tests/auto/qtquick2/qquickcanvasitem/data/tst_fillrect.qml
@@ -2,15 +2,18 @@ import QtQuick 2.0
import QtTest 1.0
Canvas {
- id:canvas; width:1;height:1; renderTarget:Canvas.Image
- onPaint: {
- context.fillStyle = "red";
- context.fillRect(0, 0, canvas.width, canvas.height);
- }
+ id:canvas; width:1;height:1;
+ renderTarget:Canvas.Image
+ renderStrategy: Canvas.Immediate
+
TestCase {
- name: "FillRect"; when: windowShown
+ name: "FillRect"; when: canvas.available
+
function test_fillRect() {
var ctx = canvas.getContext('2d');
+ ctx.fillStyle = "red";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+
var imageData = ctx.getImageData(0, 0, 1, 1);
var d = imageData.data;
verify(d.length == 4);
@@ -20,4 +23,4 @@ Canvas {
verify(d[3] == 255);
}
}
-} \ No newline at end of file
+}
diff --git a/tests/auto/qtquick2/qquickcanvasitem/qquickcanvasitem.pro b/tests/auto/qtquick2/qquickcanvasitem/qquickcanvasitem.pro
index 141e477416..93539dab15 100644
--- a/tests/auto/qtquick2/qquickcanvasitem/qquickcanvasitem.pro
+++ b/tests/auto/qtquick2/qquickcanvasitem/qquickcanvasitem.pro
@@ -27,7 +27,8 @@ OTHER_FILES += \
data/tst_pixel.qml \
data/tst_gradient.qml \
data/tst_arcto.qml \
- data/tst_arc.qml
+ data/tst_arc.qml \
+ data/tst_context.qml